1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements semantic analysis for C++ declarations. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/AST/ASTConsumer.h" 14 #include "clang/AST/ASTContext.h" 15 #include "clang/AST/ASTLambda.h" 16 #include "clang/AST/ASTMutationListener.h" 17 #include "clang/AST/CXXInheritance.h" 18 #include "clang/AST/CharUnits.h" 19 #include "clang/AST/ComparisonCategories.h" 20 #include "clang/AST/EvaluatedExprVisitor.h" 21 #include "clang/AST/ExprCXX.h" 22 #include "clang/AST/RecordLayout.h" 23 #include "clang/AST/RecursiveASTVisitor.h" 24 #include "clang/AST/StmtVisitor.h" 25 #include "clang/AST/TypeLoc.h" 26 #include "clang/AST/TypeOrdering.h" 27 #include "clang/Basic/AttributeCommonInfo.h" 28 #include "clang/Basic/PartialDiagnostic.h" 29 #include "clang/Basic/TargetInfo.h" 30 #include "clang/Lex/LiteralSupport.h" 31 #include "clang/Lex/Preprocessor.h" 32 #include "clang/Sema/CXXFieldCollector.h" 33 #include "clang/Sema/DeclSpec.h" 34 #include "clang/Sema/Initialization.h" 35 #include "clang/Sema/Lookup.h" 36 #include "clang/Sema/ParsedTemplate.h" 37 #include "clang/Sema/Scope.h" 38 #include "clang/Sema/ScopeInfo.h" 39 #include "clang/Sema/SemaInternal.h" 40 #include "clang/Sema/Template.h" 41 #include "llvm/ADT/ScopeExit.h" 42 #include "llvm/ADT/SmallString.h" 43 #include "llvm/ADT/STLExtras.h" 44 #include "llvm/ADT/StringExtras.h" 45 #include <map> 46 #include <set> 47 48 using namespace clang; 49 50 //===----------------------------------------------------------------------===// 51 // CheckDefaultArgumentVisitor 52 //===----------------------------------------------------------------------===// 53 54 namespace { 55 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 56 /// the default argument of a parameter to determine whether it 57 /// contains any ill-formed subexpressions. For example, this will 58 /// diagnose the use of local variables or parameters within the 59 /// default argument expression. 60 class CheckDefaultArgumentVisitor 61 : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> { 62 Sema &S; 63 const Expr *DefaultArg; 64 65 public: 66 CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg) 67 : S(S), DefaultArg(DefaultArg) {} 68 69 bool VisitExpr(const Expr *Node); 70 bool VisitDeclRefExpr(const DeclRefExpr *DRE); 71 bool VisitCXXThisExpr(const CXXThisExpr *ThisE); 72 bool VisitLambdaExpr(const LambdaExpr *Lambda); 73 bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE); 74 }; 75 76 /// VisitExpr - Visit all of the children of this expression. 77 bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) { 78 bool IsInvalid = false; 79 for (const Stmt *SubStmt : Node->children()) 80 IsInvalid |= Visit(SubStmt); 81 return IsInvalid; 82 } 83 84 /// VisitDeclRefExpr - Visit a reference to a declaration, to 85 /// determine whether this declaration can be used in the default 86 /// argument expression. 87 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) { 88 const NamedDecl *Decl = DRE->getDecl(); 89 if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) { 90 // C++ [dcl.fct.default]p9: 91 // [...] parameters of a function shall not be used in default 92 // argument expressions, even if they are not evaluated. [...] 93 // 94 // C++17 [dcl.fct.default]p9 (by CWG 2082): 95 // [...] A parameter shall not appear as a potentially-evaluated 96 // expression in a default argument. [...] 97 // 98 if (DRE->isNonOdrUse() != NOUR_Unevaluated) 99 return S.Diag(DRE->getBeginLoc(), 100 diag::err_param_default_argument_references_param) 101 << Param->getDeclName() << DefaultArg->getSourceRange(); 102 } else if (const auto *VDecl = dyn_cast<VarDecl>(Decl)) { 103 // C++ [dcl.fct.default]p7: 104 // Local variables shall not be used in default argument 105 // expressions. 106 // 107 // C++17 [dcl.fct.default]p7 (by CWG 2082): 108 // A local variable shall not appear as a potentially-evaluated 109 // expression in a default argument. 110 // 111 // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346): 112 // Note: A local variable cannot be odr-used (6.3) in a default argument. 113 // 114 if (VDecl->isLocalVarDecl() && !DRE->isNonOdrUse()) 115 return S.Diag(DRE->getBeginLoc(), 116 diag::err_param_default_argument_references_local) 117 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 118 } 119 120 return false; 121 } 122 123 /// VisitCXXThisExpr - Visit a C++ "this" expression. 124 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) { 125 // C++ [dcl.fct.default]p8: 126 // The keyword this shall not be used in a default argument of a 127 // member function. 128 return S.Diag(ThisE->getBeginLoc(), 129 diag::err_param_default_argument_references_this) 130 << ThisE->getSourceRange(); 131 } 132 133 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr( 134 const PseudoObjectExpr *POE) { 135 bool Invalid = false; 136 for (const Expr *E : POE->semantics()) { 137 // Look through bindings. 138 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) { 139 E = OVE->getSourceExpr(); 140 assert(E && "pseudo-object binding without source expression?"); 141 } 142 143 Invalid |= Visit(E); 144 } 145 return Invalid; 146 } 147 148 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) { 149 // C++11 [expr.lambda.prim]p13: 150 // A lambda-expression appearing in a default argument shall not 151 // implicitly or explicitly capture any entity. 152 if (Lambda->capture_begin() == Lambda->capture_end()) 153 return false; 154 155 return S.Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg); 156 } 157 } // namespace 158 159 void 160 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc, 161 const CXXMethodDecl *Method) { 162 // If we have an MSAny spec already, don't bother. 163 if (!Method || ComputedEST == EST_MSAny) 164 return; 165 166 const FunctionProtoType *Proto 167 = Method->getType()->getAs<FunctionProtoType>(); 168 Proto = Self->ResolveExceptionSpec(CallLoc, Proto); 169 if (!Proto) 170 return; 171 172 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 173 174 // If we have a throw-all spec at this point, ignore the function. 175 if (ComputedEST == EST_None) 176 return; 177 178 if (EST == EST_None && Method->hasAttr<NoThrowAttr>()) 179 EST = EST_BasicNoexcept; 180 181 switch (EST) { 182 case EST_Unparsed: 183 case EST_Uninstantiated: 184 case EST_Unevaluated: 185 llvm_unreachable("should not see unresolved exception specs here"); 186 187 // If this function can throw any exceptions, make a note of that. 188 case EST_MSAny: 189 case EST_None: 190 // FIXME: Whichever we see last of MSAny and None determines our result. 191 // We should make a consistent, order-independent choice here. 192 ClearExceptions(); 193 ComputedEST = EST; 194 return; 195 case EST_NoexceptFalse: 196 ClearExceptions(); 197 ComputedEST = EST_None; 198 return; 199 // FIXME: If the call to this decl is using any of its default arguments, we 200 // need to search them for potentially-throwing calls. 201 // If this function has a basic noexcept, it doesn't affect the outcome. 202 case EST_BasicNoexcept: 203 case EST_NoexceptTrue: 204 case EST_NoThrow: 205 return; 206 // If we're still at noexcept(true) and there's a throw() callee, 207 // change to that specification. 208 case EST_DynamicNone: 209 if (ComputedEST == EST_BasicNoexcept) 210 ComputedEST = EST_DynamicNone; 211 return; 212 case EST_DependentNoexcept: 213 llvm_unreachable( 214 "should not generate implicit declarations for dependent cases"); 215 case EST_Dynamic: 216 break; 217 } 218 assert(EST == EST_Dynamic && "EST case not considered earlier."); 219 assert(ComputedEST != EST_None && 220 "Shouldn't collect exceptions when throw-all is guaranteed."); 221 ComputedEST = EST_Dynamic; 222 // Record the exceptions in this function's exception specification. 223 for (const auto &E : Proto->exceptions()) 224 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second) 225 Exceptions.push_back(E); 226 } 227 228 void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) { 229 if (!S || ComputedEST == EST_MSAny) 230 return; 231 232 // FIXME: 233 // 234 // C++0x [except.spec]p14: 235 // [An] implicit exception-specification specifies the type-id T if and 236 // only if T is allowed by the exception-specification of a function directly 237 // invoked by f's implicit definition; f shall allow all exceptions if any 238 // function it directly invokes allows all exceptions, and f shall allow no 239 // exceptions if every function it directly invokes allows no exceptions. 240 // 241 // Note in particular that if an implicit exception-specification is generated 242 // for a function containing a throw-expression, that specification can still 243 // be noexcept(true). 244 // 245 // Note also that 'directly invoked' is not defined in the standard, and there 246 // is no indication that we should only consider potentially-evaluated calls. 247 // 248 // Ultimately we should implement the intent of the standard: the exception 249 // specification should be the set of exceptions which can be thrown by the 250 // implicit definition. For now, we assume that any non-nothrow expression can 251 // throw any exception. 252 253 if (Self->canThrow(S)) 254 ComputedEST = EST_None; 255 } 256 257 ExprResult Sema::ConvertParamDefaultArgument(const ParmVarDecl *Param, 258 Expr *Arg, 259 SourceLocation EqualLoc) { 260 if (RequireCompleteType(Param->getLocation(), Param->getType(), 261 diag::err_typecheck_decl_incomplete_type)) 262 return true; 263 264 // C++ [dcl.fct.default]p5 265 // A default argument expression is implicitly converted (clause 266 // 4) to the parameter type. The default argument expression has 267 // the same semantic constraints as the initializer expression in 268 // a declaration of a variable of the parameter type, using the 269 // copy-initialization semantics (8.5). 270 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 271 Param); 272 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 273 EqualLoc); 274 InitializationSequence InitSeq(*this, Entity, Kind, Arg); 275 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); 276 if (Result.isInvalid()) 277 return true; 278 Arg = Result.getAs<Expr>(); 279 280 CheckCompletedExpr(Arg, EqualLoc); 281 Arg = MaybeCreateExprWithCleanups(Arg); 282 283 return Arg; 284 } 285 286 void Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 287 SourceLocation EqualLoc) { 288 // Add the default argument to the parameter 289 Param->setDefaultArg(Arg); 290 291 // We have already instantiated this parameter; provide each of the 292 // instantiations with the uninstantiated default argument. 293 UnparsedDefaultArgInstantiationsMap::iterator InstPos 294 = UnparsedDefaultArgInstantiations.find(Param); 295 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 296 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 297 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 298 299 // We're done tracking this parameter's instantiations. 300 UnparsedDefaultArgInstantiations.erase(InstPos); 301 } 302 } 303 304 /// ActOnParamDefaultArgument - Check whether the default argument 305 /// provided for a function parameter is well-formed. If so, attach it 306 /// to the parameter declaration. 307 void 308 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 309 Expr *DefaultArg) { 310 if (!param || !DefaultArg) 311 return; 312 313 ParmVarDecl *Param = cast<ParmVarDecl>(param); 314 UnparsedDefaultArgLocs.erase(Param); 315 316 auto Fail = [&] { 317 Param->setInvalidDecl(); 318 Param->setDefaultArg(new (Context) OpaqueValueExpr( 319 EqualLoc, Param->getType().getNonReferenceType(), VK_RValue)); 320 }; 321 322 // Default arguments are only permitted in C++ 323 if (!getLangOpts().CPlusPlus) { 324 Diag(EqualLoc, diag::err_param_default_argument) 325 << DefaultArg->getSourceRange(); 326 return Fail(); 327 } 328 329 // Check for unexpanded parameter packs. 330 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 331 return Fail(); 332 } 333 334 // C++11 [dcl.fct.default]p3 335 // A default argument expression [...] shall not be specified for a 336 // parameter pack. 337 if (Param->isParameterPack()) { 338 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack) 339 << DefaultArg->getSourceRange(); 340 // Recover by discarding the default argument. 341 Param->setDefaultArg(nullptr); 342 return; 343 } 344 345 ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc); 346 if (Result.isInvalid()) 347 return Fail(); 348 349 DefaultArg = Result.getAs<Expr>(); 350 351 // Check that the default argument is well-formed 352 CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg); 353 if (DefaultArgChecker.Visit(DefaultArg)) 354 return Fail(); 355 356 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 357 } 358 359 /// ActOnParamUnparsedDefaultArgument - We've seen a default 360 /// argument for a function parameter, but we can't parse it yet 361 /// because we're inside a class definition. Note that this default 362 /// argument will be parsed later. 363 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 364 SourceLocation EqualLoc, 365 SourceLocation ArgLoc) { 366 if (!param) 367 return; 368 369 ParmVarDecl *Param = cast<ParmVarDecl>(param); 370 Param->setUnparsedDefaultArg(); 371 UnparsedDefaultArgLocs[Param] = ArgLoc; 372 } 373 374 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 375 /// the default argument for the parameter param failed. 376 void Sema::ActOnParamDefaultArgumentError(Decl *param, 377 SourceLocation EqualLoc) { 378 if (!param) 379 return; 380 381 ParmVarDecl *Param = cast<ParmVarDecl>(param); 382 Param->setInvalidDecl(); 383 UnparsedDefaultArgLocs.erase(Param); 384 Param->setDefaultArg(new(Context) 385 OpaqueValueExpr(EqualLoc, 386 Param->getType().getNonReferenceType(), 387 VK_RValue)); 388 } 389 390 /// CheckExtraCXXDefaultArguments - Check for any extra default 391 /// arguments in the declarator, which is not a function declaration 392 /// or definition and therefore is not permitted to have default 393 /// arguments. This routine should be invoked for every declarator 394 /// that is not a function declaration or definition. 395 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 396 // C++ [dcl.fct.default]p3 397 // A default argument expression shall be specified only in the 398 // parameter-declaration-clause of a function declaration or in a 399 // template-parameter (14.1). It shall not be specified for a 400 // parameter pack. If it is specified in a 401 // parameter-declaration-clause, it shall not occur within a 402 // declarator or abstract-declarator of a parameter-declaration. 403 bool MightBeFunction = D.isFunctionDeclarationContext(); 404 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 405 DeclaratorChunk &chunk = D.getTypeObject(i); 406 if (chunk.Kind == DeclaratorChunk::Function) { 407 if (MightBeFunction) { 408 // This is a function declaration. It can have default arguments, but 409 // keep looking in case its return type is a function type with default 410 // arguments. 411 MightBeFunction = false; 412 continue; 413 } 414 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e; 415 ++argIdx) { 416 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param); 417 if (Param->hasUnparsedDefaultArg()) { 418 std::unique_ptr<CachedTokens> Toks = 419 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens); 420 SourceRange SR; 421 if (Toks->size() > 1) 422 SR = SourceRange((*Toks)[1].getLocation(), 423 Toks->back().getLocation()); 424 else 425 SR = UnparsedDefaultArgLocs[Param]; 426 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 427 << SR; 428 } else if (Param->getDefaultArg()) { 429 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 430 << Param->getDefaultArg()->getSourceRange(); 431 Param->setDefaultArg(nullptr); 432 } 433 } 434 } else if (chunk.Kind != DeclaratorChunk::Paren) { 435 MightBeFunction = false; 436 } 437 } 438 } 439 440 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { 441 return std::any_of(FD->param_begin(), FD->param_end(), [](ParmVarDecl *P) { 442 return P->hasDefaultArg() && !P->hasInheritedDefaultArg(); 443 }); 444 } 445 446 /// MergeCXXFunctionDecl - Merge two declarations of the same C++ 447 /// function, once we already know that they have the same 448 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an 449 /// error, false otherwise. 450 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 451 Scope *S) { 452 bool Invalid = false; 453 454 // The declaration context corresponding to the scope is the semantic 455 // parent, unless this is a local function declaration, in which case 456 // it is that surrounding function. 457 DeclContext *ScopeDC = New->isLocalExternDecl() 458 ? New->getLexicalDeclContext() 459 : New->getDeclContext(); 460 461 // Find the previous declaration for the purpose of default arguments. 462 FunctionDecl *PrevForDefaultArgs = Old; 463 for (/**/; PrevForDefaultArgs; 464 // Don't bother looking back past the latest decl if this is a local 465 // extern declaration; nothing else could work. 466 PrevForDefaultArgs = New->isLocalExternDecl() 467 ? nullptr 468 : PrevForDefaultArgs->getPreviousDecl()) { 469 // Ignore hidden declarations. 470 if (!LookupResult::isVisible(*this, PrevForDefaultArgs)) 471 continue; 472 473 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) && 474 !New->isCXXClassMember()) { 475 // Ignore default arguments of old decl if they are not in 476 // the same scope and this is not an out-of-line definition of 477 // a member function. 478 continue; 479 } 480 481 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) { 482 // If only one of these is a local function declaration, then they are 483 // declared in different scopes, even though isDeclInScope may think 484 // they're in the same scope. (If both are local, the scope check is 485 // sufficient, and if neither is local, then they are in the same scope.) 486 continue; 487 } 488 489 // We found the right previous declaration. 490 break; 491 } 492 493 // C++ [dcl.fct.default]p4: 494 // For non-template functions, default arguments can be added in 495 // later declarations of a function in the same 496 // scope. Declarations in different scopes have completely 497 // distinct sets of default arguments. That is, declarations in 498 // inner scopes do not acquire default arguments from 499 // declarations in outer scopes, and vice versa. In a given 500 // function declaration, all parameters subsequent to a 501 // parameter with a default argument shall have default 502 // arguments supplied in this or previous declarations. A 503 // default argument shall not be redefined by a later 504 // declaration (not even to the same value). 505 // 506 // C++ [dcl.fct.default]p6: 507 // Except for member functions of class templates, the default arguments 508 // in a member function definition that appears outside of the class 509 // definition are added to the set of default arguments provided by the 510 // member function declaration in the class definition. 511 for (unsigned p = 0, NumParams = PrevForDefaultArgs 512 ? PrevForDefaultArgs->getNumParams() 513 : 0; 514 p < NumParams; ++p) { 515 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p); 516 ParmVarDecl *NewParam = New->getParamDecl(p); 517 518 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false; 519 bool NewParamHasDfl = NewParam->hasDefaultArg(); 520 521 if (OldParamHasDfl && NewParamHasDfl) { 522 unsigned DiagDefaultParamID = 523 diag::err_param_default_argument_redefinition; 524 525 // MSVC accepts that default parameters be redefined for member functions 526 // of template class. The new default parameter's value is ignored. 527 Invalid = true; 528 if (getLangOpts().MicrosoftExt) { 529 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New); 530 if (MD && MD->getParent()->getDescribedClassTemplate()) { 531 // Merge the old default argument into the new parameter. 532 NewParam->setHasInheritedDefaultArg(); 533 if (OldParam->hasUninstantiatedDefaultArg()) 534 NewParam->setUninstantiatedDefaultArg( 535 OldParam->getUninstantiatedDefaultArg()); 536 else 537 NewParam->setDefaultArg(OldParam->getInit()); 538 DiagDefaultParamID = diag::ext_param_default_argument_redefinition; 539 Invalid = false; 540 } 541 } 542 543 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 544 // hint here. Alternatively, we could walk the type-source information 545 // for NewParam to find the last source location in the type... but it 546 // isn't worth the effort right now. This is the kind of test case that 547 // is hard to get right: 548 // int f(int); 549 // void g(int (*fp)(int) = f); 550 // void g(int (*fp)(int) = &f); 551 Diag(NewParam->getLocation(), DiagDefaultParamID) 552 << NewParam->getDefaultArgRange(); 553 554 // Look for the function declaration where the default argument was 555 // actually written, which may be a declaration prior to Old. 556 for (auto Older = PrevForDefaultArgs; 557 OldParam->hasInheritedDefaultArg(); /**/) { 558 Older = Older->getPreviousDecl(); 559 OldParam = Older->getParamDecl(p); 560 } 561 562 Diag(OldParam->getLocation(), diag::note_previous_definition) 563 << OldParam->getDefaultArgRange(); 564 } else if (OldParamHasDfl) { 565 // Merge the old default argument into the new parameter unless the new 566 // function is a friend declaration in a template class. In the latter 567 // case the default arguments will be inherited when the friend 568 // declaration will be instantiated. 569 if (New->getFriendObjectKind() == Decl::FOK_None || 570 !New->getLexicalDeclContext()->isDependentContext()) { 571 // It's important to use getInit() here; getDefaultArg() 572 // strips off any top-level ExprWithCleanups. 573 NewParam->setHasInheritedDefaultArg(); 574 if (OldParam->hasUnparsedDefaultArg()) 575 NewParam->setUnparsedDefaultArg(); 576 else if (OldParam->hasUninstantiatedDefaultArg()) 577 NewParam->setUninstantiatedDefaultArg( 578 OldParam->getUninstantiatedDefaultArg()); 579 else 580 NewParam->setDefaultArg(OldParam->getInit()); 581 } 582 } else if (NewParamHasDfl) { 583 if (New->getDescribedFunctionTemplate()) { 584 // Paragraph 4, quoted above, only applies to non-template functions. 585 Diag(NewParam->getLocation(), 586 diag::err_param_default_argument_template_redecl) 587 << NewParam->getDefaultArgRange(); 588 Diag(PrevForDefaultArgs->getLocation(), 589 diag::note_template_prev_declaration) 590 << false; 591 } else if (New->getTemplateSpecializationKind() 592 != TSK_ImplicitInstantiation && 593 New->getTemplateSpecializationKind() != TSK_Undeclared) { 594 // C++ [temp.expr.spec]p21: 595 // Default function arguments shall not be specified in a declaration 596 // or a definition for one of the following explicit specializations: 597 // - the explicit specialization of a function template; 598 // - the explicit specialization of a member function template; 599 // - the explicit specialization of a member function of a class 600 // template where the class template specialization to which the 601 // member function specialization belongs is implicitly 602 // instantiated. 603 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 604 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 605 << New->getDeclName() 606 << NewParam->getDefaultArgRange(); 607 } else if (New->getDeclContext()->isDependentContext()) { 608 // C++ [dcl.fct.default]p6 (DR217): 609 // Default arguments for a member function of a class template shall 610 // be specified on the initial declaration of the member function 611 // within the class template. 612 // 613 // Reading the tea leaves a bit in DR217 and its reference to DR205 614 // leads me to the conclusion that one cannot add default function 615 // arguments for an out-of-line definition of a member function of a 616 // dependent type. 617 int WhichKind = 2; 618 if (CXXRecordDecl *Record 619 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 620 if (Record->getDescribedClassTemplate()) 621 WhichKind = 0; 622 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 623 WhichKind = 1; 624 else 625 WhichKind = 2; 626 } 627 628 Diag(NewParam->getLocation(), 629 diag::err_param_default_argument_member_template_redecl) 630 << WhichKind 631 << NewParam->getDefaultArgRange(); 632 } 633 } 634 } 635 636 // DR1344: If a default argument is added outside a class definition and that 637 // default argument makes the function a special member function, the program 638 // is ill-formed. This can only happen for constructors. 639 if (isa<CXXConstructorDecl>(New) && 640 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 641 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 642 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 643 if (NewSM != OldSM) { 644 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 645 assert(NewParam->hasDefaultArg()); 646 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 647 << NewParam->getDefaultArgRange() << NewSM; 648 Diag(Old->getLocation(), diag::note_previous_declaration); 649 } 650 } 651 652 const FunctionDecl *Def; 653 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 654 // template has a constexpr specifier then all its declarations shall 655 // contain the constexpr specifier. 656 if (New->getConstexprKind() != Old->getConstexprKind()) { 657 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 658 << New << New->getConstexprKind() << Old->getConstexprKind(); 659 Diag(Old->getLocation(), diag::note_previous_declaration); 660 Invalid = true; 661 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() && 662 Old->isDefined(Def) && 663 // If a friend function is inlined but does not have 'inline' 664 // specifier, it is a definition. Do not report attribute conflict 665 // in this case, redefinition will be diagnosed later. 666 (New->isInlineSpecified() || 667 New->getFriendObjectKind() == Decl::FOK_None)) { 668 // C++11 [dcl.fcn.spec]p4: 669 // If the definition of a function appears in a translation unit before its 670 // first declaration as inline, the program is ill-formed. 671 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 672 Diag(Def->getLocation(), diag::note_previous_definition); 673 Invalid = true; 674 } 675 676 // C++17 [temp.deduct.guide]p3: 677 // Two deduction guide declarations in the same translation unit 678 // for the same class template shall not have equivalent 679 // parameter-declaration-clauses. 680 if (isa<CXXDeductionGuideDecl>(New) && 681 !New->isFunctionTemplateSpecialization() && isVisible(Old)) { 682 Diag(New->getLocation(), diag::err_deduction_guide_redeclared); 683 Diag(Old->getLocation(), diag::note_previous_declaration); 684 } 685 686 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 687 // argument expression, that declaration shall be a definition and shall be 688 // the only declaration of the function or function template in the 689 // translation unit. 690 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 691 functionDeclHasDefaultArgument(Old)) { 692 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 693 Diag(Old->getLocation(), diag::note_previous_declaration); 694 Invalid = true; 695 } 696 697 return Invalid; 698 } 699 700 NamedDecl * 701 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D, 702 MultiTemplateParamsArg TemplateParamLists) { 703 assert(D.isDecompositionDeclarator()); 704 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 705 706 // The syntax only allows a decomposition declarator as a simple-declaration, 707 // a for-range-declaration, or a condition in Clang, but we parse it in more 708 // cases than that. 709 if (!D.mayHaveDecompositionDeclarator()) { 710 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 711 << Decomp.getSourceRange(); 712 return nullptr; 713 } 714 715 if (!TemplateParamLists.empty()) { 716 // FIXME: There's no rule against this, but there are also no rules that 717 // would actually make it usable, so we reject it for now. 718 Diag(TemplateParamLists.front()->getTemplateLoc(), 719 diag::err_decomp_decl_template); 720 return nullptr; 721 } 722 723 Diag(Decomp.getLSquareLoc(), 724 !getLangOpts().CPlusPlus17 725 ? diag::ext_decomp_decl 726 : D.getContext() == DeclaratorContext::ConditionContext 727 ? diag::ext_decomp_decl_cond 728 : diag::warn_cxx14_compat_decomp_decl) 729 << Decomp.getSourceRange(); 730 731 // The semantic context is always just the current context. 732 DeclContext *const DC = CurContext; 733 734 // C++17 [dcl.dcl]/8: 735 // The decl-specifier-seq shall contain only the type-specifier auto 736 // and cv-qualifiers. 737 // C++2a [dcl.dcl]/8: 738 // If decl-specifier-seq contains any decl-specifier other than static, 739 // thread_local, auto, or cv-qualifiers, the program is ill-formed. 740 auto &DS = D.getDeclSpec(); 741 { 742 SmallVector<StringRef, 8> BadSpecifiers; 743 SmallVector<SourceLocation, 8> BadSpecifierLocs; 744 SmallVector<StringRef, 8> CPlusPlus20Specifiers; 745 SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs; 746 if (auto SCS = DS.getStorageClassSpec()) { 747 if (SCS == DeclSpec::SCS_static) { 748 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS)); 749 CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 750 } else { 751 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS)); 752 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 753 } 754 } 755 if (auto TSCS = DS.getThreadStorageClassSpec()) { 756 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS)); 757 CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc()); 758 } 759 if (DS.hasConstexprSpecifier()) { 760 BadSpecifiers.push_back( 761 DeclSpec::getSpecifierName(DS.getConstexprSpecifier())); 762 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc()); 763 } 764 if (DS.isInlineSpecified()) { 765 BadSpecifiers.push_back("inline"); 766 BadSpecifierLocs.push_back(DS.getInlineSpecLoc()); 767 } 768 if (!BadSpecifiers.empty()) { 769 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec); 770 Err << (int)BadSpecifiers.size() 771 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " "); 772 // Don't add FixItHints to remove the specifiers; we do still respect 773 // them when building the underlying variable. 774 for (auto Loc : BadSpecifierLocs) 775 Err << SourceRange(Loc, Loc); 776 } else if (!CPlusPlus20Specifiers.empty()) { 777 auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(), 778 getLangOpts().CPlusPlus20 779 ? diag::warn_cxx17_compat_decomp_decl_spec 780 : diag::ext_decomp_decl_spec); 781 Warn << (int)CPlusPlus20Specifiers.size() 782 << llvm::join(CPlusPlus20Specifiers.begin(), 783 CPlusPlus20Specifiers.end(), " "); 784 for (auto Loc : CPlusPlus20SpecifierLocs) 785 Warn << SourceRange(Loc, Loc); 786 } 787 // We can't recover from it being declared as a typedef. 788 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 789 return nullptr; 790 } 791 792 // C++2a [dcl.struct.bind]p1: 793 // A cv that includes volatile is deprecated 794 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) && 795 getLangOpts().CPlusPlus20) 796 Diag(DS.getVolatileSpecLoc(), 797 diag::warn_deprecated_volatile_structured_binding); 798 799 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 800 QualType R = TInfo->getType(); 801 802 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 803 UPPC_DeclarationType)) 804 D.setInvalidType(); 805 806 // The syntax only allows a single ref-qualifier prior to the decomposition 807 // declarator. No other declarator chunks are permitted. Also check the type 808 // specifier here. 809 if (DS.getTypeSpecType() != DeclSpec::TST_auto || 810 D.hasGroupingParens() || D.getNumTypeObjects() > 1 || 811 (D.getNumTypeObjects() == 1 && 812 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) { 813 Diag(Decomp.getLSquareLoc(), 814 (D.hasGroupingParens() || 815 (D.getNumTypeObjects() && 816 D.getTypeObject(0).Kind == DeclaratorChunk::Paren)) 817 ? diag::err_decomp_decl_parens 818 : diag::err_decomp_decl_type) 819 << R; 820 821 // In most cases, there's no actual problem with an explicitly-specified 822 // type, but a function type won't work here, and ActOnVariableDeclarator 823 // shouldn't be called for such a type. 824 if (R->isFunctionType()) 825 D.setInvalidType(); 826 } 827 828 // Build the BindingDecls. 829 SmallVector<BindingDecl*, 8> Bindings; 830 831 // Build the BindingDecls. 832 for (auto &B : D.getDecompositionDeclarator().bindings()) { 833 // Check for name conflicts. 834 DeclarationNameInfo NameInfo(B.Name, B.NameLoc); 835 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 836 ForVisibleRedeclaration); 837 LookupName(Previous, S, 838 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit()); 839 840 // It's not permitted to shadow a template parameter name. 841 if (Previous.isSingleResult() && 842 Previous.getFoundDecl()->isTemplateParameter()) { 843 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 844 Previous.getFoundDecl()); 845 Previous.clear(); 846 } 847 848 bool ConsiderLinkage = DC->isFunctionOrMethod() && 849 DS.getStorageClassSpec() == DeclSpec::SCS_extern; 850 FilterLookupForScope(Previous, DC, S, ConsiderLinkage, 851 /*AllowInlineNamespace*/false); 852 if (!Previous.empty()) { 853 auto *Old = Previous.getRepresentativeDecl(); 854 Diag(B.NameLoc, diag::err_redefinition) << B.Name; 855 Diag(Old->getLocation(), diag::note_previous_definition); 856 } 857 858 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name); 859 PushOnScopeChains(BD, S, true); 860 Bindings.push_back(BD); 861 ParsingInitForAutoVars.insert(BD); 862 } 863 864 // There are no prior lookup results for the variable itself, because it 865 // is unnamed. 866 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr, 867 Decomp.getLSquareLoc()); 868 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 869 ForVisibleRedeclaration); 870 871 // Build the variable that holds the non-decomposed object. 872 bool AddToScope = true; 873 NamedDecl *New = 874 ActOnVariableDeclarator(S, D, DC, TInfo, Previous, 875 MultiTemplateParamsArg(), AddToScope, Bindings); 876 if (AddToScope) { 877 S->AddDecl(New); 878 CurContext->addHiddenDecl(New); 879 } 880 881 if (isInOpenMPDeclareTargetContext()) 882 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 883 884 return New; 885 } 886 887 static bool checkSimpleDecomposition( 888 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src, 889 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType, 890 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) { 891 if ((int64_t)Bindings.size() != NumElems) { 892 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 893 << DecompType << (unsigned)Bindings.size() << NumElems.toString(10) 894 << (NumElems < Bindings.size()); 895 return true; 896 } 897 898 unsigned I = 0; 899 for (auto *B : Bindings) { 900 SourceLocation Loc = B->getLocation(); 901 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 902 if (E.isInvalid()) 903 return true; 904 E = GetInit(Loc, E.get(), I++); 905 if (E.isInvalid()) 906 return true; 907 B->setBinding(ElemType, E.get()); 908 } 909 910 return false; 911 } 912 913 static bool checkArrayLikeDecomposition(Sema &S, 914 ArrayRef<BindingDecl *> Bindings, 915 ValueDecl *Src, QualType DecompType, 916 const llvm::APSInt &NumElems, 917 QualType ElemType) { 918 return checkSimpleDecomposition( 919 S, Bindings, Src, DecompType, NumElems, ElemType, 920 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 921 ExprResult E = S.ActOnIntegerConstant(Loc, I); 922 if (E.isInvalid()) 923 return ExprError(); 924 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc); 925 }); 926 } 927 928 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 929 ValueDecl *Src, QualType DecompType, 930 const ConstantArrayType *CAT) { 931 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType, 932 llvm::APSInt(CAT->getSize()), 933 CAT->getElementType()); 934 } 935 936 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 937 ValueDecl *Src, QualType DecompType, 938 const VectorType *VT) { 939 return checkArrayLikeDecomposition( 940 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()), 941 S.Context.getQualifiedType(VT->getElementType(), 942 DecompType.getQualifiers())); 943 } 944 945 static bool checkComplexDecomposition(Sema &S, 946 ArrayRef<BindingDecl *> Bindings, 947 ValueDecl *Src, QualType DecompType, 948 const ComplexType *CT) { 949 return checkSimpleDecomposition( 950 S, Bindings, Src, DecompType, llvm::APSInt::get(2), 951 S.Context.getQualifiedType(CT->getElementType(), 952 DecompType.getQualifiers()), 953 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 954 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base); 955 }); 956 } 957 958 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy, 959 TemplateArgumentListInfo &Args) { 960 SmallString<128> SS; 961 llvm::raw_svector_ostream OS(SS); 962 bool First = true; 963 for (auto &Arg : Args.arguments()) { 964 if (!First) 965 OS << ", "; 966 Arg.getArgument().print(PrintingPolicy, OS); 967 First = false; 968 } 969 return std::string(OS.str()); 970 } 971 972 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup, 973 SourceLocation Loc, StringRef Trait, 974 TemplateArgumentListInfo &Args, 975 unsigned DiagID) { 976 auto DiagnoseMissing = [&] { 977 if (DiagID) 978 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(), 979 Args); 980 return true; 981 }; 982 983 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine. 984 NamespaceDecl *Std = S.getStdNamespace(); 985 if (!Std) 986 return DiagnoseMissing(); 987 988 // Look up the trait itself, within namespace std. We can diagnose various 989 // problems with this lookup even if we've been asked to not diagnose a 990 // missing specialization, because this can only fail if the user has been 991 // declaring their own names in namespace std or we don't support the 992 // standard library implementation in use. 993 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait), 994 Loc, Sema::LookupOrdinaryName); 995 if (!S.LookupQualifiedName(Result, Std)) 996 return DiagnoseMissing(); 997 if (Result.isAmbiguous()) 998 return true; 999 1000 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>(); 1001 if (!TraitTD) { 1002 Result.suppressDiagnostics(); 1003 NamedDecl *Found = *Result.begin(); 1004 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait; 1005 S.Diag(Found->getLocation(), diag::note_declared_at); 1006 return true; 1007 } 1008 1009 // Build the template-id. 1010 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args); 1011 if (TraitTy.isNull()) 1012 return true; 1013 if (!S.isCompleteType(Loc, TraitTy)) { 1014 if (DiagID) 1015 S.RequireCompleteType( 1016 Loc, TraitTy, DiagID, 1017 printTemplateArgs(S.Context.getPrintingPolicy(), Args)); 1018 return true; 1019 } 1020 1021 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl(); 1022 assert(RD && "specialization of class template is not a class?"); 1023 1024 // Look up the member of the trait type. 1025 S.LookupQualifiedName(TraitMemberLookup, RD); 1026 return TraitMemberLookup.isAmbiguous(); 1027 } 1028 1029 static TemplateArgumentLoc 1030 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, 1031 uint64_t I) { 1032 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T); 1033 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc); 1034 } 1035 1036 static TemplateArgumentLoc 1037 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) { 1038 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc); 1039 } 1040 1041 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; } 1042 1043 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, 1044 llvm::APSInt &Size) { 1045 EnterExpressionEvaluationContext ContextRAII( 1046 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 1047 1048 DeclarationName Value = S.PP.getIdentifierInfo("value"); 1049 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName); 1050 1051 // Form template argument list for tuple_size<T>. 1052 TemplateArgumentListInfo Args(Loc, Loc); 1053 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1054 1055 // If there's no tuple_size specialization or the lookup of 'value' is empty, 1056 // it's not tuple-like. 1057 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) || 1058 R.empty()) 1059 return IsTupleLike::NotTupleLike; 1060 1061 // If we get this far, we've committed to the tuple interpretation, but 1062 // we can still fail if there actually isn't a usable ::value. 1063 1064 struct ICEDiagnoser : Sema::VerifyICEDiagnoser { 1065 LookupResult &R; 1066 TemplateArgumentListInfo &Args; 1067 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args) 1068 : R(R), Args(Args) {} 1069 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S, 1070 SourceLocation Loc) override { 1071 return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant) 1072 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1073 } 1074 } Diagnoser(R, Args); 1075 1076 ExprResult E = 1077 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false); 1078 if (E.isInvalid()) 1079 return IsTupleLike::Error; 1080 1081 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser); 1082 if (E.isInvalid()) 1083 return IsTupleLike::Error; 1084 1085 return IsTupleLike::TupleLike; 1086 } 1087 1088 /// \return std::tuple_element<I, T>::type. 1089 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, 1090 unsigned I, QualType T) { 1091 // Form template argument list for tuple_element<I, T>. 1092 TemplateArgumentListInfo Args(Loc, Loc); 1093 Args.addArgument( 1094 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1095 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1096 1097 DeclarationName TypeDN = S.PP.getIdentifierInfo("type"); 1098 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName); 1099 if (lookupStdTypeTraitMember( 1100 S, R, Loc, "tuple_element", Args, 1101 diag::err_decomp_decl_std_tuple_element_not_specialized)) 1102 return QualType(); 1103 1104 auto *TD = R.getAsSingle<TypeDecl>(); 1105 if (!TD) { 1106 R.suppressDiagnostics(); 1107 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized) 1108 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1109 if (!R.empty()) 1110 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at); 1111 return QualType(); 1112 } 1113 1114 return S.Context.getTypeDeclType(TD); 1115 } 1116 1117 namespace { 1118 struct InitializingBinding { 1119 Sema &S; 1120 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) { 1121 Sema::CodeSynthesisContext Ctx; 1122 Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding; 1123 Ctx.PointOfInstantiation = BD->getLocation(); 1124 Ctx.Entity = BD; 1125 S.pushCodeSynthesisContext(Ctx); 1126 } 1127 ~InitializingBinding() { 1128 S.popCodeSynthesisContext(); 1129 } 1130 }; 1131 } 1132 1133 static bool checkTupleLikeDecomposition(Sema &S, 1134 ArrayRef<BindingDecl *> Bindings, 1135 VarDecl *Src, QualType DecompType, 1136 const llvm::APSInt &TupleSize) { 1137 if ((int64_t)Bindings.size() != TupleSize) { 1138 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1139 << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10) 1140 << (TupleSize < Bindings.size()); 1141 return true; 1142 } 1143 1144 if (Bindings.empty()) 1145 return false; 1146 1147 DeclarationName GetDN = S.PP.getIdentifierInfo("get"); 1148 1149 // [dcl.decomp]p3: 1150 // The unqualified-id get is looked up in the scope of E by class member 1151 // access lookup ... 1152 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName); 1153 bool UseMemberGet = false; 1154 if (S.isCompleteType(Src->getLocation(), DecompType)) { 1155 if (auto *RD = DecompType->getAsCXXRecordDecl()) 1156 S.LookupQualifiedName(MemberGet, RD); 1157 if (MemberGet.isAmbiguous()) 1158 return true; 1159 // ... and if that finds at least one declaration that is a function 1160 // template whose first template parameter is a non-type parameter ... 1161 for (NamedDecl *D : MemberGet) { 1162 if (FunctionTemplateDecl *FTD = 1163 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) { 1164 TemplateParameterList *TPL = FTD->getTemplateParameters(); 1165 if (TPL->size() != 0 && 1166 isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) { 1167 // ... the initializer is e.get<i>(). 1168 UseMemberGet = true; 1169 break; 1170 } 1171 } 1172 } 1173 } 1174 1175 unsigned I = 0; 1176 for (auto *B : Bindings) { 1177 InitializingBinding InitContext(S, B); 1178 SourceLocation Loc = B->getLocation(); 1179 1180 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1181 if (E.isInvalid()) 1182 return true; 1183 1184 // e is an lvalue if the type of the entity is an lvalue reference and 1185 // an xvalue otherwise 1186 if (!Src->getType()->isLValueReferenceType()) 1187 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp, 1188 E.get(), nullptr, VK_XValue, 1189 FPOptionsOverride()); 1190 1191 TemplateArgumentListInfo Args(Loc, Loc); 1192 Args.addArgument( 1193 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1194 1195 if (UseMemberGet) { 1196 // if [lookup of member get] finds at least one declaration, the 1197 // initializer is e.get<i-1>(). 1198 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false, 1199 CXXScopeSpec(), SourceLocation(), nullptr, 1200 MemberGet, &Args, nullptr); 1201 if (E.isInvalid()) 1202 return true; 1203 1204 E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc); 1205 } else { 1206 // Otherwise, the initializer is get<i-1>(e), where get is looked up 1207 // in the associated namespaces. 1208 Expr *Get = UnresolvedLookupExpr::Create( 1209 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(), 1210 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args, 1211 UnresolvedSetIterator(), UnresolvedSetIterator()); 1212 1213 Expr *Arg = E.get(); 1214 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc); 1215 } 1216 if (E.isInvalid()) 1217 return true; 1218 Expr *Init = E.get(); 1219 1220 // Given the type T designated by std::tuple_element<i - 1, E>::type, 1221 QualType T = getTupleLikeElementType(S, Loc, I, DecompType); 1222 if (T.isNull()) 1223 return true; 1224 1225 // each vi is a variable of type "reference to T" initialized with the 1226 // initializer, where the reference is an lvalue reference if the 1227 // initializer is an lvalue and an rvalue reference otherwise 1228 QualType RefType = 1229 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName()); 1230 if (RefType.isNull()) 1231 return true; 1232 auto *RefVD = VarDecl::Create( 1233 S.Context, Src->getDeclContext(), Loc, Loc, 1234 B->getDeclName().getAsIdentifierInfo(), RefType, 1235 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass()); 1236 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext()); 1237 RefVD->setTSCSpec(Src->getTSCSpec()); 1238 RefVD->setImplicit(); 1239 if (Src->isInlineSpecified()) 1240 RefVD->setInlineSpecified(); 1241 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD); 1242 1243 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD); 1244 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc); 1245 InitializationSequence Seq(S, Entity, Kind, Init); 1246 E = Seq.Perform(S, Entity, Kind, Init); 1247 if (E.isInvalid()) 1248 return true; 1249 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false); 1250 if (E.isInvalid()) 1251 return true; 1252 RefVD->setInit(E.get()); 1253 S.CheckCompleteVariableDeclaration(RefVD); 1254 1255 E = S.BuildDeclarationNameExpr(CXXScopeSpec(), 1256 DeclarationNameInfo(B->getDeclName(), Loc), 1257 RefVD); 1258 if (E.isInvalid()) 1259 return true; 1260 1261 B->setBinding(T, E.get()); 1262 I++; 1263 } 1264 1265 return false; 1266 } 1267 1268 /// Find the base class to decompose in a built-in decomposition of a class type. 1269 /// This base class search is, unfortunately, not quite like any other that we 1270 /// perform anywhere else in C++. 1271 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc, 1272 const CXXRecordDecl *RD, 1273 CXXCastPath &BasePath) { 1274 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier, 1275 CXXBasePath &Path) { 1276 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields(); 1277 }; 1278 1279 const CXXRecordDecl *ClassWithFields = nullptr; 1280 AccessSpecifier AS = AS_public; 1281 if (RD->hasDirectFields()) 1282 // [dcl.decomp]p4: 1283 // Otherwise, all of E's non-static data members shall be public direct 1284 // members of E ... 1285 ClassWithFields = RD; 1286 else { 1287 // ... or of ... 1288 CXXBasePaths Paths; 1289 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD)); 1290 if (!RD->lookupInBases(BaseHasFields, Paths)) { 1291 // If no classes have fields, just decompose RD itself. (This will work 1292 // if and only if zero bindings were provided.) 1293 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public); 1294 } 1295 1296 CXXBasePath *BestPath = nullptr; 1297 for (auto &P : Paths) { 1298 if (!BestPath) 1299 BestPath = &P; 1300 else if (!S.Context.hasSameType(P.back().Base->getType(), 1301 BestPath->back().Base->getType())) { 1302 // ... the same ... 1303 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1304 << false << RD << BestPath->back().Base->getType() 1305 << P.back().Base->getType(); 1306 return DeclAccessPair(); 1307 } else if (P.Access < BestPath->Access) { 1308 BestPath = &P; 1309 } 1310 } 1311 1312 // ... unambiguous ... 1313 QualType BaseType = BestPath->back().Base->getType(); 1314 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) { 1315 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base) 1316 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths); 1317 return DeclAccessPair(); 1318 } 1319 1320 // ... [accessible, implied by other rules] base class of E. 1321 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD), 1322 *BestPath, diag::err_decomp_decl_inaccessible_base); 1323 AS = BestPath->Access; 1324 1325 ClassWithFields = BaseType->getAsCXXRecordDecl(); 1326 S.BuildBasePathArray(Paths, BasePath); 1327 } 1328 1329 // The above search did not check whether the selected class itself has base 1330 // classes with fields, so check that now. 1331 CXXBasePaths Paths; 1332 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) { 1333 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1334 << (ClassWithFields == RD) << RD << ClassWithFields 1335 << Paths.front().back().Base->getType(); 1336 return DeclAccessPair(); 1337 } 1338 1339 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS); 1340 } 1341 1342 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 1343 ValueDecl *Src, QualType DecompType, 1344 const CXXRecordDecl *OrigRD) { 1345 if (S.RequireCompleteType(Src->getLocation(), DecompType, 1346 diag::err_incomplete_type)) 1347 return true; 1348 1349 CXXCastPath BasePath; 1350 DeclAccessPair BasePair = 1351 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath); 1352 const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl()); 1353 if (!RD) 1354 return true; 1355 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD), 1356 DecompType.getQualifiers()); 1357 1358 auto DiagnoseBadNumberOfBindings = [&]() -> bool { 1359 unsigned NumFields = 1360 std::count_if(RD->field_begin(), RD->field_end(), 1361 [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); }); 1362 assert(Bindings.size() != NumFields); 1363 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1364 << DecompType << (unsigned)Bindings.size() << NumFields 1365 << (NumFields < Bindings.size()); 1366 return true; 1367 }; 1368 1369 // all of E's non-static data members shall be [...] well-formed 1370 // when named as e.name in the context of the structured binding, 1371 // E shall not have an anonymous union member, ... 1372 unsigned I = 0; 1373 for (auto *FD : RD->fields()) { 1374 if (FD->isUnnamedBitfield()) 1375 continue; 1376 1377 if (FD->isAnonymousStructOrUnion()) { 1378 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member) 1379 << DecompType << FD->getType()->isUnionType(); 1380 S.Diag(FD->getLocation(), diag::note_declared_at); 1381 return true; 1382 } 1383 1384 // We have a real field to bind. 1385 if (I >= Bindings.size()) 1386 return DiagnoseBadNumberOfBindings(); 1387 auto *B = Bindings[I++]; 1388 SourceLocation Loc = B->getLocation(); 1389 1390 // The field must be accessible in the context of the structured binding. 1391 // We already checked that the base class is accessible. 1392 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the 1393 // const_cast here. 1394 S.CheckStructuredBindingMemberAccess( 1395 Loc, const_cast<CXXRecordDecl *>(OrigRD), 1396 DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess( 1397 BasePair.getAccess(), FD->getAccess()))); 1398 1399 // Initialize the binding to Src.FD. 1400 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1401 if (E.isInvalid()) 1402 return true; 1403 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase, 1404 VK_LValue, &BasePath); 1405 if (E.isInvalid()) 1406 return true; 1407 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc, 1408 CXXScopeSpec(), FD, 1409 DeclAccessPair::make(FD, FD->getAccess()), 1410 DeclarationNameInfo(FD->getDeclName(), Loc)); 1411 if (E.isInvalid()) 1412 return true; 1413 1414 // If the type of the member is T, the referenced type is cv T, where cv is 1415 // the cv-qualification of the decomposition expression. 1416 // 1417 // FIXME: We resolve a defect here: if the field is mutable, we do not add 1418 // 'const' to the type of the field. 1419 Qualifiers Q = DecompType.getQualifiers(); 1420 if (FD->isMutable()) 1421 Q.removeConst(); 1422 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get()); 1423 } 1424 1425 if (I != Bindings.size()) 1426 return DiagnoseBadNumberOfBindings(); 1427 1428 return false; 1429 } 1430 1431 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) { 1432 QualType DecompType = DD->getType(); 1433 1434 // If the type of the decomposition is dependent, then so is the type of 1435 // each binding. 1436 if (DecompType->isDependentType()) { 1437 for (auto *B : DD->bindings()) 1438 B->setType(Context.DependentTy); 1439 return; 1440 } 1441 1442 DecompType = DecompType.getNonReferenceType(); 1443 ArrayRef<BindingDecl*> Bindings = DD->bindings(); 1444 1445 // C++1z [dcl.decomp]/2: 1446 // If E is an array type [...] 1447 // As an extension, we also support decomposition of built-in complex and 1448 // vector types. 1449 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) { 1450 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT)) 1451 DD->setInvalidDecl(); 1452 return; 1453 } 1454 if (auto *VT = DecompType->getAs<VectorType>()) { 1455 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT)) 1456 DD->setInvalidDecl(); 1457 return; 1458 } 1459 if (auto *CT = DecompType->getAs<ComplexType>()) { 1460 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT)) 1461 DD->setInvalidDecl(); 1462 return; 1463 } 1464 1465 // C++1z [dcl.decomp]/3: 1466 // if the expression std::tuple_size<E>::value is a well-formed integral 1467 // constant expression, [...] 1468 llvm::APSInt TupleSize(32); 1469 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) { 1470 case IsTupleLike::Error: 1471 DD->setInvalidDecl(); 1472 return; 1473 1474 case IsTupleLike::TupleLike: 1475 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize)) 1476 DD->setInvalidDecl(); 1477 return; 1478 1479 case IsTupleLike::NotTupleLike: 1480 break; 1481 } 1482 1483 // C++1z [dcl.dcl]/8: 1484 // [E shall be of array or non-union class type] 1485 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl(); 1486 if (!RD || RD->isUnion()) { 1487 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type) 1488 << DD << !RD << DecompType; 1489 DD->setInvalidDecl(); 1490 return; 1491 } 1492 1493 // C++1z [dcl.decomp]/4: 1494 // all of E's non-static data members shall be [...] direct members of 1495 // E or of the same unambiguous public base class of E, ... 1496 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD)) 1497 DD->setInvalidDecl(); 1498 } 1499 1500 /// Merge the exception specifications of two variable declarations. 1501 /// 1502 /// This is called when there's a redeclaration of a VarDecl. The function 1503 /// checks if the redeclaration might have an exception specification and 1504 /// validates compatibility and merges the specs if necessary. 1505 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 1506 // Shortcut if exceptions are disabled. 1507 if (!getLangOpts().CXXExceptions) 1508 return; 1509 1510 assert(Context.hasSameType(New->getType(), Old->getType()) && 1511 "Should only be called if types are otherwise the same."); 1512 1513 QualType NewType = New->getType(); 1514 QualType OldType = Old->getType(); 1515 1516 // We're only interested in pointers and references to functions, as well 1517 // as pointers to member functions. 1518 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 1519 NewType = R->getPointeeType(); 1520 OldType = OldType->castAs<ReferenceType>()->getPointeeType(); 1521 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 1522 NewType = P->getPointeeType(); 1523 OldType = OldType->castAs<PointerType>()->getPointeeType(); 1524 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 1525 NewType = M->getPointeeType(); 1526 OldType = OldType->castAs<MemberPointerType>()->getPointeeType(); 1527 } 1528 1529 if (!NewType->isFunctionProtoType()) 1530 return; 1531 1532 // There's lots of special cases for functions. For function pointers, system 1533 // libraries are hopefully not as broken so that we don't need these 1534 // workarounds. 1535 if (CheckEquivalentExceptionSpec( 1536 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 1537 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 1538 New->setInvalidDecl(); 1539 } 1540 } 1541 1542 /// CheckCXXDefaultArguments - Verify that the default arguments for a 1543 /// function declaration are well-formed according to C++ 1544 /// [dcl.fct.default]. 1545 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 1546 unsigned NumParams = FD->getNumParams(); 1547 unsigned ParamIdx = 0; 1548 1549 // This checking doesn't make sense for explicit specializations; their 1550 // default arguments are determined by the declaration we're specializing, 1551 // not by FD. 1552 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 1553 return; 1554 if (auto *FTD = FD->getDescribedFunctionTemplate()) 1555 if (FTD->isMemberSpecialization()) 1556 return; 1557 1558 // Find first parameter with a default argument 1559 for (; ParamIdx < NumParams; ++ParamIdx) { 1560 ParmVarDecl *Param = FD->getParamDecl(ParamIdx); 1561 if (Param->hasDefaultArg()) 1562 break; 1563 } 1564 1565 // C++20 [dcl.fct.default]p4: 1566 // In a given function declaration, each parameter subsequent to a parameter 1567 // with a default argument shall have a default argument supplied in this or 1568 // a previous declaration, unless the parameter was expanded from a 1569 // parameter pack, or shall be a function parameter pack. 1570 for (; ParamIdx < NumParams; ++ParamIdx) { 1571 ParmVarDecl *Param = FD->getParamDecl(ParamIdx); 1572 if (!Param->hasDefaultArg() && !Param->isParameterPack() && 1573 !(CurrentInstantiationScope && 1574 CurrentInstantiationScope->isLocalPackExpansion(Param))) { 1575 if (Param->isInvalidDecl()) 1576 /* We already complained about this parameter. */; 1577 else if (Param->getIdentifier()) 1578 Diag(Param->getLocation(), 1579 diag::err_param_default_argument_missing_name) 1580 << Param->getIdentifier(); 1581 else 1582 Diag(Param->getLocation(), 1583 diag::err_param_default_argument_missing); 1584 } 1585 } 1586 } 1587 1588 /// Check that the given type is a literal type. Issue a diagnostic if not, 1589 /// if Kind is Diagnose. 1590 /// \return \c true if a problem has been found (and optionally diagnosed). 1591 template <typename... Ts> 1592 static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind, 1593 SourceLocation Loc, QualType T, unsigned DiagID, 1594 Ts &&...DiagArgs) { 1595 if (T->isDependentType()) 1596 return false; 1597 1598 switch (Kind) { 1599 case Sema::CheckConstexprKind::Diagnose: 1600 return SemaRef.RequireLiteralType(Loc, T, DiagID, 1601 std::forward<Ts>(DiagArgs)...); 1602 1603 case Sema::CheckConstexprKind::CheckValid: 1604 return !T->isLiteralType(SemaRef.Context); 1605 } 1606 1607 llvm_unreachable("unknown CheckConstexprKind"); 1608 } 1609 1610 /// Determine whether a destructor cannot be constexpr due to 1611 static bool CheckConstexprDestructorSubobjects(Sema &SemaRef, 1612 const CXXDestructorDecl *DD, 1613 Sema::CheckConstexprKind Kind) { 1614 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) { 1615 const CXXRecordDecl *RD = 1616 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 1617 if (!RD || RD->hasConstexprDestructor()) 1618 return true; 1619 1620 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1621 SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject) 1622 << DD->getConstexprKind() << !FD 1623 << (FD ? FD->getDeclName() : DeclarationName()) << T; 1624 SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject) 1625 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T; 1626 } 1627 return false; 1628 }; 1629 1630 const CXXRecordDecl *RD = DD->getParent(); 1631 for (const CXXBaseSpecifier &B : RD->bases()) 1632 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr)) 1633 return false; 1634 for (const FieldDecl *FD : RD->fields()) 1635 if (!Check(FD->getLocation(), FD->getType(), FD)) 1636 return false; 1637 return true; 1638 } 1639 1640 /// Check whether a function's parameter types are all literal types. If so, 1641 /// return true. If not, produce a suitable diagnostic and return false. 1642 static bool CheckConstexprParameterTypes(Sema &SemaRef, 1643 const FunctionDecl *FD, 1644 Sema::CheckConstexprKind Kind) { 1645 unsigned ArgIndex = 0; 1646 const auto *FT = FD->getType()->castAs<FunctionProtoType>(); 1647 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 1648 e = FT->param_type_end(); 1649 i != e; ++i, ++ArgIndex) { 1650 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 1651 SourceLocation ParamLoc = PD->getLocation(); 1652 if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i, 1653 diag::err_constexpr_non_literal_param, ArgIndex + 1, 1654 PD->getSourceRange(), isa<CXXConstructorDecl>(FD), 1655 FD->isConsteval())) 1656 return false; 1657 } 1658 return true; 1659 } 1660 1661 /// Check whether a function's return type is a literal type. If so, return 1662 /// true. If not, produce a suitable diagnostic and return false. 1663 static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD, 1664 Sema::CheckConstexprKind Kind) { 1665 if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(), 1666 diag::err_constexpr_non_literal_return, 1667 FD->isConsteval())) 1668 return false; 1669 return true; 1670 } 1671 1672 /// Get diagnostic %select index for tag kind for 1673 /// record diagnostic message. 1674 /// WARNING: Indexes apply to particular diagnostics only! 1675 /// 1676 /// \returns diagnostic %select index. 1677 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 1678 switch (Tag) { 1679 case TTK_Struct: return 0; 1680 case TTK_Interface: return 1; 1681 case TTK_Class: return 2; 1682 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 1683 } 1684 } 1685 1686 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, 1687 Stmt *Body, 1688 Sema::CheckConstexprKind Kind); 1689 1690 // Check whether a function declaration satisfies the requirements of a 1691 // constexpr function definition or a constexpr constructor definition. If so, 1692 // return true. If not, produce appropriate diagnostics (unless asked not to by 1693 // Kind) and return false. 1694 // 1695 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 1696 bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD, 1697 CheckConstexprKind Kind) { 1698 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 1699 if (MD && MD->isInstance()) { 1700 // C++11 [dcl.constexpr]p4: 1701 // The definition of a constexpr constructor shall satisfy the following 1702 // constraints: 1703 // - the class shall not have any virtual base classes; 1704 // 1705 // FIXME: This only applies to constructors and destructors, not arbitrary 1706 // member functions. 1707 const CXXRecordDecl *RD = MD->getParent(); 1708 if (RD->getNumVBases()) { 1709 if (Kind == CheckConstexprKind::CheckValid) 1710 return false; 1711 1712 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 1713 << isa<CXXConstructorDecl>(NewFD) 1714 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 1715 for (const auto &I : RD->vbases()) 1716 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here) 1717 << I.getSourceRange(); 1718 return false; 1719 } 1720 } 1721 1722 if (!isa<CXXConstructorDecl>(NewFD)) { 1723 // C++11 [dcl.constexpr]p3: 1724 // The definition of a constexpr function shall satisfy the following 1725 // constraints: 1726 // - it shall not be virtual; (removed in C++20) 1727 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 1728 if (Method && Method->isVirtual()) { 1729 if (getLangOpts().CPlusPlus20) { 1730 if (Kind == CheckConstexprKind::Diagnose) 1731 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual); 1732 } else { 1733 if (Kind == CheckConstexprKind::CheckValid) 1734 return false; 1735 1736 Method = Method->getCanonicalDecl(); 1737 Diag(Method->getLocation(), diag::err_constexpr_virtual); 1738 1739 // If it's not obvious why this function is virtual, find an overridden 1740 // function which uses the 'virtual' keyword. 1741 const CXXMethodDecl *WrittenVirtual = Method; 1742 while (!WrittenVirtual->isVirtualAsWritten()) 1743 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 1744 if (WrittenVirtual != Method) 1745 Diag(WrittenVirtual->getLocation(), 1746 diag::note_overridden_virtual_function); 1747 return false; 1748 } 1749 } 1750 1751 // - its return type shall be a literal type; 1752 if (!CheckConstexprReturnType(*this, NewFD, Kind)) 1753 return false; 1754 } 1755 1756 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) { 1757 // A destructor can be constexpr only if the defaulted destructor could be; 1758 // we don't need to check the members and bases if we already know they all 1759 // have constexpr destructors. 1760 if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) { 1761 if (Kind == CheckConstexprKind::CheckValid) 1762 return false; 1763 if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind)) 1764 return false; 1765 } 1766 } 1767 1768 // - each of its parameter types shall be a literal type; 1769 if (!CheckConstexprParameterTypes(*this, NewFD, Kind)) 1770 return false; 1771 1772 Stmt *Body = NewFD->getBody(); 1773 assert(Body && 1774 "CheckConstexprFunctionDefinition called on function with no body"); 1775 return CheckConstexprFunctionBody(*this, NewFD, Body, Kind); 1776 } 1777 1778 /// Check the given declaration statement is legal within a constexpr function 1779 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 1780 /// 1781 /// \return true if the body is OK (maybe only as an extension), false if we 1782 /// have diagnosed a problem. 1783 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 1784 DeclStmt *DS, SourceLocation &Cxx1yLoc, 1785 Sema::CheckConstexprKind Kind) { 1786 // C++11 [dcl.constexpr]p3 and p4: 1787 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 1788 // contain only 1789 for (const auto *DclIt : DS->decls()) { 1790 switch (DclIt->getKind()) { 1791 case Decl::StaticAssert: 1792 case Decl::Using: 1793 case Decl::UsingShadow: 1794 case Decl::UsingDirective: 1795 case Decl::UnresolvedUsingTypename: 1796 case Decl::UnresolvedUsingValue: 1797 // - static_assert-declarations 1798 // - using-declarations, 1799 // - using-directives, 1800 continue; 1801 1802 case Decl::Typedef: 1803 case Decl::TypeAlias: { 1804 // - typedef declarations and alias-declarations that do not define 1805 // classes or enumerations, 1806 const auto *TN = cast<TypedefNameDecl>(DclIt); 1807 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 1808 // Don't allow variably-modified types in constexpr functions. 1809 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1810 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 1811 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 1812 << TL.getSourceRange() << TL.getType() 1813 << isa<CXXConstructorDecl>(Dcl); 1814 } 1815 return false; 1816 } 1817 continue; 1818 } 1819 1820 case Decl::Enum: 1821 case Decl::CXXRecord: 1822 // C++1y allows types to be defined, not just declared. 1823 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) { 1824 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1825 SemaRef.Diag(DS->getBeginLoc(), 1826 SemaRef.getLangOpts().CPlusPlus14 1827 ? diag::warn_cxx11_compat_constexpr_type_definition 1828 : diag::ext_constexpr_type_definition) 1829 << isa<CXXConstructorDecl>(Dcl); 1830 } else if (!SemaRef.getLangOpts().CPlusPlus14) { 1831 return false; 1832 } 1833 } 1834 continue; 1835 1836 case Decl::EnumConstant: 1837 case Decl::IndirectField: 1838 case Decl::ParmVar: 1839 // These can only appear with other declarations which are banned in 1840 // C++11 and permitted in C++1y, so ignore them. 1841 continue; 1842 1843 case Decl::Var: 1844 case Decl::Decomposition: { 1845 // C++1y [dcl.constexpr]p3 allows anything except: 1846 // a definition of a variable of non-literal type or of static or 1847 // thread storage duration or [before C++2a] for which no 1848 // initialization is performed. 1849 const auto *VD = cast<VarDecl>(DclIt); 1850 if (VD->isThisDeclarationADefinition()) { 1851 if (VD->isStaticLocal()) { 1852 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1853 SemaRef.Diag(VD->getLocation(), 1854 diag::err_constexpr_local_var_static) 1855 << isa<CXXConstructorDecl>(Dcl) 1856 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 1857 } 1858 return false; 1859 } 1860 if (CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(), 1861 diag::err_constexpr_local_var_non_literal_type, 1862 isa<CXXConstructorDecl>(Dcl))) 1863 return false; 1864 if (!VD->getType()->isDependentType() && 1865 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 1866 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1867 SemaRef.Diag( 1868 VD->getLocation(), 1869 SemaRef.getLangOpts().CPlusPlus20 1870 ? diag::warn_cxx17_compat_constexpr_local_var_no_init 1871 : diag::ext_constexpr_local_var_no_init) 1872 << isa<CXXConstructorDecl>(Dcl); 1873 } else if (!SemaRef.getLangOpts().CPlusPlus20) { 1874 return false; 1875 } 1876 continue; 1877 } 1878 } 1879 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1880 SemaRef.Diag(VD->getLocation(), 1881 SemaRef.getLangOpts().CPlusPlus14 1882 ? diag::warn_cxx11_compat_constexpr_local_var 1883 : diag::ext_constexpr_local_var) 1884 << isa<CXXConstructorDecl>(Dcl); 1885 } else if (!SemaRef.getLangOpts().CPlusPlus14) { 1886 return false; 1887 } 1888 continue; 1889 } 1890 1891 case Decl::NamespaceAlias: 1892 case Decl::Function: 1893 // These are disallowed in C++11 and permitted in C++1y. Allow them 1894 // everywhere as an extension. 1895 if (!Cxx1yLoc.isValid()) 1896 Cxx1yLoc = DS->getBeginLoc(); 1897 continue; 1898 1899 default: 1900 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1901 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 1902 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 1903 } 1904 return false; 1905 } 1906 } 1907 1908 return true; 1909 } 1910 1911 /// Check that the given field is initialized within a constexpr constructor. 1912 /// 1913 /// \param Dcl The constexpr constructor being checked. 1914 /// \param Field The field being checked. This may be a member of an anonymous 1915 /// struct or union nested within the class being checked. 1916 /// \param Inits All declarations, including anonymous struct/union members and 1917 /// indirect members, for which any initialization was provided. 1918 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach 1919 /// multiple notes for different members to the same error. 1920 /// \param Kind Whether we're diagnosing a constructor as written or determining 1921 /// whether the formal requirements are satisfied. 1922 /// \return \c false if we're checking for validity and the constructor does 1923 /// not satisfy the requirements on a constexpr constructor. 1924 static bool CheckConstexprCtorInitializer(Sema &SemaRef, 1925 const FunctionDecl *Dcl, 1926 FieldDecl *Field, 1927 llvm::SmallSet<Decl*, 16> &Inits, 1928 bool &Diagnosed, 1929 Sema::CheckConstexprKind Kind) { 1930 // In C++20 onwards, there's nothing to check for validity. 1931 if (Kind == Sema::CheckConstexprKind::CheckValid && 1932 SemaRef.getLangOpts().CPlusPlus20) 1933 return true; 1934 1935 if (Field->isInvalidDecl()) 1936 return true; 1937 1938 if (Field->isUnnamedBitfield()) 1939 return true; 1940 1941 // Anonymous unions with no variant members and empty anonymous structs do not 1942 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 1943 // indirect fields don't need initializing. 1944 if (Field->isAnonymousStructOrUnion() && 1945 (Field->getType()->isUnionType() 1946 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 1947 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 1948 return true; 1949 1950 if (!Inits.count(Field)) { 1951 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1952 if (!Diagnosed) { 1953 SemaRef.Diag(Dcl->getLocation(), 1954 SemaRef.getLangOpts().CPlusPlus20 1955 ? diag::warn_cxx17_compat_constexpr_ctor_missing_init 1956 : diag::ext_constexpr_ctor_missing_init); 1957 Diagnosed = true; 1958 } 1959 SemaRef.Diag(Field->getLocation(), 1960 diag::note_constexpr_ctor_missing_init); 1961 } else if (!SemaRef.getLangOpts().CPlusPlus20) { 1962 return false; 1963 } 1964 } else if (Field->isAnonymousStructOrUnion()) { 1965 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 1966 for (auto *I : RD->fields()) 1967 // If an anonymous union contains an anonymous struct of which any member 1968 // is initialized, all members must be initialized. 1969 if (!RD->isUnion() || Inits.count(I)) 1970 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, 1971 Kind)) 1972 return false; 1973 } 1974 return true; 1975 } 1976 1977 /// Check the provided statement is allowed in a constexpr function 1978 /// definition. 1979 static bool 1980 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 1981 SmallVectorImpl<SourceLocation> &ReturnStmts, 1982 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc, 1983 Sema::CheckConstexprKind Kind) { 1984 // - its function-body shall be [...] a compound-statement that contains only 1985 switch (S->getStmtClass()) { 1986 case Stmt::NullStmtClass: 1987 // - null statements, 1988 return true; 1989 1990 case Stmt::DeclStmtClass: 1991 // - static_assert-declarations 1992 // - using-declarations, 1993 // - using-directives, 1994 // - typedef declarations and alias-declarations that do not define 1995 // classes or enumerations, 1996 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind)) 1997 return false; 1998 return true; 1999 2000 case Stmt::ReturnStmtClass: 2001 // - and exactly one return statement; 2002 if (isa<CXXConstructorDecl>(Dcl)) { 2003 // C++1y allows return statements in constexpr constructors. 2004 if (!Cxx1yLoc.isValid()) 2005 Cxx1yLoc = S->getBeginLoc(); 2006 return true; 2007 } 2008 2009 ReturnStmts.push_back(S->getBeginLoc()); 2010 return true; 2011 2012 case Stmt::CompoundStmtClass: { 2013 // C++1y allows compound-statements. 2014 if (!Cxx1yLoc.isValid()) 2015 Cxx1yLoc = S->getBeginLoc(); 2016 2017 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 2018 for (auto *BodyIt : CompStmt->body()) { 2019 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 2020 Cxx1yLoc, Cxx2aLoc, Kind)) 2021 return false; 2022 } 2023 return true; 2024 } 2025 2026 case Stmt::AttributedStmtClass: 2027 if (!Cxx1yLoc.isValid()) 2028 Cxx1yLoc = S->getBeginLoc(); 2029 return true; 2030 2031 case Stmt::IfStmtClass: { 2032 // C++1y allows if-statements. 2033 if (!Cxx1yLoc.isValid()) 2034 Cxx1yLoc = S->getBeginLoc(); 2035 2036 IfStmt *If = cast<IfStmt>(S); 2037 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 2038 Cxx1yLoc, Cxx2aLoc, Kind)) 2039 return false; 2040 if (If->getElse() && 2041 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 2042 Cxx1yLoc, Cxx2aLoc, Kind)) 2043 return false; 2044 return true; 2045 } 2046 2047 case Stmt::WhileStmtClass: 2048 case Stmt::DoStmtClass: 2049 case Stmt::ForStmtClass: 2050 case Stmt::CXXForRangeStmtClass: 2051 case Stmt::ContinueStmtClass: 2052 // C++1y allows all of these. We don't allow them as extensions in C++11, 2053 // because they don't make sense without variable mutation. 2054 if (!SemaRef.getLangOpts().CPlusPlus14) 2055 break; 2056 if (!Cxx1yLoc.isValid()) 2057 Cxx1yLoc = S->getBeginLoc(); 2058 for (Stmt *SubStmt : S->children()) 2059 if (SubStmt && 2060 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2061 Cxx1yLoc, Cxx2aLoc, Kind)) 2062 return false; 2063 return true; 2064 2065 case Stmt::SwitchStmtClass: 2066 case Stmt::CaseStmtClass: 2067 case Stmt::DefaultStmtClass: 2068 case Stmt::BreakStmtClass: 2069 // C++1y allows switch-statements, and since they don't need variable 2070 // mutation, we can reasonably allow them in C++11 as an extension. 2071 if (!Cxx1yLoc.isValid()) 2072 Cxx1yLoc = S->getBeginLoc(); 2073 for (Stmt *SubStmt : S->children()) 2074 if (SubStmt && 2075 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2076 Cxx1yLoc, Cxx2aLoc, Kind)) 2077 return false; 2078 return true; 2079 2080 case Stmt::GCCAsmStmtClass: 2081 case Stmt::MSAsmStmtClass: 2082 // C++2a allows inline assembly statements. 2083 case Stmt::CXXTryStmtClass: 2084 if (Cxx2aLoc.isInvalid()) 2085 Cxx2aLoc = S->getBeginLoc(); 2086 for (Stmt *SubStmt : S->children()) { 2087 if (SubStmt && 2088 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2089 Cxx1yLoc, Cxx2aLoc, Kind)) 2090 return false; 2091 } 2092 return true; 2093 2094 case Stmt::CXXCatchStmtClass: 2095 // Do not bother checking the language mode (already covered by the 2096 // try block check). 2097 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, 2098 cast<CXXCatchStmt>(S)->getHandlerBlock(), 2099 ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind)) 2100 return false; 2101 return true; 2102 2103 default: 2104 if (!isa<Expr>(S)) 2105 break; 2106 2107 // C++1y allows expression-statements. 2108 if (!Cxx1yLoc.isValid()) 2109 Cxx1yLoc = S->getBeginLoc(); 2110 return true; 2111 } 2112 2113 if (Kind == Sema::CheckConstexprKind::Diagnose) { 2114 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 2115 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 2116 } 2117 return false; 2118 } 2119 2120 /// Check the body for the given constexpr function declaration only contains 2121 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 2122 /// 2123 /// \return true if the body is OK, false if we have found or diagnosed a 2124 /// problem. 2125 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, 2126 Stmt *Body, 2127 Sema::CheckConstexprKind Kind) { 2128 SmallVector<SourceLocation, 4> ReturnStmts; 2129 2130 if (isa<CXXTryStmt>(Body)) { 2131 // C++11 [dcl.constexpr]p3: 2132 // The definition of a constexpr function shall satisfy the following 2133 // constraints: [...] 2134 // - its function-body shall be = delete, = default, or a 2135 // compound-statement 2136 // 2137 // C++11 [dcl.constexpr]p4: 2138 // In the definition of a constexpr constructor, [...] 2139 // - its function-body shall not be a function-try-block; 2140 // 2141 // This restriction is lifted in C++2a, as long as inner statements also 2142 // apply the general constexpr rules. 2143 switch (Kind) { 2144 case Sema::CheckConstexprKind::CheckValid: 2145 if (!SemaRef.getLangOpts().CPlusPlus20) 2146 return false; 2147 break; 2148 2149 case Sema::CheckConstexprKind::Diagnose: 2150 SemaRef.Diag(Body->getBeginLoc(), 2151 !SemaRef.getLangOpts().CPlusPlus20 2152 ? diag::ext_constexpr_function_try_block_cxx20 2153 : diag::warn_cxx17_compat_constexpr_function_try_block) 2154 << isa<CXXConstructorDecl>(Dcl); 2155 break; 2156 } 2157 } 2158 2159 // - its function-body shall be [...] a compound-statement that contains only 2160 // [... list of cases ...] 2161 // 2162 // Note that walking the children here is enough to properly check for 2163 // CompoundStmt and CXXTryStmt body. 2164 SourceLocation Cxx1yLoc, Cxx2aLoc; 2165 for (Stmt *SubStmt : Body->children()) { 2166 if (SubStmt && 2167 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2168 Cxx1yLoc, Cxx2aLoc, Kind)) 2169 return false; 2170 } 2171 2172 if (Kind == Sema::CheckConstexprKind::CheckValid) { 2173 // If this is only valid as an extension, report that we don't satisfy the 2174 // constraints of the current language. 2175 if ((Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) || 2176 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17)) 2177 return false; 2178 } else if (Cxx2aLoc.isValid()) { 2179 SemaRef.Diag(Cxx2aLoc, 2180 SemaRef.getLangOpts().CPlusPlus20 2181 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt 2182 : diag::ext_constexpr_body_invalid_stmt_cxx20) 2183 << isa<CXXConstructorDecl>(Dcl); 2184 } else if (Cxx1yLoc.isValid()) { 2185 SemaRef.Diag(Cxx1yLoc, 2186 SemaRef.getLangOpts().CPlusPlus14 2187 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 2188 : diag::ext_constexpr_body_invalid_stmt) 2189 << isa<CXXConstructorDecl>(Dcl); 2190 } 2191 2192 if (const CXXConstructorDecl *Constructor 2193 = dyn_cast<CXXConstructorDecl>(Dcl)) { 2194 const CXXRecordDecl *RD = Constructor->getParent(); 2195 // DR1359: 2196 // - every non-variant non-static data member and base class sub-object 2197 // shall be initialized; 2198 // DR1460: 2199 // - if the class is a union having variant members, exactly one of them 2200 // shall be initialized; 2201 if (RD->isUnion()) { 2202 if (Constructor->getNumCtorInitializers() == 0 && 2203 RD->hasVariantMembers()) { 2204 if (Kind == Sema::CheckConstexprKind::Diagnose) { 2205 SemaRef.Diag( 2206 Dcl->getLocation(), 2207 SemaRef.getLangOpts().CPlusPlus20 2208 ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init 2209 : diag::ext_constexpr_union_ctor_no_init); 2210 } else if (!SemaRef.getLangOpts().CPlusPlus20) { 2211 return false; 2212 } 2213 } 2214 } else if (!Constructor->isDependentContext() && 2215 !Constructor->isDelegatingConstructor()) { 2216 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 2217 2218 // Skip detailed checking if we have enough initializers, and we would 2219 // allow at most one initializer per member. 2220 bool AnyAnonStructUnionMembers = false; 2221 unsigned Fields = 0; 2222 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 2223 E = RD->field_end(); I != E; ++I, ++Fields) { 2224 if (I->isAnonymousStructOrUnion()) { 2225 AnyAnonStructUnionMembers = true; 2226 break; 2227 } 2228 } 2229 // DR1460: 2230 // - if the class is a union-like class, but is not a union, for each of 2231 // its anonymous union members having variant members, exactly one of 2232 // them shall be initialized; 2233 if (AnyAnonStructUnionMembers || 2234 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 2235 // Check initialization of non-static data members. Base classes are 2236 // always initialized so do not need to be checked. Dependent bases 2237 // might not have initializers in the member initializer list. 2238 llvm::SmallSet<Decl*, 16> Inits; 2239 for (const auto *I: Constructor->inits()) { 2240 if (FieldDecl *FD = I->getMember()) 2241 Inits.insert(FD); 2242 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 2243 Inits.insert(ID->chain_begin(), ID->chain_end()); 2244 } 2245 2246 bool Diagnosed = false; 2247 for (auto *I : RD->fields()) 2248 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, 2249 Kind)) 2250 return false; 2251 } 2252 } 2253 } else { 2254 if (ReturnStmts.empty()) { 2255 // C++1y doesn't require constexpr functions to contain a 'return' 2256 // statement. We still do, unless the return type might be void, because 2257 // otherwise if there's no return statement, the function cannot 2258 // be used in a core constant expression. 2259 bool OK = SemaRef.getLangOpts().CPlusPlus14 && 2260 (Dcl->getReturnType()->isVoidType() || 2261 Dcl->getReturnType()->isDependentType()); 2262 switch (Kind) { 2263 case Sema::CheckConstexprKind::Diagnose: 2264 SemaRef.Diag(Dcl->getLocation(), 2265 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 2266 : diag::err_constexpr_body_no_return) 2267 << Dcl->isConsteval(); 2268 if (!OK) 2269 return false; 2270 break; 2271 2272 case Sema::CheckConstexprKind::CheckValid: 2273 // The formal requirements don't include this rule in C++14, even 2274 // though the "must be able to produce a constant expression" rules 2275 // still imply it in some cases. 2276 if (!SemaRef.getLangOpts().CPlusPlus14) 2277 return false; 2278 break; 2279 } 2280 } else if (ReturnStmts.size() > 1) { 2281 switch (Kind) { 2282 case Sema::CheckConstexprKind::Diagnose: 2283 SemaRef.Diag( 2284 ReturnStmts.back(), 2285 SemaRef.getLangOpts().CPlusPlus14 2286 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 2287 : diag::ext_constexpr_body_multiple_return); 2288 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 2289 SemaRef.Diag(ReturnStmts[I], 2290 diag::note_constexpr_body_previous_return); 2291 break; 2292 2293 case Sema::CheckConstexprKind::CheckValid: 2294 if (!SemaRef.getLangOpts().CPlusPlus14) 2295 return false; 2296 break; 2297 } 2298 } 2299 } 2300 2301 // C++11 [dcl.constexpr]p5: 2302 // if no function argument values exist such that the function invocation 2303 // substitution would produce a constant expression, the program is 2304 // ill-formed; no diagnostic required. 2305 // C++11 [dcl.constexpr]p3: 2306 // - every constructor call and implicit conversion used in initializing the 2307 // return value shall be one of those allowed in a constant expression. 2308 // C++11 [dcl.constexpr]p4: 2309 // - every constructor involved in initializing non-static data members and 2310 // base class sub-objects shall be a constexpr constructor. 2311 // 2312 // Note that this rule is distinct from the "requirements for a constexpr 2313 // function", so is not checked in CheckValid mode. 2314 SmallVector<PartialDiagnosticAt, 8> Diags; 2315 if (Kind == Sema::CheckConstexprKind::Diagnose && 2316 !Expr::isPotentialConstantExpr(Dcl, Diags)) { 2317 SemaRef.Diag(Dcl->getLocation(), 2318 diag::ext_constexpr_function_never_constant_expr) 2319 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 2320 for (size_t I = 0, N = Diags.size(); I != N; ++I) 2321 SemaRef.Diag(Diags[I].first, Diags[I].second); 2322 // Don't return false here: we allow this for compatibility in 2323 // system headers. 2324 } 2325 2326 return true; 2327 } 2328 2329 /// Get the class that is directly named by the current context. This is the 2330 /// class for which an unqualified-id in this scope could name a constructor 2331 /// or destructor. 2332 /// 2333 /// If the scope specifier denotes a class, this will be that class. 2334 /// If the scope specifier is empty, this will be the class whose 2335 /// member-specification we are currently within. Otherwise, there 2336 /// is no such class. 2337 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) { 2338 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2339 2340 if (SS && SS->isInvalid()) 2341 return nullptr; 2342 2343 if (SS && SS->isNotEmpty()) { 2344 DeclContext *DC = computeDeclContext(*SS, true); 2345 return dyn_cast_or_null<CXXRecordDecl>(DC); 2346 } 2347 2348 return dyn_cast_or_null<CXXRecordDecl>(CurContext); 2349 } 2350 2351 /// isCurrentClassName - Determine whether the identifier II is the 2352 /// name of the class type currently being defined. In the case of 2353 /// nested classes, this will only return true if II is the name of 2354 /// the innermost class. 2355 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S, 2356 const CXXScopeSpec *SS) { 2357 CXXRecordDecl *CurDecl = getCurrentClass(S, SS); 2358 return CurDecl && &II == CurDecl->getIdentifier(); 2359 } 2360 2361 /// Determine whether the identifier II is a typo for the name of 2362 /// the class type currently being defined. If so, update it to the identifier 2363 /// that should have been used. 2364 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 2365 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2366 2367 if (!getLangOpts().SpellChecking) 2368 return false; 2369 2370 CXXRecordDecl *CurDecl; 2371 if (SS && SS->isSet() && !SS->isInvalid()) { 2372 DeclContext *DC = computeDeclContext(*SS, true); 2373 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 2374 } else 2375 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 2376 2377 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 2378 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 2379 < II->getLength()) { 2380 II = CurDecl->getIdentifier(); 2381 return true; 2382 } 2383 2384 return false; 2385 } 2386 2387 /// Determine whether the given class is a base class of the given 2388 /// class, including looking at dependent bases. 2389 static bool findCircularInheritance(const CXXRecordDecl *Class, 2390 const CXXRecordDecl *Current) { 2391 SmallVector<const CXXRecordDecl*, 8> Queue; 2392 2393 Class = Class->getCanonicalDecl(); 2394 while (true) { 2395 for (const auto &I : Current->bases()) { 2396 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 2397 if (!Base) 2398 continue; 2399 2400 Base = Base->getDefinition(); 2401 if (!Base) 2402 continue; 2403 2404 if (Base->getCanonicalDecl() == Class) 2405 return true; 2406 2407 Queue.push_back(Base); 2408 } 2409 2410 if (Queue.empty()) 2411 return false; 2412 2413 Current = Queue.pop_back_val(); 2414 } 2415 2416 return false; 2417 } 2418 2419 /// Check the validity of a C++ base class specifier. 2420 /// 2421 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 2422 /// and returns NULL otherwise. 2423 CXXBaseSpecifier * 2424 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 2425 SourceRange SpecifierRange, 2426 bool Virtual, AccessSpecifier Access, 2427 TypeSourceInfo *TInfo, 2428 SourceLocation EllipsisLoc) { 2429 QualType BaseType = TInfo->getType(); 2430 if (BaseType->containsErrors()) { 2431 // Already emitted a diagnostic when parsing the error type. 2432 return nullptr; 2433 } 2434 // C++ [class.union]p1: 2435 // A union shall not have base classes. 2436 if (Class->isUnion()) { 2437 Diag(Class->getLocation(), diag::err_base_clause_on_union) 2438 << SpecifierRange; 2439 return nullptr; 2440 } 2441 2442 if (EllipsisLoc.isValid() && 2443 !TInfo->getType()->containsUnexpandedParameterPack()) { 2444 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2445 << TInfo->getTypeLoc().getSourceRange(); 2446 EllipsisLoc = SourceLocation(); 2447 } 2448 2449 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 2450 2451 if (BaseType->isDependentType()) { 2452 // Make sure that we don't have circular inheritance among our dependent 2453 // bases. For non-dependent bases, the check for completeness below handles 2454 // this. 2455 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 2456 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 2457 ((BaseDecl = BaseDecl->getDefinition()) && 2458 findCircularInheritance(Class, BaseDecl))) { 2459 Diag(BaseLoc, diag::err_circular_inheritance) 2460 << BaseType << Context.getTypeDeclType(Class); 2461 2462 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 2463 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 2464 << BaseType; 2465 2466 return nullptr; 2467 } 2468 } 2469 2470 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2471 Class->getTagKind() == TTK_Class, 2472 Access, TInfo, EllipsisLoc); 2473 } 2474 2475 // Base specifiers must be record types. 2476 if (!BaseType->isRecordType()) { 2477 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 2478 return nullptr; 2479 } 2480 2481 // C++ [class.union]p1: 2482 // A union shall not be used as a base class. 2483 if (BaseType->isUnionType()) { 2484 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 2485 return nullptr; 2486 } 2487 2488 // For the MS ABI, propagate DLL attributes to base class templates. 2489 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 2490 if (Attr *ClassAttr = getDLLAttr(Class)) { 2491 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 2492 BaseType->getAsCXXRecordDecl())) { 2493 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate, 2494 BaseLoc); 2495 } 2496 } 2497 } 2498 2499 // C++ [class.derived]p2: 2500 // The class-name in a base-specifier shall not be an incompletely 2501 // defined class. 2502 if (RequireCompleteType(BaseLoc, BaseType, 2503 diag::err_incomplete_base_class, SpecifierRange)) { 2504 Class->setInvalidDecl(); 2505 return nullptr; 2506 } 2507 2508 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 2509 RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl(); 2510 assert(BaseDecl && "Record type has no declaration"); 2511 BaseDecl = BaseDecl->getDefinition(); 2512 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 2513 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 2514 assert(CXXBaseDecl && "Base type is not a C++ type"); 2515 2516 // Microsoft docs say: 2517 // "If a base-class has a code_seg attribute, derived classes must have the 2518 // same attribute." 2519 const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>(); 2520 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>(); 2521 if ((DerivedCSA || BaseCSA) && 2522 (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) { 2523 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base); 2524 Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here) 2525 << CXXBaseDecl; 2526 return nullptr; 2527 } 2528 2529 // A class which contains a flexible array member is not suitable for use as a 2530 // base class: 2531 // - If the layout determines that a base comes before another base, 2532 // the flexible array member would index into the subsequent base. 2533 // - If the layout determines that base comes before the derived class, 2534 // the flexible array member would index into the derived class. 2535 if (CXXBaseDecl->hasFlexibleArrayMember()) { 2536 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 2537 << CXXBaseDecl->getDeclName(); 2538 return nullptr; 2539 } 2540 2541 // C++ [class]p3: 2542 // If a class is marked final and it appears as a base-type-specifier in 2543 // base-clause, the program is ill-formed. 2544 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 2545 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 2546 << CXXBaseDecl->getDeclName() 2547 << FA->isSpelledAsSealed(); 2548 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 2549 << CXXBaseDecl->getDeclName() << FA->getRange(); 2550 return nullptr; 2551 } 2552 2553 if (BaseDecl->isInvalidDecl()) 2554 Class->setInvalidDecl(); 2555 2556 // Create the base specifier. 2557 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2558 Class->getTagKind() == TTK_Class, 2559 Access, TInfo, EllipsisLoc); 2560 } 2561 2562 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 2563 /// one entry in the base class list of a class specifier, for 2564 /// example: 2565 /// class foo : public bar, virtual private baz { 2566 /// 'public bar' and 'virtual private baz' are each base-specifiers. 2567 BaseResult 2568 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 2569 ParsedAttributes &Attributes, 2570 bool Virtual, AccessSpecifier Access, 2571 ParsedType basetype, SourceLocation BaseLoc, 2572 SourceLocation EllipsisLoc) { 2573 if (!classdecl) 2574 return true; 2575 2576 AdjustDeclIfTemplate(classdecl); 2577 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 2578 if (!Class) 2579 return true; 2580 2581 // We haven't yet attached the base specifiers. 2582 Class->setIsParsingBaseSpecifiers(); 2583 2584 // We do not support any C++11 attributes on base-specifiers yet. 2585 // Diagnose any attributes we see. 2586 for (const ParsedAttr &AL : Attributes) { 2587 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute) 2588 continue; 2589 Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute 2590 ? (unsigned)diag::warn_unknown_attribute_ignored 2591 : (unsigned)diag::err_base_specifier_attribute) 2592 << AL; 2593 } 2594 2595 TypeSourceInfo *TInfo = nullptr; 2596 GetTypeFromParser(basetype, &TInfo); 2597 2598 if (EllipsisLoc.isInvalid() && 2599 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 2600 UPPC_BaseType)) 2601 return true; 2602 2603 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 2604 Virtual, Access, TInfo, 2605 EllipsisLoc)) 2606 return BaseSpec; 2607 else 2608 Class->setInvalidDecl(); 2609 2610 return true; 2611 } 2612 2613 /// Use small set to collect indirect bases. As this is only used 2614 /// locally, there's no need to abstract the small size parameter. 2615 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet; 2616 2617 /// Recursively add the bases of Type. Don't add Type itself. 2618 static void 2619 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, 2620 const QualType &Type) 2621 { 2622 // Even though the incoming type is a base, it might not be 2623 // a class -- it could be a template parm, for instance. 2624 if (auto Rec = Type->getAs<RecordType>()) { 2625 auto Decl = Rec->getAsCXXRecordDecl(); 2626 2627 // Iterate over its bases. 2628 for (const auto &BaseSpec : Decl->bases()) { 2629 QualType Base = Context.getCanonicalType(BaseSpec.getType()) 2630 .getUnqualifiedType(); 2631 if (Set.insert(Base).second) 2632 // If we've not already seen it, recurse. 2633 NoteIndirectBases(Context, Set, Base); 2634 } 2635 } 2636 } 2637 2638 /// Performs the actual work of attaching the given base class 2639 /// specifiers to a C++ class. 2640 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, 2641 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2642 if (Bases.empty()) 2643 return false; 2644 2645 // Used to keep track of which base types we have already seen, so 2646 // that we can properly diagnose redundant direct base types. Note 2647 // that the key is always the unqualified canonical type of the base 2648 // class. 2649 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 2650 2651 // Used to track indirect bases so we can see if a direct base is 2652 // ambiguous. 2653 IndirectBaseSet IndirectBaseTypes; 2654 2655 // Copy non-redundant base specifiers into permanent storage. 2656 unsigned NumGoodBases = 0; 2657 bool Invalid = false; 2658 for (unsigned idx = 0; idx < Bases.size(); ++idx) { 2659 QualType NewBaseType 2660 = Context.getCanonicalType(Bases[idx]->getType()); 2661 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 2662 2663 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 2664 if (KnownBase) { 2665 // C++ [class.mi]p3: 2666 // A class shall not be specified as a direct base class of a 2667 // derived class more than once. 2668 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class) 2669 << KnownBase->getType() << Bases[idx]->getSourceRange(); 2670 2671 // Delete the duplicate base class specifier; we're going to 2672 // overwrite its pointer later. 2673 Context.Deallocate(Bases[idx]); 2674 2675 Invalid = true; 2676 } else { 2677 // Okay, add this new base class. 2678 KnownBase = Bases[idx]; 2679 Bases[NumGoodBases++] = Bases[idx]; 2680 2681 // Note this base's direct & indirect bases, if there could be ambiguity. 2682 if (Bases.size() > 1) 2683 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType); 2684 2685 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 2686 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 2687 if (Class->isInterface() && 2688 (!RD->isInterfaceLike() || 2689 KnownBase->getAccessSpecifier() != AS_public)) { 2690 // The Microsoft extension __interface does not permit bases that 2691 // are not themselves public interfaces. 2692 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface) 2693 << getRecordDiagFromTagKind(RD->getTagKind()) << RD 2694 << RD->getSourceRange(); 2695 Invalid = true; 2696 } 2697 if (RD->hasAttr<WeakAttr>()) 2698 Class->addAttr(WeakAttr::CreateImplicit(Context)); 2699 } 2700 } 2701 } 2702 2703 // Attach the remaining base class specifiers to the derived class. 2704 Class->setBases(Bases.data(), NumGoodBases); 2705 2706 // Check that the only base classes that are duplicate are virtual. 2707 for (unsigned idx = 0; idx < NumGoodBases; ++idx) { 2708 // Check whether this direct base is inaccessible due to ambiguity. 2709 QualType BaseType = Bases[idx]->getType(); 2710 2711 // Skip all dependent types in templates being used as base specifiers. 2712 // Checks below assume that the base specifier is a CXXRecord. 2713 if (BaseType->isDependentType()) 2714 continue; 2715 2716 CanQualType CanonicalBase = Context.getCanonicalType(BaseType) 2717 .getUnqualifiedType(); 2718 2719 if (IndirectBaseTypes.count(CanonicalBase)) { 2720 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2721 /*DetectVirtual=*/true); 2722 bool found 2723 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); 2724 assert(found); 2725 (void)found; 2726 2727 if (Paths.isAmbiguous(CanonicalBase)) 2728 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class) 2729 << BaseType << getAmbiguousPathsDisplayString(Paths) 2730 << Bases[idx]->getSourceRange(); 2731 else 2732 assert(Bases[idx]->isVirtual()); 2733 } 2734 2735 // Delete the base class specifier, since its data has been copied 2736 // into the CXXRecordDecl. 2737 Context.Deallocate(Bases[idx]); 2738 } 2739 2740 return Invalid; 2741 } 2742 2743 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 2744 /// class, after checking whether there are any duplicate base 2745 /// classes. 2746 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, 2747 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2748 if (!ClassDecl || Bases.empty()) 2749 return; 2750 2751 AdjustDeclIfTemplate(ClassDecl); 2752 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases); 2753 } 2754 2755 /// Determine whether the type \p Derived is a C++ class that is 2756 /// derived from the type \p Base. 2757 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) { 2758 if (!getLangOpts().CPlusPlus) 2759 return false; 2760 2761 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2762 if (!DerivedRD) 2763 return false; 2764 2765 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2766 if (!BaseRD) 2767 return false; 2768 2769 // If either the base or the derived type is invalid, don't try to 2770 // check whether one is derived from the other. 2771 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 2772 return false; 2773 2774 // FIXME: In a modules build, do we need the entire path to be visible for us 2775 // to be able to use the inheritance relationship? 2776 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2777 return false; 2778 2779 return DerivedRD->isDerivedFrom(BaseRD); 2780 } 2781 2782 /// Determine whether the type \p Derived is a C++ class that is 2783 /// derived from the type \p Base. 2784 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, 2785 CXXBasePaths &Paths) { 2786 if (!getLangOpts().CPlusPlus) 2787 return false; 2788 2789 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2790 if (!DerivedRD) 2791 return false; 2792 2793 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2794 if (!BaseRD) 2795 return false; 2796 2797 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2798 return false; 2799 2800 return DerivedRD->isDerivedFrom(BaseRD, Paths); 2801 } 2802 2803 static void BuildBasePathArray(const CXXBasePath &Path, 2804 CXXCastPath &BasePathArray) { 2805 // We first go backward and check if we have a virtual base. 2806 // FIXME: It would be better if CXXBasePath had the base specifier for 2807 // the nearest virtual base. 2808 unsigned Start = 0; 2809 for (unsigned I = Path.size(); I != 0; --I) { 2810 if (Path[I - 1].Base->isVirtual()) { 2811 Start = I - 1; 2812 break; 2813 } 2814 } 2815 2816 // Now add all bases. 2817 for (unsigned I = Start, E = Path.size(); I != E; ++I) 2818 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 2819 } 2820 2821 2822 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 2823 CXXCastPath &BasePathArray) { 2824 assert(BasePathArray.empty() && "Base path array must be empty!"); 2825 assert(Paths.isRecordingPaths() && "Must record paths!"); 2826 return ::BuildBasePathArray(Paths.front(), BasePathArray); 2827 } 2828 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 2829 /// conversion (where Derived and Base are class types) is 2830 /// well-formed, meaning that the conversion is unambiguous (and 2831 /// that all of the base classes are accessible). Returns true 2832 /// and emits a diagnostic if the code is ill-formed, returns false 2833 /// otherwise. Loc is the location where this routine should point to 2834 /// if there is an error, and Range is the source range to highlight 2835 /// if there is an error. 2836 /// 2837 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the 2838 /// diagnostic for the respective type of error will be suppressed, but the 2839 /// check for ill-formed code will still be performed. 2840 bool 2841 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2842 unsigned InaccessibleBaseID, 2843 unsigned AmbiguousBaseConvID, 2844 SourceLocation Loc, SourceRange Range, 2845 DeclarationName Name, 2846 CXXCastPath *BasePath, 2847 bool IgnoreAccess) { 2848 // First, determine whether the path from Derived to Base is 2849 // ambiguous. This is slightly more expensive than checking whether 2850 // the Derived to Base conversion exists, because here we need to 2851 // explore multiple paths to determine if there is an ambiguity. 2852 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2853 /*DetectVirtual=*/false); 2854 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2855 if (!DerivationOkay) 2856 return true; 2857 2858 const CXXBasePath *Path = nullptr; 2859 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) 2860 Path = &Paths.front(); 2861 2862 // For MSVC compatibility, check if Derived directly inherits from Base. Clang 2863 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the 2864 // user to access such bases. 2865 if (!Path && getLangOpts().MSVCCompat) { 2866 for (const CXXBasePath &PossiblePath : Paths) { 2867 if (PossiblePath.size() == 1) { 2868 Path = &PossiblePath; 2869 if (AmbiguousBaseConvID) 2870 Diag(Loc, diag::ext_ms_ambiguous_direct_base) 2871 << Base << Derived << Range; 2872 break; 2873 } 2874 } 2875 } 2876 2877 if (Path) { 2878 if (!IgnoreAccess) { 2879 // Check that the base class can be accessed. 2880 switch ( 2881 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) { 2882 case AR_inaccessible: 2883 return true; 2884 case AR_accessible: 2885 case AR_dependent: 2886 case AR_delayed: 2887 break; 2888 } 2889 } 2890 2891 // Build a base path if necessary. 2892 if (BasePath) 2893 ::BuildBasePathArray(*Path, *BasePath); 2894 return false; 2895 } 2896 2897 if (AmbiguousBaseConvID) { 2898 // We know that the derived-to-base conversion is ambiguous, and 2899 // we're going to produce a diagnostic. Perform the derived-to-base 2900 // search just one more time to compute all of the possible paths so 2901 // that we can print them out. This is more expensive than any of 2902 // the previous derived-to-base checks we've done, but at this point 2903 // performance isn't as much of an issue. 2904 Paths.clear(); 2905 Paths.setRecordingPaths(true); 2906 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2907 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 2908 (void)StillOkay; 2909 2910 // Build up a textual representation of the ambiguous paths, e.g., 2911 // D -> B -> A, that will be used to illustrate the ambiguous 2912 // conversions in the diagnostic. We only print one of the paths 2913 // to each base class subobject. 2914 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2915 2916 Diag(Loc, AmbiguousBaseConvID) 2917 << Derived << Base << PathDisplayStr << Range << Name; 2918 } 2919 return true; 2920 } 2921 2922 bool 2923 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2924 SourceLocation Loc, SourceRange Range, 2925 CXXCastPath *BasePath, 2926 bool IgnoreAccess) { 2927 return CheckDerivedToBaseConversion( 2928 Derived, Base, diag::err_upcast_to_inaccessible_base, 2929 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(), 2930 BasePath, IgnoreAccess); 2931 } 2932 2933 2934 /// Builds a string representing ambiguous paths from a 2935 /// specific derived class to different subobjects of the same base 2936 /// class. 2937 /// 2938 /// This function builds a string that can be used in error messages 2939 /// to show the different paths that one can take through the 2940 /// inheritance hierarchy to go from the derived class to different 2941 /// subobjects of a base class. The result looks something like this: 2942 /// @code 2943 /// struct D -> struct B -> struct A 2944 /// struct D -> struct C -> struct A 2945 /// @endcode 2946 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 2947 std::string PathDisplayStr; 2948 std::set<unsigned> DisplayedPaths; 2949 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2950 Path != Paths.end(); ++Path) { 2951 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 2952 // We haven't displayed a path to this particular base 2953 // class subobject yet. 2954 PathDisplayStr += "\n "; 2955 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 2956 for (CXXBasePath::const_iterator Element = Path->begin(); 2957 Element != Path->end(); ++Element) 2958 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 2959 } 2960 } 2961 2962 return PathDisplayStr; 2963 } 2964 2965 //===----------------------------------------------------------------------===// 2966 // C++ class member Handling 2967 //===----------------------------------------------------------------------===// 2968 2969 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 2970 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, 2971 SourceLocation ColonLoc, 2972 const ParsedAttributesView &Attrs) { 2973 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 2974 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 2975 ASLoc, ColonLoc); 2976 CurContext->addHiddenDecl(ASDecl); 2977 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 2978 } 2979 2980 /// CheckOverrideControl - Check C++11 override control semantics. 2981 void Sema::CheckOverrideControl(NamedDecl *D) { 2982 if (D->isInvalidDecl()) 2983 return; 2984 2985 // We only care about "override" and "final" declarations. 2986 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 2987 return; 2988 2989 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 2990 2991 // We can't check dependent instance methods. 2992 if (MD && MD->isInstance() && 2993 (MD->getParent()->hasAnyDependentBases() || 2994 MD->getType()->isDependentType())) 2995 return; 2996 2997 if (MD && !MD->isVirtual()) { 2998 // If we have a non-virtual method, check if if hides a virtual method. 2999 // (In that case, it's most likely the method has the wrong type.) 3000 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 3001 FindHiddenVirtualMethods(MD, OverloadedMethods); 3002 3003 if (!OverloadedMethods.empty()) { 3004 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 3005 Diag(OA->getLocation(), 3006 diag::override_keyword_hides_virtual_member_function) 3007 << "override" << (OverloadedMethods.size() > 1); 3008 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 3009 Diag(FA->getLocation(), 3010 diag::override_keyword_hides_virtual_member_function) 3011 << (FA->isSpelledAsSealed() ? "sealed" : "final") 3012 << (OverloadedMethods.size() > 1); 3013 } 3014 NoteHiddenVirtualMethods(MD, OverloadedMethods); 3015 MD->setInvalidDecl(); 3016 return; 3017 } 3018 // Fall through into the general case diagnostic. 3019 // FIXME: We might want to attempt typo correction here. 3020 } 3021 3022 if (!MD || !MD->isVirtual()) { 3023 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 3024 Diag(OA->getLocation(), 3025 diag::override_keyword_only_allowed_on_virtual_member_functions) 3026 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 3027 D->dropAttr<OverrideAttr>(); 3028 } 3029 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 3030 Diag(FA->getLocation(), 3031 diag::override_keyword_only_allowed_on_virtual_member_functions) 3032 << (FA->isSpelledAsSealed() ? "sealed" : "final") 3033 << FixItHint::CreateRemoval(FA->getLocation()); 3034 D->dropAttr<FinalAttr>(); 3035 } 3036 return; 3037 } 3038 3039 // C++11 [class.virtual]p5: 3040 // If a function is marked with the virt-specifier override and 3041 // does not override a member function of a base class, the program is 3042 // ill-formed. 3043 bool HasOverriddenMethods = MD->size_overridden_methods() != 0; 3044 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 3045 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 3046 << MD->getDeclName(); 3047 } 3048 3049 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) { 3050 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) 3051 return; 3052 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 3053 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>()) 3054 return; 3055 3056 SourceLocation Loc = MD->getLocation(); 3057 SourceLocation SpellingLoc = Loc; 3058 if (getSourceManager().isMacroArgExpansion(Loc)) 3059 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin(); 3060 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); 3061 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) 3062 return; 3063 3064 if (MD->size_overridden_methods() > 0) { 3065 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) { 3066 unsigned DiagID = 3067 Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation()) 3068 ? DiagInconsistent 3069 : DiagSuggest; 3070 Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 3071 const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); 3072 Diag(OMD->getLocation(), diag::note_overridden_virtual_function); 3073 }; 3074 if (isa<CXXDestructorDecl>(MD)) 3075 EmitDiag( 3076 diag::warn_inconsistent_destructor_marked_not_override_overriding, 3077 diag::warn_suggest_destructor_marked_not_override_overriding); 3078 else 3079 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding, 3080 diag::warn_suggest_function_marked_not_override_overriding); 3081 } 3082 } 3083 3084 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 3085 /// function overrides a virtual member function marked 'final', according to 3086 /// C++11 [class.virtual]p4. 3087 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 3088 const CXXMethodDecl *Old) { 3089 FinalAttr *FA = Old->getAttr<FinalAttr>(); 3090 if (!FA) 3091 return false; 3092 3093 Diag(New->getLocation(), diag::err_final_function_overridden) 3094 << New->getDeclName() 3095 << FA->isSpelledAsSealed(); 3096 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 3097 return true; 3098 } 3099 3100 static bool InitializationHasSideEffects(const FieldDecl &FD) { 3101 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 3102 // FIXME: Destruction of ObjC lifetime types has side-effects. 3103 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 3104 return !RD->isCompleteDefinition() || 3105 !RD->hasTrivialDefaultConstructor() || 3106 !RD->hasTrivialDestructor(); 3107 return false; 3108 } 3109 3110 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) { 3111 ParsedAttributesView::const_iterator Itr = 3112 llvm::find_if(list, [](const ParsedAttr &AL) { 3113 return AL.isDeclspecPropertyAttribute(); 3114 }); 3115 if (Itr != list.end()) 3116 return &*Itr; 3117 return nullptr; 3118 } 3119 3120 // Check if there is a field shadowing. 3121 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc, 3122 DeclarationName FieldName, 3123 const CXXRecordDecl *RD, 3124 bool DeclIsField) { 3125 if (Diags.isIgnored(diag::warn_shadow_field, Loc)) 3126 return; 3127 3128 // To record a shadowed field in a base 3129 std::map<CXXRecordDecl*, NamedDecl*> Bases; 3130 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier, 3131 CXXBasePath &Path) { 3132 const auto Base = Specifier->getType()->getAsCXXRecordDecl(); 3133 // Record an ambiguous path directly 3134 if (Bases.find(Base) != Bases.end()) 3135 return true; 3136 for (const auto Field : Base->lookup(FieldName)) { 3137 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) && 3138 Field->getAccess() != AS_private) { 3139 assert(Field->getAccess() != AS_none); 3140 assert(Bases.find(Base) == Bases.end()); 3141 Bases[Base] = Field; 3142 return true; 3143 } 3144 } 3145 return false; 3146 }; 3147 3148 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3149 /*DetectVirtual=*/true); 3150 if (!RD->lookupInBases(FieldShadowed, Paths)) 3151 return; 3152 3153 for (const auto &P : Paths) { 3154 auto Base = P.back().Base->getType()->getAsCXXRecordDecl(); 3155 auto It = Bases.find(Base); 3156 // Skip duplicated bases 3157 if (It == Bases.end()) 3158 continue; 3159 auto BaseField = It->second; 3160 assert(BaseField->getAccess() != AS_private); 3161 if (AS_none != 3162 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) { 3163 Diag(Loc, diag::warn_shadow_field) 3164 << FieldName << RD << Base << DeclIsField; 3165 Diag(BaseField->getLocation(), diag::note_shadow_field); 3166 Bases.erase(It); 3167 } 3168 } 3169 } 3170 3171 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 3172 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 3173 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 3174 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 3175 /// present (but parsing it has been deferred). 3176 NamedDecl * 3177 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 3178 MultiTemplateParamsArg TemplateParameterLists, 3179 Expr *BW, const VirtSpecifiers &VS, 3180 InClassInitStyle InitStyle) { 3181 const DeclSpec &DS = D.getDeclSpec(); 3182 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 3183 DeclarationName Name = NameInfo.getName(); 3184 SourceLocation Loc = NameInfo.getLoc(); 3185 3186 // For anonymous bitfields, the location should point to the type. 3187 if (Loc.isInvalid()) 3188 Loc = D.getBeginLoc(); 3189 3190 Expr *BitWidth = static_cast<Expr*>(BW); 3191 3192 assert(isa<CXXRecordDecl>(CurContext)); 3193 assert(!DS.isFriendSpecified()); 3194 3195 bool isFunc = D.isDeclarationOfFunction(); 3196 const ParsedAttr *MSPropertyAttr = 3197 getMSPropertyAttr(D.getDeclSpec().getAttributes()); 3198 3199 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 3200 // The Microsoft extension __interface only permits public member functions 3201 // and prohibits constructors, destructors, operators, non-public member 3202 // functions, static methods and data members. 3203 unsigned InvalidDecl; 3204 bool ShowDeclName = true; 3205 if (!isFunc && 3206 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr)) 3207 InvalidDecl = 0; 3208 else if (!isFunc) 3209 InvalidDecl = 1; 3210 else if (AS != AS_public) 3211 InvalidDecl = 2; 3212 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 3213 InvalidDecl = 3; 3214 else switch (Name.getNameKind()) { 3215 case DeclarationName::CXXConstructorName: 3216 InvalidDecl = 4; 3217 ShowDeclName = false; 3218 break; 3219 3220 case DeclarationName::CXXDestructorName: 3221 InvalidDecl = 5; 3222 ShowDeclName = false; 3223 break; 3224 3225 case DeclarationName::CXXOperatorName: 3226 case DeclarationName::CXXConversionFunctionName: 3227 InvalidDecl = 6; 3228 break; 3229 3230 default: 3231 InvalidDecl = 0; 3232 break; 3233 } 3234 3235 if (InvalidDecl) { 3236 if (ShowDeclName) 3237 Diag(Loc, diag::err_invalid_member_in_interface) 3238 << (InvalidDecl-1) << Name; 3239 else 3240 Diag(Loc, diag::err_invalid_member_in_interface) 3241 << (InvalidDecl-1) << ""; 3242 return nullptr; 3243 } 3244 } 3245 3246 // C++ 9.2p6: A member shall not be declared to have automatic storage 3247 // duration (auto, register) or with the extern storage-class-specifier. 3248 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 3249 // data members and cannot be applied to names declared const or static, 3250 // and cannot be applied to reference members. 3251 switch (DS.getStorageClassSpec()) { 3252 case DeclSpec::SCS_unspecified: 3253 case DeclSpec::SCS_typedef: 3254 case DeclSpec::SCS_static: 3255 break; 3256 case DeclSpec::SCS_mutable: 3257 if (isFunc) { 3258 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 3259 3260 // FIXME: It would be nicer if the keyword was ignored only for this 3261 // declarator. Otherwise we could get follow-up errors. 3262 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3263 } 3264 break; 3265 default: 3266 Diag(DS.getStorageClassSpecLoc(), 3267 diag::err_storageclass_invalid_for_member); 3268 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3269 break; 3270 } 3271 3272 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 3273 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 3274 !isFunc); 3275 3276 if (DS.hasConstexprSpecifier() && isInstField) { 3277 SemaDiagnosticBuilder B = 3278 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 3279 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 3280 if (InitStyle == ICIS_NoInit) { 3281 B << 0 << 0; 3282 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 3283 B << FixItHint::CreateRemoval(ConstexprLoc); 3284 else { 3285 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 3286 D.getMutableDeclSpec().ClearConstexprSpec(); 3287 const char *PrevSpec; 3288 unsigned DiagID; 3289 bool Failed = D.getMutableDeclSpec().SetTypeQual( 3290 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 3291 (void)Failed; 3292 assert(!Failed && "Making a constexpr member const shouldn't fail"); 3293 } 3294 } else { 3295 B << 1; 3296 const char *PrevSpec; 3297 unsigned DiagID; 3298 if (D.getMutableDeclSpec().SetStorageClassSpec( 3299 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 3300 Context.getPrintingPolicy())) { 3301 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 3302 "This is the only DeclSpec that should fail to be applied"); 3303 B << 1; 3304 } else { 3305 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 3306 isInstField = false; 3307 } 3308 } 3309 } 3310 3311 NamedDecl *Member; 3312 if (isInstField) { 3313 CXXScopeSpec &SS = D.getCXXScopeSpec(); 3314 3315 // Data members must have identifiers for names. 3316 if (!Name.isIdentifier()) { 3317 Diag(Loc, diag::err_bad_variable_name) 3318 << Name; 3319 return nullptr; 3320 } 3321 3322 IdentifierInfo *II = Name.getAsIdentifierInfo(); 3323 3324 // Member field could not be with "template" keyword. 3325 // So TemplateParameterLists should be empty in this case. 3326 if (TemplateParameterLists.size()) { 3327 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 3328 if (TemplateParams->size()) { 3329 // There is no such thing as a member field template. 3330 Diag(D.getIdentifierLoc(), diag::err_template_member) 3331 << II 3332 << SourceRange(TemplateParams->getTemplateLoc(), 3333 TemplateParams->getRAngleLoc()); 3334 } else { 3335 // There is an extraneous 'template<>' for this member. 3336 Diag(TemplateParams->getTemplateLoc(), 3337 diag::err_template_member_noparams) 3338 << II 3339 << SourceRange(TemplateParams->getTemplateLoc(), 3340 TemplateParams->getRAngleLoc()); 3341 } 3342 return nullptr; 3343 } 3344 3345 if (SS.isSet() && !SS.isInvalid()) { 3346 // The user provided a superfluous scope specifier inside a class 3347 // definition: 3348 // 3349 // class X { 3350 // int X::member; 3351 // }; 3352 if (DeclContext *DC = computeDeclContext(SS, false)) 3353 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(), 3354 D.getName().getKind() == 3355 UnqualifiedIdKind::IK_TemplateId); 3356 else 3357 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 3358 << Name << SS.getRange(); 3359 3360 SS.clear(); 3361 } 3362 3363 if (MSPropertyAttr) { 3364 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3365 BitWidth, InitStyle, AS, *MSPropertyAttr); 3366 if (!Member) 3367 return nullptr; 3368 isInstField = false; 3369 } else { 3370 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3371 BitWidth, InitStyle, AS); 3372 if (!Member) 3373 return nullptr; 3374 } 3375 3376 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext)); 3377 } else { 3378 Member = HandleDeclarator(S, D, TemplateParameterLists); 3379 if (!Member) 3380 return nullptr; 3381 3382 // Non-instance-fields can't have a bitfield. 3383 if (BitWidth) { 3384 if (Member->isInvalidDecl()) { 3385 // don't emit another diagnostic. 3386 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) { 3387 // C++ 9.6p3: A bit-field shall not be a static member. 3388 // "static member 'A' cannot be a bit-field" 3389 Diag(Loc, diag::err_static_not_bitfield) 3390 << Name << BitWidth->getSourceRange(); 3391 } else if (isa<TypedefDecl>(Member)) { 3392 // "typedef member 'x' cannot be a bit-field" 3393 Diag(Loc, diag::err_typedef_not_bitfield) 3394 << Name << BitWidth->getSourceRange(); 3395 } else { 3396 // A function typedef ("typedef int f(); f a;"). 3397 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 3398 Diag(Loc, diag::err_not_integral_type_bitfield) 3399 << Name << cast<ValueDecl>(Member)->getType() 3400 << BitWidth->getSourceRange(); 3401 } 3402 3403 BitWidth = nullptr; 3404 Member->setInvalidDecl(); 3405 } 3406 3407 NamedDecl *NonTemplateMember = Member; 3408 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 3409 NonTemplateMember = FunTmpl->getTemplatedDecl(); 3410 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 3411 NonTemplateMember = VarTmpl->getTemplatedDecl(); 3412 3413 Member->setAccess(AS); 3414 3415 // If we have declared a member function template or static data member 3416 // template, set the access of the templated declaration as well. 3417 if (NonTemplateMember != Member) 3418 NonTemplateMember->setAccess(AS); 3419 3420 // C++ [temp.deduct.guide]p3: 3421 // A deduction guide [...] for a member class template [shall be 3422 // declared] with the same access [as the template]. 3423 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) { 3424 auto *TD = DG->getDeducedTemplate(); 3425 // Access specifiers are only meaningful if both the template and the 3426 // deduction guide are from the same scope. 3427 if (AS != TD->getAccess() && 3428 TD->getDeclContext()->getRedeclContext()->Equals( 3429 DG->getDeclContext()->getRedeclContext())) { 3430 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access); 3431 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access) 3432 << TD->getAccess(); 3433 const AccessSpecDecl *LastAccessSpec = nullptr; 3434 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) { 3435 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D)) 3436 LastAccessSpec = AccessSpec; 3437 } 3438 assert(LastAccessSpec && "differing access with no access specifier"); 3439 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access) 3440 << AS; 3441 } 3442 } 3443 } 3444 3445 if (VS.isOverrideSpecified()) 3446 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(), 3447 AttributeCommonInfo::AS_Keyword)); 3448 if (VS.isFinalSpecified()) 3449 Member->addAttr(FinalAttr::Create( 3450 Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword, 3451 static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed()))); 3452 3453 if (VS.getLastLocation().isValid()) { 3454 // Update the end location of a method that has a virt-specifiers. 3455 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 3456 MD->setRangeEnd(VS.getLastLocation()); 3457 } 3458 3459 CheckOverrideControl(Member); 3460 3461 assert((Name || isInstField) && "No identifier for non-field ?"); 3462 3463 if (isInstField) { 3464 FieldDecl *FD = cast<FieldDecl>(Member); 3465 FieldCollector->Add(FD); 3466 3467 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 3468 // Remember all explicit private FieldDecls that have a name, no side 3469 // effects and are not part of a dependent type declaration. 3470 if (!FD->isImplicit() && FD->getDeclName() && 3471 FD->getAccess() == AS_private && 3472 !FD->hasAttr<UnusedAttr>() && 3473 !FD->getParent()->isDependentContext() && 3474 !InitializationHasSideEffects(*FD)) 3475 UnusedPrivateFields.insert(FD); 3476 } 3477 } 3478 3479 return Member; 3480 } 3481 3482 namespace { 3483 class UninitializedFieldVisitor 3484 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 3485 Sema &S; 3486 // List of Decls to generate a warning on. Also remove Decls that become 3487 // initialized. 3488 llvm::SmallPtrSetImpl<ValueDecl*> &Decls; 3489 // List of base classes of the record. Classes are removed after their 3490 // initializers. 3491 llvm::SmallPtrSetImpl<QualType> &BaseClasses; 3492 // Vector of decls to be removed from the Decl set prior to visiting the 3493 // nodes. These Decls may have been initialized in the prior initializer. 3494 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; 3495 // If non-null, add a note to the warning pointing back to the constructor. 3496 const CXXConstructorDecl *Constructor; 3497 // Variables to hold state when processing an initializer list. When 3498 // InitList is true, special case initialization of FieldDecls matching 3499 // InitListFieldDecl. 3500 bool InitList; 3501 FieldDecl *InitListFieldDecl; 3502 llvm::SmallVector<unsigned, 4> InitFieldIndex; 3503 3504 public: 3505 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 3506 UninitializedFieldVisitor(Sema &S, 3507 llvm::SmallPtrSetImpl<ValueDecl*> &Decls, 3508 llvm::SmallPtrSetImpl<QualType> &BaseClasses) 3509 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), 3510 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} 3511 3512 // Returns true if the use of ME is not an uninitialized use. 3513 bool IsInitListMemberExprInitialized(MemberExpr *ME, 3514 bool CheckReferenceOnly) { 3515 llvm::SmallVector<FieldDecl*, 4> Fields; 3516 bool ReferenceField = false; 3517 while (ME) { 3518 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 3519 if (!FD) 3520 return false; 3521 Fields.push_back(FD); 3522 if (FD->getType()->isReferenceType()) 3523 ReferenceField = true; 3524 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); 3525 } 3526 3527 // Binding a reference to an uninitialized field is not an 3528 // uninitialized use. 3529 if (CheckReferenceOnly && !ReferenceField) 3530 return true; 3531 3532 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 3533 // Discard the first field since it is the field decl that is being 3534 // initialized. 3535 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) { 3536 UsedFieldIndex.push_back((*I)->getFieldIndex()); 3537 } 3538 3539 for (auto UsedIter = UsedFieldIndex.begin(), 3540 UsedEnd = UsedFieldIndex.end(), 3541 OrigIter = InitFieldIndex.begin(), 3542 OrigEnd = InitFieldIndex.end(); 3543 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 3544 if (*UsedIter < *OrigIter) 3545 return true; 3546 if (*UsedIter > *OrigIter) 3547 break; 3548 } 3549 3550 return false; 3551 } 3552 3553 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, 3554 bool AddressOf) { 3555 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 3556 return; 3557 3558 // FieldME is the inner-most MemberExpr that is not an anonymous struct 3559 // or union. 3560 MemberExpr *FieldME = ME; 3561 3562 bool AllPODFields = FieldME->getType().isPODType(S.Context); 3563 3564 Expr *Base = ME; 3565 while (MemberExpr *SubME = 3566 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { 3567 3568 if (isa<VarDecl>(SubME->getMemberDecl())) 3569 return; 3570 3571 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) 3572 if (!FD->isAnonymousStructOrUnion()) 3573 FieldME = SubME; 3574 3575 if (!FieldME->getType().isPODType(S.Context)) 3576 AllPODFields = false; 3577 3578 Base = SubME->getBase(); 3579 } 3580 3581 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) { 3582 Visit(Base); 3583 return; 3584 } 3585 3586 if (AddressOf && AllPODFields) 3587 return; 3588 3589 ValueDecl* FoundVD = FieldME->getMemberDecl(); 3590 3591 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { 3592 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { 3593 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); 3594 } 3595 3596 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { 3597 QualType T = BaseCast->getType(); 3598 if (T->isPointerType() && 3599 BaseClasses.count(T->getPointeeType())) { 3600 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) 3601 << T->getPointeeType() << FoundVD; 3602 } 3603 } 3604 } 3605 3606 if (!Decls.count(FoundVD)) 3607 return; 3608 3609 const bool IsReference = FoundVD->getType()->isReferenceType(); 3610 3611 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { 3612 // Special checking for initializer lists. 3613 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { 3614 return; 3615 } 3616 } else { 3617 // Prevent double warnings on use of unbounded references. 3618 if (CheckReferenceOnly && !IsReference) 3619 return; 3620 } 3621 3622 unsigned diag = IsReference 3623 ? diag::warn_reference_field_is_uninit 3624 : diag::warn_field_is_uninit; 3625 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 3626 if (Constructor) 3627 S.Diag(Constructor->getLocation(), 3628 diag::note_uninit_in_this_constructor) 3629 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 3630 3631 } 3632 3633 void HandleValue(Expr *E, bool AddressOf) { 3634 E = E->IgnoreParens(); 3635 3636 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3637 HandleMemberExpr(ME, false /*CheckReferenceOnly*/, 3638 AddressOf /*AddressOf*/); 3639 return; 3640 } 3641 3642 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 3643 Visit(CO->getCond()); 3644 HandleValue(CO->getTrueExpr(), AddressOf); 3645 HandleValue(CO->getFalseExpr(), AddressOf); 3646 return; 3647 } 3648 3649 if (BinaryConditionalOperator *BCO = 3650 dyn_cast<BinaryConditionalOperator>(E)) { 3651 Visit(BCO->getCond()); 3652 HandleValue(BCO->getFalseExpr(), AddressOf); 3653 return; 3654 } 3655 3656 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 3657 HandleValue(OVE->getSourceExpr(), AddressOf); 3658 return; 3659 } 3660 3661 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 3662 switch (BO->getOpcode()) { 3663 default: 3664 break; 3665 case(BO_PtrMemD): 3666 case(BO_PtrMemI): 3667 HandleValue(BO->getLHS(), AddressOf); 3668 Visit(BO->getRHS()); 3669 return; 3670 case(BO_Comma): 3671 Visit(BO->getLHS()); 3672 HandleValue(BO->getRHS(), AddressOf); 3673 return; 3674 } 3675 } 3676 3677 Visit(E); 3678 } 3679 3680 void CheckInitListExpr(InitListExpr *ILE) { 3681 InitFieldIndex.push_back(0); 3682 for (auto Child : ILE->children()) { 3683 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { 3684 CheckInitListExpr(SubList); 3685 } else { 3686 Visit(Child); 3687 } 3688 ++InitFieldIndex.back(); 3689 } 3690 InitFieldIndex.pop_back(); 3691 } 3692 3693 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, 3694 FieldDecl *Field, const Type *BaseClass) { 3695 // Remove Decls that may have been initialized in the previous 3696 // initializer. 3697 for (ValueDecl* VD : DeclsToRemove) 3698 Decls.erase(VD); 3699 DeclsToRemove.clear(); 3700 3701 Constructor = FieldConstructor; 3702 InitListExpr *ILE = dyn_cast<InitListExpr>(E); 3703 3704 if (ILE && Field) { 3705 InitList = true; 3706 InitListFieldDecl = Field; 3707 InitFieldIndex.clear(); 3708 CheckInitListExpr(ILE); 3709 } else { 3710 InitList = false; 3711 Visit(E); 3712 } 3713 3714 if (Field) 3715 Decls.erase(Field); 3716 if (BaseClass) 3717 BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); 3718 } 3719 3720 void VisitMemberExpr(MemberExpr *ME) { 3721 // All uses of unbounded reference fields will warn. 3722 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); 3723 } 3724 3725 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 3726 if (E->getCastKind() == CK_LValueToRValue) { 3727 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3728 return; 3729 } 3730 3731 Inherited::VisitImplicitCastExpr(E); 3732 } 3733 3734 void VisitCXXConstructExpr(CXXConstructExpr *E) { 3735 if (E->getConstructor()->isCopyConstructor()) { 3736 Expr *ArgExpr = E->getArg(0); 3737 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 3738 if (ILE->getNumInits() == 1) 3739 ArgExpr = ILE->getInit(0); 3740 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 3741 if (ICE->getCastKind() == CK_NoOp) 3742 ArgExpr = ICE->getSubExpr(); 3743 HandleValue(ArgExpr, false /*AddressOf*/); 3744 return; 3745 } 3746 Inherited::VisitCXXConstructExpr(E); 3747 } 3748 3749 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 3750 Expr *Callee = E->getCallee(); 3751 if (isa<MemberExpr>(Callee)) { 3752 HandleValue(Callee, false /*AddressOf*/); 3753 for (auto Arg : E->arguments()) 3754 Visit(Arg); 3755 return; 3756 } 3757 3758 Inherited::VisitCXXMemberCallExpr(E); 3759 } 3760 3761 void VisitCallExpr(CallExpr *E) { 3762 // Treat std::move as a use. 3763 if (E->isCallToStdMove()) { 3764 HandleValue(E->getArg(0), /*AddressOf=*/false); 3765 return; 3766 } 3767 3768 Inherited::VisitCallExpr(E); 3769 } 3770 3771 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 3772 Expr *Callee = E->getCallee(); 3773 3774 if (isa<UnresolvedLookupExpr>(Callee)) 3775 return Inherited::VisitCXXOperatorCallExpr(E); 3776 3777 Visit(Callee); 3778 for (auto Arg : E->arguments()) 3779 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); 3780 } 3781 3782 void VisitBinaryOperator(BinaryOperator *E) { 3783 // If a field assignment is detected, remove the field from the 3784 // uninitiailized field set. 3785 if (E->getOpcode() == BO_Assign) 3786 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 3787 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 3788 if (!FD->getType()->isReferenceType()) 3789 DeclsToRemove.push_back(FD); 3790 3791 if (E->isCompoundAssignmentOp()) { 3792 HandleValue(E->getLHS(), false /*AddressOf*/); 3793 Visit(E->getRHS()); 3794 return; 3795 } 3796 3797 Inherited::VisitBinaryOperator(E); 3798 } 3799 3800 void VisitUnaryOperator(UnaryOperator *E) { 3801 if (E->isIncrementDecrementOp()) { 3802 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3803 return; 3804 } 3805 if (E->getOpcode() == UO_AddrOf) { 3806 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { 3807 HandleValue(ME->getBase(), true /*AddressOf*/); 3808 return; 3809 } 3810 } 3811 3812 Inherited::VisitUnaryOperator(E); 3813 } 3814 }; 3815 3816 // Diagnose value-uses of fields to initialize themselves, e.g. 3817 // foo(foo) 3818 // where foo is not also a parameter to the constructor. 3819 // Also diagnose across field uninitialized use such as 3820 // x(y), y(x) 3821 // TODO: implement -Wuninitialized and fold this into that framework. 3822 static void DiagnoseUninitializedFields( 3823 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 3824 3825 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 3826 Constructor->getLocation())) { 3827 return; 3828 } 3829 3830 if (Constructor->isInvalidDecl()) 3831 return; 3832 3833 const CXXRecordDecl *RD = Constructor->getParent(); 3834 3835 if (RD->isDependentContext()) 3836 return; 3837 3838 // Holds fields that are uninitialized. 3839 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 3840 3841 // At the beginning, all fields are uninitialized. 3842 for (auto *I : RD->decls()) { 3843 if (auto *FD = dyn_cast<FieldDecl>(I)) { 3844 UninitializedFields.insert(FD); 3845 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 3846 UninitializedFields.insert(IFD->getAnonField()); 3847 } 3848 } 3849 3850 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; 3851 for (auto I : RD->bases()) 3852 UninitializedBaseClasses.insert(I.getType().getCanonicalType()); 3853 3854 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3855 return; 3856 3857 UninitializedFieldVisitor UninitializedChecker(SemaRef, 3858 UninitializedFields, 3859 UninitializedBaseClasses); 3860 3861 for (const auto *FieldInit : Constructor->inits()) { 3862 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3863 break; 3864 3865 Expr *InitExpr = FieldInit->getInit(); 3866 if (!InitExpr) 3867 continue; 3868 3869 if (CXXDefaultInitExpr *Default = 3870 dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 3871 InitExpr = Default->getExpr(); 3872 if (!InitExpr) 3873 continue; 3874 // In class initializers will point to the constructor. 3875 UninitializedChecker.CheckInitializer(InitExpr, Constructor, 3876 FieldInit->getAnyMember(), 3877 FieldInit->getBaseClass()); 3878 } else { 3879 UninitializedChecker.CheckInitializer(InitExpr, nullptr, 3880 FieldInit->getAnyMember(), 3881 FieldInit->getBaseClass()); 3882 } 3883 } 3884 } 3885 } // namespace 3886 3887 /// Enter a new C++ default initializer scope. After calling this, the 3888 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 3889 /// parsing or instantiating the initializer failed. 3890 void Sema::ActOnStartCXXInClassMemberInitializer() { 3891 // Create a synthetic function scope to represent the call to the constructor 3892 // that notionally surrounds a use of this initializer. 3893 PushFunctionScope(); 3894 } 3895 3896 void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) { 3897 if (!D.isFunctionDeclarator()) 3898 return; 3899 auto &FTI = D.getFunctionTypeInfo(); 3900 if (!FTI.Params) 3901 return; 3902 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params, 3903 FTI.NumParams)) { 3904 auto *ParamDecl = cast<NamedDecl>(Param.Param); 3905 if (ParamDecl->getDeclName()) 3906 PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false); 3907 } 3908 } 3909 3910 ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) { 3911 if (ConstraintExpr.isInvalid()) 3912 return ExprError(); 3913 return CorrectDelayedTyposInExpr(ConstraintExpr); 3914 } 3915 3916 /// This is invoked after parsing an in-class initializer for a 3917 /// non-static C++ class member, and after instantiating an in-class initializer 3918 /// in a class template. Such actions are deferred until the class is complete. 3919 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 3920 SourceLocation InitLoc, 3921 Expr *InitExpr) { 3922 // Pop the notional constructor scope we created earlier. 3923 PopFunctionScopeInfo(nullptr, D); 3924 3925 FieldDecl *FD = dyn_cast<FieldDecl>(D); 3926 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && 3927 "must set init style when field is created"); 3928 3929 if (!InitExpr) { 3930 D->setInvalidDecl(); 3931 if (FD) 3932 FD->removeInClassInitializer(); 3933 return; 3934 } 3935 3936 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 3937 FD->setInvalidDecl(); 3938 FD->removeInClassInitializer(); 3939 return; 3940 } 3941 3942 ExprResult Init = InitExpr; 3943 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 3944 InitializedEntity Entity = 3945 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD); 3946 InitializationKind Kind = 3947 FD->getInClassInitStyle() == ICIS_ListInit 3948 ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(), 3949 InitExpr->getBeginLoc(), 3950 InitExpr->getEndLoc()) 3951 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc); 3952 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 3953 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 3954 if (Init.isInvalid()) { 3955 FD->setInvalidDecl(); 3956 return; 3957 } 3958 } 3959 3960 // C++11 [class.base.init]p7: 3961 // The initialization of each base and member constitutes a 3962 // full-expression. 3963 Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false); 3964 if (Init.isInvalid()) { 3965 FD->setInvalidDecl(); 3966 return; 3967 } 3968 3969 InitExpr = Init.get(); 3970 3971 FD->setInClassInitializer(InitExpr); 3972 } 3973 3974 /// Find the direct and/or virtual base specifiers that 3975 /// correspond to the given base type, for use in base initialization 3976 /// within a constructor. 3977 static bool FindBaseInitializer(Sema &SemaRef, 3978 CXXRecordDecl *ClassDecl, 3979 QualType BaseType, 3980 const CXXBaseSpecifier *&DirectBaseSpec, 3981 const CXXBaseSpecifier *&VirtualBaseSpec) { 3982 // First, check for a direct base class. 3983 DirectBaseSpec = nullptr; 3984 for (const auto &Base : ClassDecl->bases()) { 3985 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 3986 // We found a direct base of this type. That's what we're 3987 // initializing. 3988 DirectBaseSpec = &Base; 3989 break; 3990 } 3991 } 3992 3993 // Check for a virtual base class. 3994 // FIXME: We might be able to short-circuit this if we know in advance that 3995 // there are no virtual bases. 3996 VirtualBaseSpec = nullptr; 3997 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 3998 // We haven't found a base yet; search the class hierarchy for a 3999 // virtual base class. 4000 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 4001 /*DetectVirtual=*/false); 4002 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(), 4003 SemaRef.Context.getTypeDeclType(ClassDecl), 4004 BaseType, Paths)) { 4005 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 4006 Path != Paths.end(); ++Path) { 4007 if (Path->back().Base->isVirtual()) { 4008 VirtualBaseSpec = Path->back().Base; 4009 break; 4010 } 4011 } 4012 } 4013 } 4014 4015 return DirectBaseSpec || VirtualBaseSpec; 4016 } 4017 4018 /// Handle a C++ member initializer using braced-init-list syntax. 4019 MemInitResult 4020 Sema::ActOnMemInitializer(Decl *ConstructorD, 4021 Scope *S, 4022 CXXScopeSpec &SS, 4023 IdentifierInfo *MemberOrBase, 4024 ParsedType TemplateTypeTy, 4025 const DeclSpec &DS, 4026 SourceLocation IdLoc, 4027 Expr *InitList, 4028 SourceLocation EllipsisLoc) { 4029 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 4030 DS, IdLoc, InitList, 4031 EllipsisLoc); 4032 } 4033 4034 /// Handle a C++ member initializer using parentheses syntax. 4035 MemInitResult 4036 Sema::ActOnMemInitializer(Decl *ConstructorD, 4037 Scope *S, 4038 CXXScopeSpec &SS, 4039 IdentifierInfo *MemberOrBase, 4040 ParsedType TemplateTypeTy, 4041 const DeclSpec &DS, 4042 SourceLocation IdLoc, 4043 SourceLocation LParenLoc, 4044 ArrayRef<Expr *> Args, 4045 SourceLocation RParenLoc, 4046 SourceLocation EllipsisLoc) { 4047 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc); 4048 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 4049 DS, IdLoc, List, EllipsisLoc); 4050 } 4051 4052 namespace { 4053 4054 // Callback to only accept typo corrections that can be a valid C++ member 4055 // intializer: either a non-static field member or a base class. 4056 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback { 4057 public: 4058 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 4059 : ClassDecl(ClassDecl) {} 4060 4061 bool ValidateCandidate(const TypoCorrection &candidate) override { 4062 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 4063 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 4064 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 4065 return isa<TypeDecl>(ND); 4066 } 4067 return false; 4068 } 4069 4070 std::unique_ptr<CorrectionCandidateCallback> clone() override { 4071 return std::make_unique<MemInitializerValidatorCCC>(*this); 4072 } 4073 4074 private: 4075 CXXRecordDecl *ClassDecl; 4076 }; 4077 4078 } 4079 4080 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, 4081 CXXScopeSpec &SS, 4082 ParsedType TemplateTypeTy, 4083 IdentifierInfo *MemberOrBase) { 4084 if (SS.getScopeRep() || TemplateTypeTy) 4085 return nullptr; 4086 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase); 4087 if (Result.empty()) 4088 return nullptr; 4089 ValueDecl *Member; 4090 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 4091 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) 4092 return Member; 4093 return nullptr; 4094 } 4095 4096 /// Handle a C++ member initializer. 4097 MemInitResult 4098 Sema::BuildMemInitializer(Decl *ConstructorD, 4099 Scope *S, 4100 CXXScopeSpec &SS, 4101 IdentifierInfo *MemberOrBase, 4102 ParsedType TemplateTypeTy, 4103 const DeclSpec &DS, 4104 SourceLocation IdLoc, 4105 Expr *Init, 4106 SourceLocation EllipsisLoc) { 4107 ExprResult Res = CorrectDelayedTyposInExpr(Init); 4108 if (!Res.isUsable()) 4109 return true; 4110 Init = Res.get(); 4111 4112 if (!ConstructorD) 4113 return true; 4114 4115 AdjustDeclIfTemplate(ConstructorD); 4116 4117 CXXConstructorDecl *Constructor 4118 = dyn_cast<CXXConstructorDecl>(ConstructorD); 4119 if (!Constructor) { 4120 // The user wrote a constructor initializer on a function that is 4121 // not a C++ constructor. Ignore the error for now, because we may 4122 // have more member initializers coming; we'll diagnose it just 4123 // once in ActOnMemInitializers. 4124 return true; 4125 } 4126 4127 CXXRecordDecl *ClassDecl = Constructor->getParent(); 4128 4129 // C++ [class.base.init]p2: 4130 // Names in a mem-initializer-id are looked up in the scope of the 4131 // constructor's class and, if not found in that scope, are looked 4132 // up in the scope containing the constructor's definition. 4133 // [Note: if the constructor's class contains a member with the 4134 // same name as a direct or virtual base class of the class, a 4135 // mem-initializer-id naming the member or base class and composed 4136 // of a single identifier refers to the class member. A 4137 // mem-initializer-id for the hidden base class may be specified 4138 // using a qualified name. ] 4139 4140 // Look for a member, first. 4141 if (ValueDecl *Member = tryLookupCtorInitMemberDecl( 4142 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) { 4143 if (EllipsisLoc.isValid()) 4144 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 4145 << MemberOrBase 4146 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 4147 4148 return BuildMemberInitializer(Member, Init, IdLoc); 4149 } 4150 // It didn't name a member, so see if it names a class. 4151 QualType BaseType; 4152 TypeSourceInfo *TInfo = nullptr; 4153 4154 if (TemplateTypeTy) { 4155 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 4156 if (BaseType.isNull()) 4157 return true; 4158 } else if (DS.getTypeSpecType() == TST_decltype) { 4159 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 4160 } else if (DS.getTypeSpecType() == TST_decltype_auto) { 4161 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); 4162 return true; 4163 } else { 4164 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 4165 LookupParsedName(R, S, &SS); 4166 4167 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 4168 if (!TyD) { 4169 if (R.isAmbiguous()) return true; 4170 4171 // We don't want access-control diagnostics here. 4172 R.suppressDiagnostics(); 4173 4174 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 4175 bool NotUnknownSpecialization = false; 4176 DeclContext *DC = computeDeclContext(SS, false); 4177 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 4178 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 4179 4180 if (!NotUnknownSpecialization) { 4181 // When the scope specifier can refer to a member of an unknown 4182 // specialization, we take it as a type name. 4183 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 4184 SS.getWithLocInContext(Context), 4185 *MemberOrBase, IdLoc); 4186 if (BaseType.isNull()) 4187 return true; 4188 4189 TInfo = Context.CreateTypeSourceInfo(BaseType); 4190 DependentNameTypeLoc TL = 4191 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>(); 4192 if (!TL.isNull()) { 4193 TL.setNameLoc(IdLoc); 4194 TL.setElaboratedKeywordLoc(SourceLocation()); 4195 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4196 } 4197 4198 R.clear(); 4199 R.setLookupName(MemberOrBase); 4200 } 4201 } 4202 4203 // If no results were found, try to correct typos. 4204 TypoCorrection Corr; 4205 MemInitializerValidatorCCC CCC(ClassDecl); 4206 if (R.empty() && BaseType.isNull() && 4207 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 4208 CCC, CTK_ErrorRecovery, ClassDecl))) { 4209 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 4210 // We have found a non-static data member with a similar 4211 // name to what was typed; complain and initialize that 4212 // member. 4213 diagnoseTypo(Corr, 4214 PDiag(diag::err_mem_init_not_member_or_class_suggest) 4215 << MemberOrBase << true); 4216 return BuildMemberInitializer(Member, Init, IdLoc); 4217 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 4218 const CXXBaseSpecifier *DirectBaseSpec; 4219 const CXXBaseSpecifier *VirtualBaseSpec; 4220 if (FindBaseInitializer(*this, ClassDecl, 4221 Context.getTypeDeclType(Type), 4222 DirectBaseSpec, VirtualBaseSpec)) { 4223 // We have found a direct or virtual base class with a 4224 // similar name to what was typed; complain and initialize 4225 // that base class. 4226 diagnoseTypo(Corr, 4227 PDiag(diag::err_mem_init_not_member_or_class_suggest) 4228 << MemberOrBase << false, 4229 PDiag() /*Suppress note, we provide our own.*/); 4230 4231 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 4232 : VirtualBaseSpec; 4233 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here) 4234 << BaseSpec->getType() << BaseSpec->getSourceRange(); 4235 4236 TyD = Type; 4237 } 4238 } 4239 } 4240 4241 if (!TyD && BaseType.isNull()) { 4242 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 4243 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 4244 return true; 4245 } 4246 } 4247 4248 if (BaseType.isNull()) { 4249 BaseType = Context.getTypeDeclType(TyD); 4250 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); 4251 if (SS.isSet()) { 4252 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 4253 BaseType); 4254 TInfo = Context.CreateTypeSourceInfo(BaseType); 4255 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>(); 4256 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc); 4257 TL.setElaboratedKeywordLoc(SourceLocation()); 4258 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4259 } 4260 } 4261 } 4262 4263 if (!TInfo) 4264 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 4265 4266 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 4267 } 4268 4269 MemInitResult 4270 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 4271 SourceLocation IdLoc) { 4272 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 4273 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 4274 assert((DirectMember || IndirectMember) && 4275 "Member must be a FieldDecl or IndirectFieldDecl"); 4276 4277 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4278 return true; 4279 4280 if (Member->isInvalidDecl()) 4281 return true; 4282 4283 MultiExprArg Args; 4284 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4285 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4286 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 4287 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 4288 } else { 4289 // Template instantiation doesn't reconstruct ParenListExprs for us. 4290 Args = Init; 4291 } 4292 4293 SourceRange InitRange = Init->getSourceRange(); 4294 4295 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 4296 // Can't check initialization for a member of dependent type or when 4297 // any of the arguments are type-dependent expressions. 4298 DiscardCleanupsInEvaluationContext(); 4299 } else { 4300 bool InitList = false; 4301 if (isa<InitListExpr>(Init)) { 4302 InitList = true; 4303 Args = Init; 4304 } 4305 4306 // Initialize the member. 4307 InitializedEntity MemberEntity = 4308 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 4309 : InitializedEntity::InitializeMember(IndirectMember, 4310 nullptr); 4311 InitializationKind Kind = 4312 InitList ? InitializationKind::CreateDirectList( 4313 IdLoc, Init->getBeginLoc(), Init->getEndLoc()) 4314 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 4315 InitRange.getEnd()); 4316 4317 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 4318 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 4319 nullptr); 4320 if (MemberInit.isInvalid()) 4321 return true; 4322 4323 // C++11 [class.base.init]p7: 4324 // The initialization of each base and member constitutes a 4325 // full-expression. 4326 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(), 4327 /*DiscardedValue*/ false); 4328 if (MemberInit.isInvalid()) 4329 return true; 4330 4331 Init = MemberInit.get(); 4332 } 4333 4334 if (DirectMember) { 4335 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 4336 InitRange.getBegin(), Init, 4337 InitRange.getEnd()); 4338 } else { 4339 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 4340 InitRange.getBegin(), Init, 4341 InitRange.getEnd()); 4342 } 4343 } 4344 4345 MemInitResult 4346 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 4347 CXXRecordDecl *ClassDecl) { 4348 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4349 if (!LangOpts.CPlusPlus11) 4350 return Diag(NameLoc, diag::err_delegating_ctor) 4351 << TInfo->getTypeLoc().getLocalSourceRange(); 4352 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 4353 4354 bool InitList = true; 4355 MultiExprArg Args = Init; 4356 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4357 InitList = false; 4358 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4359 } 4360 4361 SourceRange InitRange = Init->getSourceRange(); 4362 // Initialize the object. 4363 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 4364 QualType(ClassDecl->getTypeForDecl(), 0)); 4365 InitializationKind Kind = 4366 InitList ? InitializationKind::CreateDirectList( 4367 NameLoc, Init->getBeginLoc(), Init->getEndLoc()) 4368 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 4369 InitRange.getEnd()); 4370 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 4371 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 4372 Args, nullptr); 4373 if (DelegationInit.isInvalid()) 4374 return true; 4375 4376 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 4377 "Delegating constructor with no target?"); 4378 4379 // C++11 [class.base.init]p7: 4380 // The initialization of each base and member constitutes a 4381 // full-expression. 4382 DelegationInit = ActOnFinishFullExpr( 4383 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false); 4384 if (DelegationInit.isInvalid()) 4385 return true; 4386 4387 // If we are in a dependent context, template instantiation will 4388 // perform this type-checking again. Just save the arguments that we 4389 // received in a ParenListExpr. 4390 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4391 // of the information that we have about the base 4392 // initializer. However, deconstructing the ASTs is a dicey process, 4393 // and this approach is far more likely to get the corner cases right. 4394 if (CurContext->isDependentContext()) 4395 DelegationInit = Init; 4396 4397 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 4398 DelegationInit.getAs<Expr>(), 4399 InitRange.getEnd()); 4400 } 4401 4402 MemInitResult 4403 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 4404 Expr *Init, CXXRecordDecl *ClassDecl, 4405 SourceLocation EllipsisLoc) { 4406 SourceLocation BaseLoc 4407 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4408 4409 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 4410 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 4411 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4412 4413 // C++ [class.base.init]p2: 4414 // [...] Unless the mem-initializer-id names a nonstatic data 4415 // member of the constructor's class or a direct or virtual base 4416 // of that class, the mem-initializer is ill-formed. A 4417 // mem-initializer-list can initialize a base class using any 4418 // name that denotes that base class type. 4419 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 4420 4421 SourceRange InitRange = Init->getSourceRange(); 4422 if (EllipsisLoc.isValid()) { 4423 // This is a pack expansion. 4424 if (!BaseType->containsUnexpandedParameterPack()) { 4425 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 4426 << SourceRange(BaseLoc, InitRange.getEnd()); 4427 4428 EllipsisLoc = SourceLocation(); 4429 } 4430 } else { 4431 // Check for any unexpanded parameter packs. 4432 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 4433 return true; 4434 4435 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4436 return true; 4437 } 4438 4439 // Check for direct and virtual base classes. 4440 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 4441 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 4442 if (!Dependent) { 4443 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 4444 BaseType)) 4445 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 4446 4447 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 4448 VirtualBaseSpec); 4449 4450 // C++ [base.class.init]p2: 4451 // Unless the mem-initializer-id names a nonstatic data member of the 4452 // constructor's class or a direct or virtual base of that class, the 4453 // mem-initializer is ill-formed. 4454 if (!DirectBaseSpec && !VirtualBaseSpec) { 4455 // If the class has any dependent bases, then it's possible that 4456 // one of those types will resolve to the same type as 4457 // BaseType. Therefore, just treat this as a dependent base 4458 // class initialization. FIXME: Should we try to check the 4459 // initialization anyway? It seems odd. 4460 if (ClassDecl->hasAnyDependentBases()) 4461 Dependent = true; 4462 else 4463 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 4464 << BaseType << Context.getTypeDeclType(ClassDecl) 4465 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4466 } 4467 } 4468 4469 if (Dependent) { 4470 DiscardCleanupsInEvaluationContext(); 4471 4472 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4473 /*IsVirtual=*/false, 4474 InitRange.getBegin(), Init, 4475 InitRange.getEnd(), EllipsisLoc); 4476 } 4477 4478 // C++ [base.class.init]p2: 4479 // If a mem-initializer-id is ambiguous because it designates both 4480 // a direct non-virtual base class and an inherited virtual base 4481 // class, the mem-initializer is ill-formed. 4482 if (DirectBaseSpec && VirtualBaseSpec) 4483 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 4484 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4485 4486 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 4487 if (!BaseSpec) 4488 BaseSpec = VirtualBaseSpec; 4489 4490 // Initialize the base. 4491 bool InitList = true; 4492 MultiExprArg Args = Init; 4493 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4494 InitList = false; 4495 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4496 } 4497 4498 InitializedEntity BaseEntity = 4499 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 4500 InitializationKind Kind = 4501 InitList ? InitializationKind::CreateDirectList(BaseLoc) 4502 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 4503 InitRange.getEnd()); 4504 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 4505 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 4506 if (BaseInit.isInvalid()) 4507 return true; 4508 4509 // C++11 [class.base.init]p7: 4510 // The initialization of each base and member constitutes a 4511 // full-expression. 4512 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(), 4513 /*DiscardedValue*/ false); 4514 if (BaseInit.isInvalid()) 4515 return true; 4516 4517 // If we are in a dependent context, template instantiation will 4518 // perform this type-checking again. Just save the arguments that we 4519 // received in a ParenListExpr. 4520 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4521 // of the information that we have about the base 4522 // initializer. However, deconstructing the ASTs is a dicey process, 4523 // and this approach is far more likely to get the corner cases right. 4524 if (CurContext->isDependentContext()) 4525 BaseInit = Init; 4526 4527 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4528 BaseSpec->isVirtual(), 4529 InitRange.getBegin(), 4530 BaseInit.getAs<Expr>(), 4531 InitRange.getEnd(), EllipsisLoc); 4532 } 4533 4534 // Create a static_cast\<T&&>(expr). 4535 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 4536 if (T.isNull()) T = E->getType(); 4537 QualType TargetType = SemaRef.BuildReferenceType( 4538 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 4539 SourceLocation ExprLoc = E->getBeginLoc(); 4540 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 4541 TargetType, ExprLoc); 4542 4543 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 4544 SourceRange(ExprLoc, ExprLoc), 4545 E->getSourceRange()).get(); 4546 } 4547 4548 /// ImplicitInitializerKind - How an implicit base or member initializer should 4549 /// initialize its base or member. 4550 enum ImplicitInitializerKind { 4551 IIK_Default, 4552 IIK_Copy, 4553 IIK_Move, 4554 IIK_Inherit 4555 }; 4556 4557 static bool 4558 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4559 ImplicitInitializerKind ImplicitInitKind, 4560 CXXBaseSpecifier *BaseSpec, 4561 bool IsInheritedVirtualBase, 4562 CXXCtorInitializer *&CXXBaseInit) { 4563 InitializedEntity InitEntity 4564 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 4565 IsInheritedVirtualBase); 4566 4567 ExprResult BaseInit; 4568 4569 switch (ImplicitInitKind) { 4570 case IIK_Inherit: 4571 case IIK_Default: { 4572 InitializationKind InitKind 4573 = InitializationKind::CreateDefault(Constructor->getLocation()); 4574 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4575 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4576 break; 4577 } 4578 4579 case IIK_Move: 4580 case IIK_Copy: { 4581 bool Moving = ImplicitInitKind == IIK_Move; 4582 ParmVarDecl *Param = Constructor->getParamDecl(0); 4583 QualType ParamType = Param->getType().getNonReferenceType(); 4584 4585 Expr *CopyCtorArg = 4586 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4587 SourceLocation(), Param, false, 4588 Constructor->getLocation(), ParamType, 4589 VK_LValue, nullptr); 4590 4591 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 4592 4593 // Cast to the base class to avoid ambiguities. 4594 QualType ArgTy = 4595 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 4596 ParamType.getQualifiers()); 4597 4598 if (Moving) { 4599 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 4600 } 4601 4602 CXXCastPath BasePath; 4603 BasePath.push_back(BaseSpec); 4604 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 4605 CK_UncheckedDerivedToBase, 4606 Moving ? VK_XValue : VK_LValue, 4607 &BasePath).get(); 4608 4609 InitializationKind InitKind 4610 = InitializationKind::CreateDirect(Constructor->getLocation(), 4611 SourceLocation(), SourceLocation()); 4612 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 4613 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 4614 break; 4615 } 4616 } 4617 4618 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 4619 if (BaseInit.isInvalid()) 4620 return true; 4621 4622 CXXBaseInit = 4623 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4624 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 4625 SourceLocation()), 4626 BaseSpec->isVirtual(), 4627 SourceLocation(), 4628 BaseInit.getAs<Expr>(), 4629 SourceLocation(), 4630 SourceLocation()); 4631 4632 return false; 4633 } 4634 4635 static bool RefersToRValueRef(Expr *MemRef) { 4636 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 4637 return Referenced->getType()->isRValueReferenceType(); 4638 } 4639 4640 static bool 4641 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4642 ImplicitInitializerKind ImplicitInitKind, 4643 FieldDecl *Field, IndirectFieldDecl *Indirect, 4644 CXXCtorInitializer *&CXXMemberInit) { 4645 if (Field->isInvalidDecl()) 4646 return true; 4647 4648 SourceLocation Loc = Constructor->getLocation(); 4649 4650 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 4651 bool Moving = ImplicitInitKind == IIK_Move; 4652 ParmVarDecl *Param = Constructor->getParamDecl(0); 4653 QualType ParamType = Param->getType().getNonReferenceType(); 4654 4655 // Suppress copying zero-width bitfields. 4656 if (Field->isZeroLengthBitField(SemaRef.Context)) 4657 return false; 4658 4659 Expr *MemberExprBase = 4660 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4661 SourceLocation(), Param, false, 4662 Loc, ParamType, VK_LValue, nullptr); 4663 4664 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 4665 4666 if (Moving) { 4667 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 4668 } 4669 4670 // Build a reference to this field within the parameter. 4671 CXXScopeSpec SS; 4672 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 4673 Sema::LookupMemberName); 4674 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 4675 : cast<ValueDecl>(Field), AS_public); 4676 MemberLookup.resolveKind(); 4677 ExprResult CtorArg 4678 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 4679 ParamType, Loc, 4680 /*IsArrow=*/false, 4681 SS, 4682 /*TemplateKWLoc=*/SourceLocation(), 4683 /*FirstQualifierInScope=*/nullptr, 4684 MemberLookup, 4685 /*TemplateArgs=*/nullptr, 4686 /*S*/nullptr); 4687 if (CtorArg.isInvalid()) 4688 return true; 4689 4690 // C++11 [class.copy]p15: 4691 // - if a member m has rvalue reference type T&&, it is direct-initialized 4692 // with static_cast<T&&>(x.m); 4693 if (RefersToRValueRef(CtorArg.get())) { 4694 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 4695 } 4696 4697 InitializedEntity Entity = 4698 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4699 /*Implicit*/ true) 4700 : InitializedEntity::InitializeMember(Field, nullptr, 4701 /*Implicit*/ true); 4702 4703 // Direct-initialize to use the copy constructor. 4704 InitializationKind InitKind = 4705 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 4706 4707 Expr *CtorArgE = CtorArg.getAs<Expr>(); 4708 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE); 4709 ExprResult MemberInit = 4710 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1)); 4711 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4712 if (MemberInit.isInvalid()) 4713 return true; 4714 4715 if (Indirect) 4716 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4717 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4718 else 4719 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4720 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4721 return false; 4722 } 4723 4724 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 4725 "Unhandled implicit init kind!"); 4726 4727 QualType FieldBaseElementType = 4728 SemaRef.Context.getBaseElementType(Field->getType()); 4729 4730 if (FieldBaseElementType->isRecordType()) { 4731 InitializedEntity InitEntity = 4732 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4733 /*Implicit*/ true) 4734 : InitializedEntity::InitializeMember(Field, nullptr, 4735 /*Implicit*/ true); 4736 InitializationKind InitKind = 4737 InitializationKind::CreateDefault(Loc); 4738 4739 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4740 ExprResult MemberInit = 4741 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4742 4743 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4744 if (MemberInit.isInvalid()) 4745 return true; 4746 4747 if (Indirect) 4748 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4749 Indirect, Loc, 4750 Loc, 4751 MemberInit.get(), 4752 Loc); 4753 else 4754 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4755 Field, Loc, Loc, 4756 MemberInit.get(), 4757 Loc); 4758 return false; 4759 } 4760 4761 if (!Field->getParent()->isUnion()) { 4762 if (FieldBaseElementType->isReferenceType()) { 4763 SemaRef.Diag(Constructor->getLocation(), 4764 diag::err_uninitialized_member_in_ctor) 4765 << (int)Constructor->isImplicit() 4766 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4767 << 0 << Field->getDeclName(); 4768 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4769 return true; 4770 } 4771 4772 if (FieldBaseElementType.isConstQualified()) { 4773 SemaRef.Diag(Constructor->getLocation(), 4774 diag::err_uninitialized_member_in_ctor) 4775 << (int)Constructor->isImplicit() 4776 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4777 << 1 << Field->getDeclName(); 4778 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4779 return true; 4780 } 4781 } 4782 4783 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) { 4784 // ARC and Weak: 4785 // Default-initialize Objective-C pointers to NULL. 4786 CXXMemberInit 4787 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 4788 Loc, Loc, 4789 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 4790 Loc); 4791 return false; 4792 } 4793 4794 // Nothing to initialize. 4795 CXXMemberInit = nullptr; 4796 return false; 4797 } 4798 4799 namespace { 4800 struct BaseAndFieldInfo { 4801 Sema &S; 4802 CXXConstructorDecl *Ctor; 4803 bool AnyErrorsInInits; 4804 ImplicitInitializerKind IIK; 4805 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 4806 SmallVector<CXXCtorInitializer*, 8> AllToInit; 4807 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 4808 4809 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 4810 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 4811 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 4812 if (Ctor->getInheritedConstructor()) 4813 IIK = IIK_Inherit; 4814 else if (Generated && Ctor->isCopyConstructor()) 4815 IIK = IIK_Copy; 4816 else if (Generated && Ctor->isMoveConstructor()) 4817 IIK = IIK_Move; 4818 else 4819 IIK = IIK_Default; 4820 } 4821 4822 bool isImplicitCopyOrMove() const { 4823 switch (IIK) { 4824 case IIK_Copy: 4825 case IIK_Move: 4826 return true; 4827 4828 case IIK_Default: 4829 case IIK_Inherit: 4830 return false; 4831 } 4832 4833 llvm_unreachable("Invalid ImplicitInitializerKind!"); 4834 } 4835 4836 bool addFieldInitializer(CXXCtorInitializer *Init) { 4837 AllToInit.push_back(Init); 4838 4839 // Check whether this initializer makes the field "used". 4840 if (Init->getInit()->HasSideEffects(S.Context)) 4841 S.UnusedPrivateFields.remove(Init->getAnyMember()); 4842 4843 return false; 4844 } 4845 4846 bool isInactiveUnionMember(FieldDecl *Field) { 4847 RecordDecl *Record = Field->getParent(); 4848 if (!Record->isUnion()) 4849 return false; 4850 4851 if (FieldDecl *Active = 4852 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 4853 return Active != Field->getCanonicalDecl(); 4854 4855 // In an implicit copy or move constructor, ignore any in-class initializer. 4856 if (isImplicitCopyOrMove()) 4857 return true; 4858 4859 // If there's no explicit initialization, the field is active only if it 4860 // has an in-class initializer... 4861 if (Field->hasInClassInitializer()) 4862 return false; 4863 // ... or it's an anonymous struct or union whose class has an in-class 4864 // initializer. 4865 if (!Field->isAnonymousStructOrUnion()) 4866 return true; 4867 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 4868 return !FieldRD->hasInClassInitializer(); 4869 } 4870 4871 /// Determine whether the given field is, or is within, a union member 4872 /// that is inactive (because there was an initializer given for a different 4873 /// member of the union, or because the union was not initialized at all). 4874 bool isWithinInactiveUnionMember(FieldDecl *Field, 4875 IndirectFieldDecl *Indirect) { 4876 if (!Indirect) 4877 return isInactiveUnionMember(Field); 4878 4879 for (auto *C : Indirect->chain()) { 4880 FieldDecl *Field = dyn_cast<FieldDecl>(C); 4881 if (Field && isInactiveUnionMember(Field)) 4882 return true; 4883 } 4884 return false; 4885 } 4886 }; 4887 } 4888 4889 /// Determine whether the given type is an incomplete or zero-lenfgth 4890 /// array type. 4891 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 4892 if (T->isIncompleteArrayType()) 4893 return true; 4894 4895 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 4896 if (!ArrayT->getSize()) 4897 return true; 4898 4899 T = ArrayT->getElementType(); 4900 } 4901 4902 return false; 4903 } 4904 4905 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 4906 FieldDecl *Field, 4907 IndirectFieldDecl *Indirect = nullptr) { 4908 if (Field->isInvalidDecl()) 4909 return false; 4910 4911 // Overwhelmingly common case: we have a direct initializer for this field. 4912 if (CXXCtorInitializer *Init = 4913 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 4914 return Info.addFieldInitializer(Init); 4915 4916 // C++11 [class.base.init]p8: 4917 // if the entity is a non-static data member that has a 4918 // brace-or-equal-initializer and either 4919 // -- the constructor's class is a union and no other variant member of that 4920 // union is designated by a mem-initializer-id or 4921 // -- the constructor's class is not a union, and, if the entity is a member 4922 // of an anonymous union, no other member of that union is designated by 4923 // a mem-initializer-id, 4924 // the entity is initialized as specified in [dcl.init]. 4925 // 4926 // We also apply the same rules to handle anonymous structs within anonymous 4927 // unions. 4928 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 4929 return false; 4930 4931 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 4932 ExprResult DIE = 4933 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); 4934 if (DIE.isInvalid()) 4935 return true; 4936 4937 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true); 4938 SemaRef.checkInitializerLifetime(Entity, DIE.get()); 4939 4940 CXXCtorInitializer *Init; 4941 if (Indirect) 4942 Init = new (SemaRef.Context) 4943 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), 4944 SourceLocation(), DIE.get(), SourceLocation()); 4945 else 4946 Init = new (SemaRef.Context) 4947 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), 4948 SourceLocation(), DIE.get(), SourceLocation()); 4949 return Info.addFieldInitializer(Init); 4950 } 4951 4952 // Don't initialize incomplete or zero-length arrays. 4953 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 4954 return false; 4955 4956 // Don't try to build an implicit initializer if there were semantic 4957 // errors in any of the initializers (and therefore we might be 4958 // missing some that the user actually wrote). 4959 if (Info.AnyErrorsInInits) 4960 return false; 4961 4962 CXXCtorInitializer *Init = nullptr; 4963 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 4964 Indirect, Init)) 4965 return true; 4966 4967 if (!Init) 4968 return false; 4969 4970 return Info.addFieldInitializer(Init); 4971 } 4972 4973 bool 4974 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 4975 CXXCtorInitializer *Initializer) { 4976 assert(Initializer->isDelegatingInitializer()); 4977 Constructor->setNumCtorInitializers(1); 4978 CXXCtorInitializer **initializer = 4979 new (Context) CXXCtorInitializer*[1]; 4980 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 4981 Constructor->setCtorInitializers(initializer); 4982 4983 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 4984 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 4985 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 4986 } 4987 4988 DelegatingCtorDecls.push_back(Constructor); 4989 4990 DiagnoseUninitializedFields(*this, Constructor); 4991 4992 return false; 4993 } 4994 4995 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 4996 ArrayRef<CXXCtorInitializer *> Initializers) { 4997 if (Constructor->isDependentContext()) { 4998 // Just store the initializers as written, they will be checked during 4999 // instantiation. 5000 if (!Initializers.empty()) { 5001 Constructor->setNumCtorInitializers(Initializers.size()); 5002 CXXCtorInitializer **baseOrMemberInitializers = 5003 new (Context) CXXCtorInitializer*[Initializers.size()]; 5004 memcpy(baseOrMemberInitializers, Initializers.data(), 5005 Initializers.size() * sizeof(CXXCtorInitializer*)); 5006 Constructor->setCtorInitializers(baseOrMemberInitializers); 5007 } 5008 5009 // Let template instantiation know whether we had errors. 5010 if (AnyErrors) 5011 Constructor->setInvalidDecl(); 5012 5013 return false; 5014 } 5015 5016 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 5017 5018 // We need to build the initializer AST according to order of construction 5019 // and not what user specified in the Initializers list. 5020 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 5021 if (!ClassDecl) 5022 return true; 5023 5024 bool HadError = false; 5025 5026 for (unsigned i = 0; i < Initializers.size(); i++) { 5027 CXXCtorInitializer *Member = Initializers[i]; 5028 5029 if (Member->isBaseInitializer()) 5030 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 5031 else { 5032 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 5033 5034 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 5035 for (auto *C : F->chain()) { 5036 FieldDecl *FD = dyn_cast<FieldDecl>(C); 5037 if (FD && FD->getParent()->isUnion()) 5038 Info.ActiveUnionMember.insert(std::make_pair( 5039 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 5040 } 5041 } else if (FieldDecl *FD = Member->getMember()) { 5042 if (FD->getParent()->isUnion()) 5043 Info.ActiveUnionMember.insert(std::make_pair( 5044 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 5045 } 5046 } 5047 } 5048 5049 // Keep track of the direct virtual bases. 5050 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 5051 for (auto &I : ClassDecl->bases()) { 5052 if (I.isVirtual()) 5053 DirectVBases.insert(&I); 5054 } 5055 5056 // Push virtual bases before others. 5057 for (auto &VBase : ClassDecl->vbases()) { 5058 if (CXXCtorInitializer *Value 5059 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 5060 // [class.base.init]p7, per DR257: 5061 // A mem-initializer where the mem-initializer-id names a virtual base 5062 // class is ignored during execution of a constructor of any class that 5063 // is not the most derived class. 5064 if (ClassDecl->isAbstract()) { 5065 // FIXME: Provide a fixit to remove the base specifier. This requires 5066 // tracking the location of the associated comma for a base specifier. 5067 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 5068 << VBase.getType() << ClassDecl; 5069 DiagnoseAbstractType(ClassDecl); 5070 } 5071 5072 Info.AllToInit.push_back(Value); 5073 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 5074 // [class.base.init]p8, per DR257: 5075 // If a given [...] base class is not named by a mem-initializer-id 5076 // [...] and the entity is not a virtual base class of an abstract 5077 // class, then [...] the entity is default-initialized. 5078 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 5079 CXXCtorInitializer *CXXBaseInit; 5080 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 5081 &VBase, IsInheritedVirtualBase, 5082 CXXBaseInit)) { 5083 HadError = true; 5084 continue; 5085 } 5086 5087 Info.AllToInit.push_back(CXXBaseInit); 5088 } 5089 } 5090 5091 // Non-virtual bases. 5092 for (auto &Base : ClassDecl->bases()) { 5093 // Virtuals are in the virtual base list and already constructed. 5094 if (Base.isVirtual()) 5095 continue; 5096 5097 if (CXXCtorInitializer *Value 5098 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 5099 Info.AllToInit.push_back(Value); 5100 } else if (!AnyErrors) { 5101 CXXCtorInitializer *CXXBaseInit; 5102 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 5103 &Base, /*IsInheritedVirtualBase=*/false, 5104 CXXBaseInit)) { 5105 HadError = true; 5106 continue; 5107 } 5108 5109 Info.AllToInit.push_back(CXXBaseInit); 5110 } 5111 } 5112 5113 // Fields. 5114 for (auto *Mem : ClassDecl->decls()) { 5115 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 5116 // C++ [class.bit]p2: 5117 // A declaration for a bit-field that omits the identifier declares an 5118 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 5119 // initialized. 5120 if (F->isUnnamedBitfield()) 5121 continue; 5122 5123 // If we're not generating the implicit copy/move constructor, then we'll 5124 // handle anonymous struct/union fields based on their individual 5125 // indirect fields. 5126 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 5127 continue; 5128 5129 if (CollectFieldInitializer(*this, Info, F)) 5130 HadError = true; 5131 continue; 5132 } 5133 5134 // Beyond this point, we only consider default initialization. 5135 if (Info.isImplicitCopyOrMove()) 5136 continue; 5137 5138 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 5139 if (F->getType()->isIncompleteArrayType()) { 5140 assert(ClassDecl->hasFlexibleArrayMember() && 5141 "Incomplete array type is not valid"); 5142 continue; 5143 } 5144 5145 // Initialize each field of an anonymous struct individually. 5146 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 5147 HadError = true; 5148 5149 continue; 5150 } 5151 } 5152 5153 unsigned NumInitializers = Info.AllToInit.size(); 5154 if (NumInitializers > 0) { 5155 Constructor->setNumCtorInitializers(NumInitializers); 5156 CXXCtorInitializer **baseOrMemberInitializers = 5157 new (Context) CXXCtorInitializer*[NumInitializers]; 5158 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 5159 NumInitializers * sizeof(CXXCtorInitializer*)); 5160 Constructor->setCtorInitializers(baseOrMemberInitializers); 5161 5162 // Constructors implicitly reference the base and member 5163 // destructors. 5164 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 5165 Constructor->getParent()); 5166 } 5167 5168 return HadError; 5169 } 5170 5171 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 5172 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 5173 const RecordDecl *RD = RT->getDecl(); 5174 if (RD->isAnonymousStructOrUnion()) { 5175 for (auto *Field : RD->fields()) 5176 PopulateKeysForFields(Field, IdealInits); 5177 return; 5178 } 5179 } 5180 IdealInits.push_back(Field->getCanonicalDecl()); 5181 } 5182 5183 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 5184 return Context.getCanonicalType(BaseType).getTypePtr(); 5185 } 5186 5187 static const void *GetKeyForMember(ASTContext &Context, 5188 CXXCtorInitializer *Member) { 5189 if (!Member->isAnyMemberInitializer()) 5190 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 5191 5192 return Member->getAnyMember()->getCanonicalDecl(); 5193 } 5194 5195 static void DiagnoseBaseOrMemInitializerOrder( 5196 Sema &SemaRef, const CXXConstructorDecl *Constructor, 5197 ArrayRef<CXXCtorInitializer *> Inits) { 5198 if (Constructor->getDeclContext()->isDependentContext()) 5199 return; 5200 5201 // Don't check initializers order unless the warning is enabled at the 5202 // location of at least one initializer. 5203 bool ShouldCheckOrder = false; 5204 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 5205 CXXCtorInitializer *Init = Inits[InitIndex]; 5206 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 5207 Init->getSourceLocation())) { 5208 ShouldCheckOrder = true; 5209 break; 5210 } 5211 } 5212 if (!ShouldCheckOrder) 5213 return; 5214 5215 // Build the list of bases and members in the order that they'll 5216 // actually be initialized. The explicit initializers should be in 5217 // this same order but may be missing things. 5218 SmallVector<const void*, 32> IdealInitKeys; 5219 5220 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 5221 5222 // 1. Virtual bases. 5223 for (const auto &VBase : ClassDecl->vbases()) 5224 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 5225 5226 // 2. Non-virtual bases. 5227 for (const auto &Base : ClassDecl->bases()) { 5228 if (Base.isVirtual()) 5229 continue; 5230 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 5231 } 5232 5233 // 3. Direct fields. 5234 for (auto *Field : ClassDecl->fields()) { 5235 if (Field->isUnnamedBitfield()) 5236 continue; 5237 5238 PopulateKeysForFields(Field, IdealInitKeys); 5239 } 5240 5241 unsigned NumIdealInits = IdealInitKeys.size(); 5242 unsigned IdealIndex = 0; 5243 5244 CXXCtorInitializer *PrevInit = nullptr; 5245 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 5246 CXXCtorInitializer *Init = Inits[InitIndex]; 5247 const void *InitKey = GetKeyForMember(SemaRef.Context, Init); 5248 5249 // Scan forward to try to find this initializer in the idealized 5250 // initializers list. 5251 for (; IdealIndex != NumIdealInits; ++IdealIndex) 5252 if (InitKey == IdealInitKeys[IdealIndex]) 5253 break; 5254 5255 // If we didn't find this initializer, it must be because we 5256 // scanned past it on a previous iteration. That can only 5257 // happen if we're out of order; emit a warning. 5258 if (IdealIndex == NumIdealInits && PrevInit) { 5259 Sema::SemaDiagnosticBuilder D = 5260 SemaRef.Diag(PrevInit->getSourceLocation(), 5261 diag::warn_initializer_out_of_order); 5262 5263 if (PrevInit->isAnyMemberInitializer()) 5264 D << 0 << PrevInit->getAnyMember()->getDeclName(); 5265 else 5266 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 5267 5268 if (Init->isAnyMemberInitializer()) 5269 D << 0 << Init->getAnyMember()->getDeclName(); 5270 else 5271 D << 1 << Init->getTypeSourceInfo()->getType(); 5272 5273 // Move back to the initializer's location in the ideal list. 5274 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 5275 if (InitKey == IdealInitKeys[IdealIndex]) 5276 break; 5277 5278 assert(IdealIndex < NumIdealInits && 5279 "initializer not found in initializer list"); 5280 } 5281 5282 PrevInit = Init; 5283 } 5284 } 5285 5286 namespace { 5287 bool CheckRedundantInit(Sema &S, 5288 CXXCtorInitializer *Init, 5289 CXXCtorInitializer *&PrevInit) { 5290 if (!PrevInit) { 5291 PrevInit = Init; 5292 return false; 5293 } 5294 5295 if (FieldDecl *Field = Init->getAnyMember()) 5296 S.Diag(Init->getSourceLocation(), 5297 diag::err_multiple_mem_initialization) 5298 << Field->getDeclName() 5299 << Init->getSourceRange(); 5300 else { 5301 const Type *BaseClass = Init->getBaseClass(); 5302 assert(BaseClass && "neither field nor base"); 5303 S.Diag(Init->getSourceLocation(), 5304 diag::err_multiple_base_initialization) 5305 << QualType(BaseClass, 0) 5306 << Init->getSourceRange(); 5307 } 5308 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 5309 << 0 << PrevInit->getSourceRange(); 5310 5311 return true; 5312 } 5313 5314 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 5315 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 5316 5317 bool CheckRedundantUnionInit(Sema &S, 5318 CXXCtorInitializer *Init, 5319 RedundantUnionMap &Unions) { 5320 FieldDecl *Field = Init->getAnyMember(); 5321 RecordDecl *Parent = Field->getParent(); 5322 NamedDecl *Child = Field; 5323 5324 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 5325 if (Parent->isUnion()) { 5326 UnionEntry &En = Unions[Parent]; 5327 if (En.first && En.first != Child) { 5328 S.Diag(Init->getSourceLocation(), 5329 diag::err_multiple_mem_union_initialization) 5330 << Field->getDeclName() 5331 << Init->getSourceRange(); 5332 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 5333 << 0 << En.second->getSourceRange(); 5334 return true; 5335 } 5336 if (!En.first) { 5337 En.first = Child; 5338 En.second = Init; 5339 } 5340 if (!Parent->isAnonymousStructOrUnion()) 5341 return false; 5342 } 5343 5344 Child = Parent; 5345 Parent = cast<RecordDecl>(Parent->getDeclContext()); 5346 } 5347 5348 return false; 5349 } 5350 } 5351 5352 /// ActOnMemInitializers - Handle the member initializers for a constructor. 5353 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 5354 SourceLocation ColonLoc, 5355 ArrayRef<CXXCtorInitializer*> MemInits, 5356 bool AnyErrors) { 5357 if (!ConstructorDecl) 5358 return; 5359 5360 AdjustDeclIfTemplate(ConstructorDecl); 5361 5362 CXXConstructorDecl *Constructor 5363 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 5364 5365 if (!Constructor) { 5366 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 5367 return; 5368 } 5369 5370 // Mapping for the duplicate initializers check. 5371 // For member initializers, this is keyed with a FieldDecl*. 5372 // For base initializers, this is keyed with a Type*. 5373 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 5374 5375 // Mapping for the inconsistent anonymous-union initializers check. 5376 RedundantUnionMap MemberUnions; 5377 5378 bool HadError = false; 5379 for (unsigned i = 0; i < MemInits.size(); i++) { 5380 CXXCtorInitializer *Init = MemInits[i]; 5381 5382 // Set the source order index. 5383 Init->setSourceOrder(i); 5384 5385 if (Init->isAnyMemberInitializer()) { 5386 const void *Key = GetKeyForMember(Context, Init); 5387 if (CheckRedundantInit(*this, Init, Members[Key]) || 5388 CheckRedundantUnionInit(*this, Init, MemberUnions)) 5389 HadError = true; 5390 } else if (Init->isBaseInitializer()) { 5391 const void *Key = GetKeyForMember(Context, Init); 5392 if (CheckRedundantInit(*this, Init, Members[Key])) 5393 HadError = true; 5394 } else { 5395 assert(Init->isDelegatingInitializer()); 5396 // This must be the only initializer 5397 if (MemInits.size() != 1) { 5398 Diag(Init->getSourceLocation(), 5399 diag::err_delegating_initializer_alone) 5400 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 5401 // We will treat this as being the only initializer. 5402 } 5403 SetDelegatingInitializer(Constructor, MemInits[i]); 5404 // Return immediately as the initializer is set. 5405 return; 5406 } 5407 } 5408 5409 if (HadError) 5410 return; 5411 5412 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 5413 5414 SetCtorInitializers(Constructor, AnyErrors, MemInits); 5415 5416 DiagnoseUninitializedFields(*this, Constructor); 5417 } 5418 5419 void 5420 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 5421 CXXRecordDecl *ClassDecl) { 5422 // Ignore dependent contexts. Also ignore unions, since their members never 5423 // have destructors implicitly called. 5424 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 5425 return; 5426 5427 // FIXME: all the access-control diagnostics are positioned on the 5428 // field/base declaration. That's probably good; that said, the 5429 // user might reasonably want to know why the destructor is being 5430 // emitted, and we currently don't say. 5431 5432 // Non-static data members. 5433 for (auto *Field : ClassDecl->fields()) { 5434 if (Field->isInvalidDecl()) 5435 continue; 5436 5437 // Don't destroy incomplete or zero-length arrays. 5438 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 5439 continue; 5440 5441 QualType FieldType = Context.getBaseElementType(Field->getType()); 5442 5443 const RecordType* RT = FieldType->getAs<RecordType>(); 5444 if (!RT) 5445 continue; 5446 5447 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5448 if (FieldClassDecl->isInvalidDecl()) 5449 continue; 5450 if (FieldClassDecl->hasIrrelevantDestructor()) 5451 continue; 5452 // The destructor for an implicit anonymous union member is never invoked. 5453 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 5454 continue; 5455 5456 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 5457 assert(Dtor && "No dtor found for FieldClassDecl!"); 5458 CheckDestructorAccess(Field->getLocation(), Dtor, 5459 PDiag(diag::err_access_dtor_field) 5460 << Field->getDeclName() 5461 << FieldType); 5462 5463 MarkFunctionReferenced(Location, Dtor); 5464 DiagnoseUseOfDecl(Dtor, Location); 5465 } 5466 5467 // We only potentially invoke the destructors of potentially constructed 5468 // subobjects. 5469 bool VisitVirtualBases = !ClassDecl->isAbstract(); 5470 5471 // If the destructor exists and has already been marked used in the MS ABI, 5472 // then virtual base destructors have already been checked and marked used. 5473 // Skip checking them again to avoid duplicate diagnostics. 5474 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 5475 CXXDestructorDecl *Dtor = ClassDecl->getDestructor(); 5476 if (Dtor && Dtor->isUsed()) 5477 VisitVirtualBases = false; 5478 } 5479 5480 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 5481 5482 // Bases. 5483 for (const auto &Base : ClassDecl->bases()) { 5484 // Bases are always records in a well-formed non-dependent class. 5485 const RecordType *RT = Base.getType()->getAs<RecordType>(); 5486 5487 // Remember direct virtual bases. 5488 if (Base.isVirtual()) { 5489 if (!VisitVirtualBases) 5490 continue; 5491 DirectVirtualBases.insert(RT); 5492 } 5493 5494 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5495 // If our base class is invalid, we probably can't get its dtor anyway. 5496 if (BaseClassDecl->isInvalidDecl()) 5497 continue; 5498 if (BaseClassDecl->hasIrrelevantDestructor()) 5499 continue; 5500 5501 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5502 assert(Dtor && "No dtor found for BaseClassDecl!"); 5503 5504 // FIXME: caret should be on the start of the class name 5505 CheckDestructorAccess(Base.getBeginLoc(), Dtor, 5506 PDiag(diag::err_access_dtor_base) 5507 << Base.getType() << Base.getSourceRange(), 5508 Context.getTypeDeclType(ClassDecl)); 5509 5510 MarkFunctionReferenced(Location, Dtor); 5511 DiagnoseUseOfDecl(Dtor, Location); 5512 } 5513 5514 if (VisitVirtualBases) 5515 MarkVirtualBaseDestructorsReferenced(Location, ClassDecl, 5516 &DirectVirtualBases); 5517 } 5518 5519 void Sema::MarkVirtualBaseDestructorsReferenced( 5520 SourceLocation Location, CXXRecordDecl *ClassDecl, 5521 llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) { 5522 // Virtual bases. 5523 for (const auto &VBase : ClassDecl->vbases()) { 5524 // Bases are always records in a well-formed non-dependent class. 5525 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 5526 5527 // Ignore already visited direct virtual bases. 5528 if (DirectVirtualBases && DirectVirtualBases->count(RT)) 5529 continue; 5530 5531 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5532 // If our base class is invalid, we probably can't get its dtor anyway. 5533 if (BaseClassDecl->isInvalidDecl()) 5534 continue; 5535 if (BaseClassDecl->hasIrrelevantDestructor()) 5536 continue; 5537 5538 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5539 assert(Dtor && "No dtor found for BaseClassDecl!"); 5540 if (CheckDestructorAccess( 5541 ClassDecl->getLocation(), Dtor, 5542 PDiag(diag::err_access_dtor_vbase) 5543 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 5544 Context.getTypeDeclType(ClassDecl)) == 5545 AR_accessible) { 5546 CheckDerivedToBaseConversion( 5547 Context.getTypeDeclType(ClassDecl), VBase.getType(), 5548 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 5549 SourceRange(), DeclarationName(), nullptr); 5550 } 5551 5552 MarkFunctionReferenced(Location, Dtor); 5553 DiagnoseUseOfDecl(Dtor, Location); 5554 } 5555 } 5556 5557 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 5558 if (!CDtorDecl) 5559 return; 5560 5561 if (CXXConstructorDecl *Constructor 5562 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 5563 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 5564 DiagnoseUninitializedFields(*this, Constructor); 5565 } 5566 } 5567 5568 bool Sema::isAbstractType(SourceLocation Loc, QualType T) { 5569 if (!getLangOpts().CPlusPlus) 5570 return false; 5571 5572 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl(); 5573 if (!RD) 5574 return false; 5575 5576 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a 5577 // class template specialization here, but doing so breaks a lot of code. 5578 5579 // We can't answer whether something is abstract until it has a 5580 // definition. If it's currently being defined, we'll walk back 5581 // over all the declarations when we have a full definition. 5582 const CXXRecordDecl *Def = RD->getDefinition(); 5583 if (!Def || Def->isBeingDefined()) 5584 return false; 5585 5586 return RD->isAbstract(); 5587 } 5588 5589 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 5590 TypeDiagnoser &Diagnoser) { 5591 if (!isAbstractType(Loc, T)) 5592 return false; 5593 5594 T = Context.getBaseElementType(T); 5595 Diagnoser.diagnose(*this, Loc, T); 5596 DiagnoseAbstractType(T->getAsCXXRecordDecl()); 5597 return true; 5598 } 5599 5600 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 5601 // Check if we've already emitted the list of pure virtual functions 5602 // for this class. 5603 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 5604 return; 5605 5606 // If the diagnostic is suppressed, don't emit the notes. We're only 5607 // going to emit them once, so try to attach them to a diagnostic we're 5608 // actually going to show. 5609 if (Diags.isLastDiagnosticIgnored()) 5610 return; 5611 5612 CXXFinalOverriderMap FinalOverriders; 5613 RD->getFinalOverriders(FinalOverriders); 5614 5615 // Keep a set of seen pure methods so we won't diagnose the same method 5616 // more than once. 5617 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 5618 5619 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 5620 MEnd = FinalOverriders.end(); 5621 M != MEnd; 5622 ++M) { 5623 for (OverridingMethods::iterator SO = M->second.begin(), 5624 SOEnd = M->second.end(); 5625 SO != SOEnd; ++SO) { 5626 // C++ [class.abstract]p4: 5627 // A class is abstract if it contains or inherits at least one 5628 // pure virtual function for which the final overrider is pure 5629 // virtual. 5630 5631 // 5632 if (SO->second.size() != 1) 5633 continue; 5634 5635 if (!SO->second.front().Method->isPure()) 5636 continue; 5637 5638 if (!SeenPureMethods.insert(SO->second.front().Method).second) 5639 continue; 5640 5641 Diag(SO->second.front().Method->getLocation(), 5642 diag::note_pure_virtual_function) 5643 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 5644 } 5645 } 5646 5647 if (!PureVirtualClassDiagSet) 5648 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 5649 PureVirtualClassDiagSet->insert(RD); 5650 } 5651 5652 namespace { 5653 struct AbstractUsageInfo { 5654 Sema &S; 5655 CXXRecordDecl *Record; 5656 CanQualType AbstractType; 5657 bool Invalid; 5658 5659 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 5660 : S(S), Record(Record), 5661 AbstractType(S.Context.getCanonicalType( 5662 S.Context.getTypeDeclType(Record))), 5663 Invalid(false) {} 5664 5665 void DiagnoseAbstractType() { 5666 if (Invalid) return; 5667 S.DiagnoseAbstractType(Record); 5668 Invalid = true; 5669 } 5670 5671 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 5672 }; 5673 5674 struct CheckAbstractUsage { 5675 AbstractUsageInfo &Info; 5676 const NamedDecl *Ctx; 5677 5678 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 5679 : Info(Info), Ctx(Ctx) {} 5680 5681 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5682 switch (TL.getTypeLocClass()) { 5683 #define ABSTRACT_TYPELOC(CLASS, PARENT) 5684 #define TYPELOC(CLASS, PARENT) \ 5685 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 5686 #include "clang/AST/TypeLocNodes.def" 5687 } 5688 } 5689 5690 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5691 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 5692 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 5693 if (!TL.getParam(I)) 5694 continue; 5695 5696 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 5697 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 5698 } 5699 } 5700 5701 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5702 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 5703 } 5704 5705 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5706 // Visit the type parameters from a permissive context. 5707 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 5708 TemplateArgumentLoc TAL = TL.getArgLoc(I); 5709 if (TAL.getArgument().getKind() == TemplateArgument::Type) 5710 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 5711 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 5712 // TODO: other template argument types? 5713 } 5714 } 5715 5716 // Visit pointee types from a permissive context. 5717 #define CheckPolymorphic(Type) \ 5718 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 5719 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 5720 } 5721 CheckPolymorphic(PointerTypeLoc) 5722 CheckPolymorphic(ReferenceTypeLoc) 5723 CheckPolymorphic(MemberPointerTypeLoc) 5724 CheckPolymorphic(BlockPointerTypeLoc) 5725 CheckPolymorphic(AtomicTypeLoc) 5726 5727 /// Handle all the types we haven't given a more specific 5728 /// implementation for above. 5729 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5730 // Every other kind of type that we haven't called out already 5731 // that has an inner type is either (1) sugar or (2) contains that 5732 // inner type in some way as a subobject. 5733 if (TypeLoc Next = TL.getNextTypeLoc()) 5734 return Visit(Next, Sel); 5735 5736 // If there's no inner type and we're in a permissive context, 5737 // don't diagnose. 5738 if (Sel == Sema::AbstractNone) return; 5739 5740 // Check whether the type matches the abstract type. 5741 QualType T = TL.getType(); 5742 if (T->isArrayType()) { 5743 Sel = Sema::AbstractArrayType; 5744 T = Info.S.Context.getBaseElementType(T); 5745 } 5746 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 5747 if (CT != Info.AbstractType) return; 5748 5749 // It matched; do some magic. 5750 if (Sel == Sema::AbstractArrayType) { 5751 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 5752 << T << TL.getSourceRange(); 5753 } else { 5754 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 5755 << Sel << T << TL.getSourceRange(); 5756 } 5757 Info.DiagnoseAbstractType(); 5758 } 5759 }; 5760 5761 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 5762 Sema::AbstractDiagSelID Sel) { 5763 CheckAbstractUsage(*this, D).Visit(TL, Sel); 5764 } 5765 5766 } 5767 5768 /// Check for invalid uses of an abstract type in a method declaration. 5769 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5770 CXXMethodDecl *MD) { 5771 // No need to do the check on definitions, which require that 5772 // the return/param types be complete. 5773 if (MD->doesThisDeclarationHaveABody()) 5774 return; 5775 5776 // For safety's sake, just ignore it if we don't have type source 5777 // information. This should never happen for non-implicit methods, 5778 // but... 5779 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 5780 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 5781 } 5782 5783 /// Check for invalid uses of an abstract type within a class definition. 5784 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5785 CXXRecordDecl *RD) { 5786 for (auto *D : RD->decls()) { 5787 if (D->isImplicit()) continue; 5788 5789 // Methods and method templates. 5790 if (isa<CXXMethodDecl>(D)) { 5791 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 5792 } else if (isa<FunctionTemplateDecl>(D)) { 5793 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 5794 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 5795 5796 // Fields and static variables. 5797 } else if (isa<FieldDecl>(D)) { 5798 FieldDecl *FD = cast<FieldDecl>(D); 5799 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 5800 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 5801 } else if (isa<VarDecl>(D)) { 5802 VarDecl *VD = cast<VarDecl>(D); 5803 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 5804 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 5805 5806 // Nested classes and class templates. 5807 } else if (isa<CXXRecordDecl>(D)) { 5808 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 5809 } else if (isa<ClassTemplateDecl>(D)) { 5810 CheckAbstractClassUsage(Info, 5811 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 5812 } 5813 } 5814 } 5815 5816 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) { 5817 Attr *ClassAttr = getDLLAttr(Class); 5818 if (!ClassAttr) 5819 return; 5820 5821 assert(ClassAttr->getKind() == attr::DLLExport); 5822 5823 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5824 5825 if (TSK == TSK_ExplicitInstantiationDeclaration) 5826 // Don't go any further if this is just an explicit instantiation 5827 // declaration. 5828 return; 5829 5830 // Add a context note to explain how we got to any diagnostics produced below. 5831 struct MarkingClassDllexported { 5832 Sema &S; 5833 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class, 5834 SourceLocation AttrLoc) 5835 : S(S) { 5836 Sema::CodeSynthesisContext Ctx; 5837 Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported; 5838 Ctx.PointOfInstantiation = AttrLoc; 5839 Ctx.Entity = Class; 5840 S.pushCodeSynthesisContext(Ctx); 5841 } 5842 ~MarkingClassDllexported() { 5843 S.popCodeSynthesisContext(); 5844 } 5845 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation()); 5846 5847 if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) 5848 S.MarkVTableUsed(Class->getLocation(), Class, true); 5849 5850 for (Decl *Member : Class->decls()) { 5851 // Defined static variables that are members of an exported base 5852 // class must be marked export too. 5853 auto *VD = dyn_cast<VarDecl>(Member); 5854 if (VD && Member->getAttr<DLLExportAttr>() && 5855 VD->getStorageClass() == SC_Static && 5856 TSK == TSK_ImplicitInstantiation) 5857 S.MarkVariableReferenced(VD->getLocation(), VD); 5858 5859 auto *MD = dyn_cast<CXXMethodDecl>(Member); 5860 if (!MD) 5861 continue; 5862 5863 if (Member->getAttr<DLLExportAttr>()) { 5864 if (MD->isUserProvided()) { 5865 // Instantiate non-default class member functions ... 5866 5867 // .. except for certain kinds of template specializations. 5868 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 5869 continue; 5870 5871 S.MarkFunctionReferenced(Class->getLocation(), MD); 5872 5873 // The function will be passed to the consumer when its definition is 5874 // encountered. 5875 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() || 5876 MD->isCopyAssignmentOperator() || 5877 MD->isMoveAssignmentOperator()) { 5878 // Synthesize and instantiate non-trivial implicit methods, explicitly 5879 // defaulted methods, and the copy and move assignment operators. The 5880 // latter are exported even if they are trivial, because the address of 5881 // an operator can be taken and should compare equal across libraries. 5882 S.MarkFunctionReferenced(Class->getLocation(), MD); 5883 5884 // There is no later point when we will see the definition of this 5885 // function, so pass it to the consumer now. 5886 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 5887 } 5888 } 5889 } 5890 } 5891 5892 static void checkForMultipleExportedDefaultConstructors(Sema &S, 5893 CXXRecordDecl *Class) { 5894 // Only the MS ABI has default constructor closures, so we don't need to do 5895 // this semantic checking anywhere else. 5896 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft()) 5897 return; 5898 5899 CXXConstructorDecl *LastExportedDefaultCtor = nullptr; 5900 for (Decl *Member : Class->decls()) { 5901 // Look for exported default constructors. 5902 auto *CD = dyn_cast<CXXConstructorDecl>(Member); 5903 if (!CD || !CD->isDefaultConstructor()) 5904 continue; 5905 auto *Attr = CD->getAttr<DLLExportAttr>(); 5906 if (!Attr) 5907 continue; 5908 5909 // If the class is non-dependent, mark the default arguments as ODR-used so 5910 // that we can properly codegen the constructor closure. 5911 if (!Class->isDependentContext()) { 5912 for (ParmVarDecl *PD : CD->parameters()) { 5913 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD); 5914 S.DiscardCleanupsInEvaluationContext(); 5915 } 5916 } 5917 5918 if (LastExportedDefaultCtor) { 5919 S.Diag(LastExportedDefaultCtor->getLocation(), 5920 diag::err_attribute_dll_ambiguous_default_ctor) 5921 << Class; 5922 S.Diag(CD->getLocation(), diag::note_entity_declared_at) 5923 << CD->getDeclName(); 5924 return; 5925 } 5926 LastExportedDefaultCtor = CD; 5927 } 5928 } 5929 5930 static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S, 5931 CXXRecordDecl *Class) { 5932 bool ErrorReported = false; 5933 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S, 5934 ClassTemplateDecl *TD) { 5935 if (ErrorReported) 5936 return; 5937 S.Diag(TD->getLocation(), 5938 diag::err_cuda_device_builtin_surftex_cls_template) 5939 << /*surface*/ 0 << TD; 5940 ErrorReported = true; 5941 }; 5942 5943 ClassTemplateDecl *TD = Class->getDescribedClassTemplate(); 5944 if (!TD) { 5945 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class); 5946 if (!SD) { 5947 S.Diag(Class->getLocation(), 5948 diag::err_cuda_device_builtin_surftex_ref_decl) 5949 << /*surface*/ 0 << Class; 5950 S.Diag(Class->getLocation(), 5951 diag::note_cuda_device_builtin_surftex_should_be_template_class) 5952 << Class; 5953 return; 5954 } 5955 TD = SD->getSpecializedTemplate(); 5956 } 5957 5958 TemplateParameterList *Params = TD->getTemplateParameters(); 5959 unsigned N = Params->size(); 5960 5961 if (N != 2) { 5962 reportIllegalClassTemplate(S, TD); 5963 S.Diag(TD->getLocation(), 5964 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args) 5965 << TD << 2; 5966 } 5967 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 5968 reportIllegalClassTemplate(S, TD); 5969 S.Diag(TD->getLocation(), 5970 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 5971 << TD << /*1st*/ 0 << /*type*/ 0; 5972 } 5973 if (N > 1) { 5974 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 5975 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 5976 reportIllegalClassTemplate(S, TD); 5977 S.Diag(TD->getLocation(), 5978 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 5979 << TD << /*2nd*/ 1 << /*integer*/ 1; 5980 } 5981 } 5982 } 5983 5984 static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S, 5985 CXXRecordDecl *Class) { 5986 bool ErrorReported = false; 5987 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S, 5988 ClassTemplateDecl *TD) { 5989 if (ErrorReported) 5990 return; 5991 S.Diag(TD->getLocation(), 5992 diag::err_cuda_device_builtin_surftex_cls_template) 5993 << /*texture*/ 1 << TD; 5994 ErrorReported = true; 5995 }; 5996 5997 ClassTemplateDecl *TD = Class->getDescribedClassTemplate(); 5998 if (!TD) { 5999 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class); 6000 if (!SD) { 6001 S.Diag(Class->getLocation(), 6002 diag::err_cuda_device_builtin_surftex_ref_decl) 6003 << /*texture*/ 1 << Class; 6004 S.Diag(Class->getLocation(), 6005 diag::note_cuda_device_builtin_surftex_should_be_template_class) 6006 << Class; 6007 return; 6008 } 6009 TD = SD->getSpecializedTemplate(); 6010 } 6011 6012 TemplateParameterList *Params = TD->getTemplateParameters(); 6013 unsigned N = Params->size(); 6014 6015 if (N != 3) { 6016 reportIllegalClassTemplate(S, TD); 6017 S.Diag(TD->getLocation(), 6018 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args) 6019 << TD << 3; 6020 } 6021 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 6022 reportIllegalClassTemplate(S, TD); 6023 S.Diag(TD->getLocation(), 6024 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6025 << TD << /*1st*/ 0 << /*type*/ 0; 6026 } 6027 if (N > 1) { 6028 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 6029 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 6030 reportIllegalClassTemplate(S, TD); 6031 S.Diag(TD->getLocation(), 6032 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6033 << TD << /*2nd*/ 1 << /*integer*/ 1; 6034 } 6035 } 6036 if (N > 2) { 6037 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2)); 6038 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 6039 reportIllegalClassTemplate(S, TD); 6040 S.Diag(TD->getLocation(), 6041 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6042 << TD << /*3rd*/ 2 << /*integer*/ 1; 6043 } 6044 } 6045 } 6046 6047 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) { 6048 // Mark any compiler-generated routines with the implicit code_seg attribute. 6049 for (auto *Method : Class->methods()) { 6050 if (Method->isUserProvided()) 6051 continue; 6052 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true)) 6053 Method->addAttr(A); 6054 } 6055 } 6056 6057 /// Check class-level dllimport/dllexport attribute. 6058 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) { 6059 Attr *ClassAttr = getDLLAttr(Class); 6060 6061 // MSVC inherits DLL attributes to partial class template specializations. 6062 if ((Context.getTargetInfo().getCXXABI().isMicrosoft() || 6063 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment()) && !ClassAttr) { 6064 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 6065 if (Attr *TemplateAttr = 6066 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 6067 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext())); 6068 A->setInherited(true); 6069 ClassAttr = A; 6070 } 6071 } 6072 } 6073 6074 if (!ClassAttr) 6075 return; 6076 6077 if (!Class->isExternallyVisible()) { 6078 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) 6079 << Class << ClassAttr; 6080 return; 6081 } 6082 6083 if ((Context.getTargetInfo().getCXXABI().isMicrosoft() || 6084 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment()) && 6085 !ClassAttr->isInherited()) { 6086 // Diagnose dll attributes on members of class with dll attribute. 6087 for (Decl *Member : Class->decls()) { 6088 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 6089 continue; 6090 InheritableAttr *MemberAttr = getDLLAttr(Member); 6091 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 6092 continue; 6093 6094 Diag(MemberAttr->getLocation(), 6095 diag::err_attribute_dll_member_of_dll_class) 6096 << MemberAttr << ClassAttr; 6097 Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 6098 Member->setInvalidDecl(); 6099 } 6100 } 6101 6102 if (Class->getDescribedClassTemplate()) 6103 // Don't inherit dll attribute until the template is instantiated. 6104 return; 6105 6106 // The class is either imported or exported. 6107 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 6108 6109 // Check if this was a dllimport attribute propagated from a derived class to 6110 // a base class template specialization. We don't apply these attributes to 6111 // static data members. 6112 const bool PropagatedImport = 6113 !ClassExported && 6114 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate(); 6115 6116 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 6117 6118 // Ignore explicit dllexport on explicit class template instantiation 6119 // declarations, except in MinGW mode. 6120 if (ClassExported && !ClassAttr->isInherited() && 6121 TSK == TSK_ExplicitInstantiationDeclaration && 6122 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) { 6123 Class->dropAttr<DLLExportAttr>(); 6124 return; 6125 } 6126 6127 // Force declaration of implicit members so they can inherit the attribute. 6128 ForceDeclarationOfImplicitMembers(Class); 6129 6130 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 6131 // seem to be true in practice? 6132 6133 for (Decl *Member : Class->decls()) { 6134 VarDecl *VD = dyn_cast<VarDecl>(Member); 6135 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 6136 6137 // Only methods and static fields inherit the attributes. 6138 if (!VD && !MD) 6139 continue; 6140 6141 if (MD) { 6142 // Don't process deleted methods. 6143 if (MD->isDeleted()) 6144 continue; 6145 6146 if (MD->isInlined()) { 6147 // MinGW does not import or export inline methods. But do it for 6148 // template instantiations. 6149 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() && 6150 !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment() && 6151 TSK != TSK_ExplicitInstantiationDeclaration && 6152 TSK != TSK_ExplicitInstantiationDefinition) 6153 continue; 6154 6155 // MSVC versions before 2015 don't export the move assignment operators 6156 // and move constructor, so don't attempt to import/export them if 6157 // we have a definition. 6158 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD); 6159 if ((MD->isMoveAssignmentOperator() || 6160 (Ctor && Ctor->isMoveConstructor())) && 6161 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015)) 6162 continue; 6163 6164 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign 6165 // operator is exported anyway. 6166 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 6167 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial()) 6168 continue; 6169 } 6170 } 6171 6172 // Don't apply dllimport attributes to static data members of class template 6173 // instantiations when the attribute is propagated from a derived class. 6174 if (VD && PropagatedImport) 6175 continue; 6176 6177 if (!cast<NamedDecl>(Member)->isExternallyVisible()) 6178 continue; 6179 6180 if (!getDLLAttr(Member)) { 6181 InheritableAttr *NewAttr = nullptr; 6182 6183 // Do not export/import inline function when -fno-dllexport-inlines is 6184 // passed. But add attribute for later local static var check. 6185 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() && 6186 TSK != TSK_ExplicitInstantiationDeclaration && 6187 TSK != TSK_ExplicitInstantiationDefinition) { 6188 if (ClassExported) { 6189 NewAttr = ::new (getASTContext()) 6190 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr); 6191 } else { 6192 NewAttr = ::new (getASTContext()) 6193 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr); 6194 } 6195 } else { 6196 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6197 } 6198 6199 NewAttr->setInherited(true); 6200 Member->addAttr(NewAttr); 6201 6202 if (MD) { 6203 // Propagate DLLAttr to friend re-declarations of MD that have already 6204 // been constructed. 6205 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD; 6206 FD = FD->getPreviousDecl()) { 6207 if (FD->getFriendObjectKind() == Decl::FOK_None) 6208 continue; 6209 assert(!getDLLAttr(FD) && 6210 "friend re-decl should not already have a DLLAttr"); 6211 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6212 NewAttr->setInherited(true); 6213 FD->addAttr(NewAttr); 6214 } 6215 } 6216 } 6217 } 6218 6219 if (ClassExported) 6220 DelayedDllExportClasses.push_back(Class); 6221 } 6222 6223 /// Perform propagation of DLL attributes from a derived class to a 6224 /// templated base class for MS compatibility. 6225 void Sema::propagateDLLAttrToBaseClassTemplate( 6226 CXXRecordDecl *Class, Attr *ClassAttr, 6227 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 6228 if (getDLLAttr( 6229 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 6230 // If the base class template has a DLL attribute, don't try to change it. 6231 return; 6232 } 6233 6234 auto TSK = BaseTemplateSpec->getSpecializationKind(); 6235 if (!getDLLAttr(BaseTemplateSpec) && 6236 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration || 6237 TSK == TSK_ImplicitInstantiation)) { 6238 // The template hasn't been instantiated yet (or it has, but only as an 6239 // explicit instantiation declaration or implicit instantiation, which means 6240 // we haven't codegenned any members yet), so propagate the attribute. 6241 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6242 NewAttr->setInherited(true); 6243 BaseTemplateSpec->addAttr(NewAttr); 6244 6245 // If this was an import, mark that we propagated it from a derived class to 6246 // a base class template specialization. 6247 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr)) 6248 ImportAttr->setPropagatedToBaseTemplate(); 6249 6250 // If the template is already instantiated, checkDLLAttributeRedeclaration() 6251 // needs to be run again to work see the new attribute. Otherwise this will 6252 // get run whenever the template is instantiated. 6253 if (TSK != TSK_Undeclared) 6254 checkClassLevelDLLAttribute(BaseTemplateSpec); 6255 6256 return; 6257 } 6258 6259 if (getDLLAttr(BaseTemplateSpec)) { 6260 // The template has already been specialized or instantiated with an 6261 // attribute, explicitly or through propagation. We should not try to change 6262 // it. 6263 return; 6264 } 6265 6266 // The template was previously instantiated or explicitly specialized without 6267 // a dll attribute, It's too late for us to add an attribute, so warn that 6268 // this is unsupported. 6269 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 6270 << BaseTemplateSpec->isExplicitSpecialization(); 6271 Diag(ClassAttr->getLocation(), diag::note_attribute); 6272 if (BaseTemplateSpec->isExplicitSpecialization()) { 6273 Diag(BaseTemplateSpec->getLocation(), 6274 diag::note_template_class_explicit_specialization_was_here) 6275 << BaseTemplateSpec; 6276 } else { 6277 Diag(BaseTemplateSpec->getPointOfInstantiation(), 6278 diag::note_template_class_instantiation_was_here) 6279 << BaseTemplateSpec; 6280 } 6281 } 6282 6283 /// Determine the kind of defaulting that would be done for a given function. 6284 /// 6285 /// If the function is both a default constructor and a copy / move constructor 6286 /// (due to having a default argument for the first parameter), this picks 6287 /// CXXDefaultConstructor. 6288 /// 6289 /// FIXME: Check that case is properly handled by all callers. 6290 Sema::DefaultedFunctionKind 6291 Sema::getDefaultedFunctionKind(const FunctionDecl *FD) { 6292 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 6293 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 6294 if (Ctor->isDefaultConstructor()) 6295 return Sema::CXXDefaultConstructor; 6296 6297 if (Ctor->isCopyConstructor()) 6298 return Sema::CXXCopyConstructor; 6299 6300 if (Ctor->isMoveConstructor()) 6301 return Sema::CXXMoveConstructor; 6302 } 6303 6304 if (MD->isCopyAssignmentOperator()) 6305 return Sema::CXXCopyAssignment; 6306 6307 if (MD->isMoveAssignmentOperator()) 6308 return Sema::CXXMoveAssignment; 6309 6310 if (isa<CXXDestructorDecl>(FD)) 6311 return Sema::CXXDestructor; 6312 } 6313 6314 switch (FD->getDeclName().getCXXOverloadedOperator()) { 6315 case OO_EqualEqual: 6316 return DefaultedComparisonKind::Equal; 6317 6318 case OO_ExclaimEqual: 6319 return DefaultedComparisonKind::NotEqual; 6320 6321 case OO_Spaceship: 6322 // No point allowing this if <=> doesn't exist in the current language mode. 6323 if (!getLangOpts().CPlusPlus20) 6324 break; 6325 return DefaultedComparisonKind::ThreeWay; 6326 6327 case OO_Less: 6328 case OO_LessEqual: 6329 case OO_Greater: 6330 case OO_GreaterEqual: 6331 // No point allowing this if <=> doesn't exist in the current language mode. 6332 if (!getLangOpts().CPlusPlus20) 6333 break; 6334 return DefaultedComparisonKind::Relational; 6335 6336 default: 6337 break; 6338 } 6339 6340 // Not defaultable. 6341 return DefaultedFunctionKind(); 6342 } 6343 6344 static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD, 6345 SourceLocation DefaultLoc) { 6346 Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD); 6347 if (DFK.isComparison()) 6348 return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison()); 6349 6350 switch (DFK.asSpecialMember()) { 6351 case Sema::CXXDefaultConstructor: 6352 S.DefineImplicitDefaultConstructor(DefaultLoc, 6353 cast<CXXConstructorDecl>(FD)); 6354 break; 6355 case Sema::CXXCopyConstructor: 6356 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD)); 6357 break; 6358 case Sema::CXXCopyAssignment: 6359 S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD)); 6360 break; 6361 case Sema::CXXDestructor: 6362 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD)); 6363 break; 6364 case Sema::CXXMoveConstructor: 6365 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD)); 6366 break; 6367 case Sema::CXXMoveAssignment: 6368 S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD)); 6369 break; 6370 case Sema::CXXInvalid: 6371 llvm_unreachable("Invalid special member."); 6372 } 6373 } 6374 6375 /// Determine whether a type is permitted to be passed or returned in 6376 /// registers, per C++ [class.temporary]p3. 6377 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D, 6378 TargetInfo::CallingConvKind CCK) { 6379 if (D->isDependentType() || D->isInvalidDecl()) 6380 return false; 6381 6382 // Clang <= 4 used the pre-C++11 rule, which ignores move operations. 6383 // The PS4 platform ABI follows the behavior of Clang 3.2. 6384 if (CCK == TargetInfo::CCK_ClangABI4OrPS4) 6385 return !D->hasNonTrivialDestructorForCall() && 6386 !D->hasNonTrivialCopyConstructorForCall(); 6387 6388 if (CCK == TargetInfo::CCK_MicrosoftWin64) { 6389 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false; 6390 bool DtorIsTrivialForCall = false; 6391 6392 // If a class has at least one non-deleted, trivial copy constructor, it 6393 // is passed according to the C ABI. Otherwise, it is passed indirectly. 6394 // 6395 // Note: This permits classes with non-trivial copy or move ctors to be 6396 // passed in registers, so long as they *also* have a trivial copy ctor, 6397 // which is non-conforming. 6398 if (D->needsImplicitCopyConstructor()) { 6399 if (!D->defaultedCopyConstructorIsDeleted()) { 6400 if (D->hasTrivialCopyConstructor()) 6401 CopyCtorIsTrivial = true; 6402 if (D->hasTrivialCopyConstructorForCall()) 6403 CopyCtorIsTrivialForCall = true; 6404 } 6405 } else { 6406 for (const CXXConstructorDecl *CD : D->ctors()) { 6407 if (CD->isCopyConstructor() && !CD->isDeleted()) { 6408 if (CD->isTrivial()) 6409 CopyCtorIsTrivial = true; 6410 if (CD->isTrivialForCall()) 6411 CopyCtorIsTrivialForCall = true; 6412 } 6413 } 6414 } 6415 6416 if (D->needsImplicitDestructor()) { 6417 if (!D->defaultedDestructorIsDeleted() && 6418 D->hasTrivialDestructorForCall()) 6419 DtorIsTrivialForCall = true; 6420 } else if (const auto *DD = D->getDestructor()) { 6421 if (!DD->isDeleted() && DD->isTrivialForCall()) 6422 DtorIsTrivialForCall = true; 6423 } 6424 6425 // If the copy ctor and dtor are both trivial-for-calls, pass direct. 6426 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall) 6427 return true; 6428 6429 // If a class has a destructor, we'd really like to pass it indirectly 6430 // because it allows us to elide copies. Unfortunately, MSVC makes that 6431 // impossible for small types, which it will pass in a single register or 6432 // stack slot. Most objects with dtors are large-ish, so handle that early. 6433 // We can't call out all large objects as being indirect because there are 6434 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate 6435 // how we pass large POD types. 6436 6437 // Note: This permits small classes with nontrivial destructors to be 6438 // passed in registers, which is non-conforming. 6439 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64(); 6440 uint64_t TypeSize = isAArch64 ? 128 : 64; 6441 6442 if (CopyCtorIsTrivial && 6443 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize) 6444 return true; 6445 return false; 6446 } 6447 6448 // Per C++ [class.temporary]p3, the relevant condition is: 6449 // each copy constructor, move constructor, and destructor of X is 6450 // either trivial or deleted, and X has at least one non-deleted copy 6451 // or move constructor 6452 bool HasNonDeletedCopyOrMove = false; 6453 6454 if (D->needsImplicitCopyConstructor() && 6455 !D->defaultedCopyConstructorIsDeleted()) { 6456 if (!D->hasTrivialCopyConstructorForCall()) 6457 return false; 6458 HasNonDeletedCopyOrMove = true; 6459 } 6460 6461 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() && 6462 !D->defaultedMoveConstructorIsDeleted()) { 6463 if (!D->hasTrivialMoveConstructorForCall()) 6464 return false; 6465 HasNonDeletedCopyOrMove = true; 6466 } 6467 6468 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() && 6469 !D->hasTrivialDestructorForCall()) 6470 return false; 6471 6472 for (const CXXMethodDecl *MD : D->methods()) { 6473 if (MD->isDeleted()) 6474 continue; 6475 6476 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 6477 if (CD && CD->isCopyOrMoveConstructor()) 6478 HasNonDeletedCopyOrMove = true; 6479 else if (!isa<CXXDestructorDecl>(MD)) 6480 continue; 6481 6482 if (!MD->isTrivialForCall()) 6483 return false; 6484 } 6485 6486 return HasNonDeletedCopyOrMove; 6487 } 6488 6489 /// Report an error regarding overriding, along with any relevant 6490 /// overridden methods. 6491 /// 6492 /// \param DiagID the primary error to report. 6493 /// \param MD the overriding method. 6494 static bool 6495 ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD, 6496 llvm::function_ref<bool(const CXXMethodDecl *)> Report) { 6497 bool IssuedDiagnostic = false; 6498 for (const CXXMethodDecl *O : MD->overridden_methods()) { 6499 if (Report(O)) { 6500 if (!IssuedDiagnostic) { 6501 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 6502 IssuedDiagnostic = true; 6503 } 6504 S.Diag(O->getLocation(), diag::note_overridden_virtual_function); 6505 } 6506 } 6507 return IssuedDiagnostic; 6508 } 6509 6510 /// Perform semantic checks on a class definition that has been 6511 /// completing, introducing implicitly-declared members, checking for 6512 /// abstract types, etc. 6513 /// 6514 /// \param S The scope in which the class was parsed. Null if we didn't just 6515 /// parse a class definition. 6516 /// \param Record The completed class. 6517 void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) { 6518 if (!Record) 6519 return; 6520 6521 if (Record->isAbstract() && !Record->isInvalidDecl()) { 6522 AbstractUsageInfo Info(*this, Record); 6523 CheckAbstractClassUsage(Info, Record); 6524 } 6525 6526 // If this is not an aggregate type and has no user-declared constructor, 6527 // complain about any non-static data members of reference or const scalar 6528 // type, since they will never get initializers. 6529 if (!Record->isInvalidDecl() && !Record->isDependentType() && 6530 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 6531 !Record->isLambda()) { 6532 bool Complained = false; 6533 for (const auto *F : Record->fields()) { 6534 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 6535 continue; 6536 6537 if (F->getType()->isReferenceType() || 6538 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 6539 if (!Complained) { 6540 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 6541 << Record->getTagKind() << Record; 6542 Complained = true; 6543 } 6544 6545 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 6546 << F->getType()->isReferenceType() 6547 << F->getDeclName(); 6548 } 6549 } 6550 } 6551 6552 if (Record->getIdentifier()) { 6553 // C++ [class.mem]p13: 6554 // If T is the name of a class, then each of the following shall have a 6555 // name different from T: 6556 // - every member of every anonymous union that is a member of class T. 6557 // 6558 // C++ [class.mem]p14: 6559 // In addition, if class T has a user-declared constructor (12.1), every 6560 // non-static data member of class T shall have a name different from T. 6561 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 6562 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 6563 ++I) { 6564 NamedDecl *D = (*I)->getUnderlyingDecl(); 6565 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) && 6566 Record->hasUserDeclaredConstructor()) || 6567 isa<IndirectFieldDecl>(D)) { 6568 Diag((*I)->getLocation(), diag::err_member_name_of_class) 6569 << D->getDeclName(); 6570 break; 6571 } 6572 } 6573 } 6574 6575 // Warn if the class has virtual methods but non-virtual public destructor. 6576 if (Record->isPolymorphic() && !Record->isDependentType()) { 6577 CXXDestructorDecl *dtor = Record->getDestructor(); 6578 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 6579 !Record->hasAttr<FinalAttr>()) 6580 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 6581 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 6582 } 6583 6584 if (Record->isAbstract()) { 6585 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 6586 Diag(Record->getLocation(), diag::warn_abstract_final_class) 6587 << FA->isSpelledAsSealed(); 6588 DiagnoseAbstractType(Record); 6589 } 6590 } 6591 6592 // Warn if the class has a final destructor but is not itself marked final. 6593 if (!Record->hasAttr<FinalAttr>()) { 6594 if (const CXXDestructorDecl *dtor = Record->getDestructor()) { 6595 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) { 6596 Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class) 6597 << FA->isSpelledAsSealed() 6598 << FixItHint::CreateInsertion( 6599 getLocForEndOfToken(Record->getLocation()), 6600 (FA->isSpelledAsSealed() ? " sealed" : " final")); 6601 Diag(Record->getLocation(), 6602 diag::note_final_dtor_non_final_class_silence) 6603 << Context.getRecordType(Record) << FA->isSpelledAsSealed(); 6604 } 6605 } 6606 } 6607 6608 // See if trivial_abi has to be dropped. 6609 if (Record->hasAttr<TrivialABIAttr>()) 6610 checkIllFormedTrivialABIStruct(*Record); 6611 6612 // Set HasTrivialSpecialMemberForCall if the record has attribute 6613 // "trivial_abi". 6614 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>(); 6615 6616 if (HasTrivialABI) 6617 Record->setHasTrivialSpecialMemberForCall(); 6618 6619 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=). 6620 // We check these last because they can depend on the properties of the 6621 // primary comparison functions (==, <=>). 6622 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons; 6623 6624 // Perform checks that can't be done until we know all the properties of a 6625 // member function (whether it's defaulted, deleted, virtual, overriding, 6626 // ...). 6627 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) { 6628 // A static function cannot override anything. 6629 if (MD->getStorageClass() == SC_Static) { 6630 if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD, 6631 [](const CXXMethodDecl *) { return true; })) 6632 return; 6633 } 6634 6635 // A deleted function cannot override a non-deleted function and vice 6636 // versa. 6637 if (ReportOverrides(*this, 6638 MD->isDeleted() ? diag::err_deleted_override 6639 : diag::err_non_deleted_override, 6640 MD, [&](const CXXMethodDecl *V) { 6641 return MD->isDeleted() != V->isDeleted(); 6642 })) { 6643 if (MD->isDefaulted() && MD->isDeleted()) 6644 // Explain why this defaulted function was deleted. 6645 DiagnoseDeletedDefaultedFunction(MD); 6646 return; 6647 } 6648 6649 // A consteval function cannot override a non-consteval function and vice 6650 // versa. 6651 if (ReportOverrides(*this, 6652 MD->isConsteval() ? diag::err_consteval_override 6653 : diag::err_non_consteval_override, 6654 MD, [&](const CXXMethodDecl *V) { 6655 return MD->isConsteval() != V->isConsteval(); 6656 })) { 6657 if (MD->isDefaulted() && MD->isDeleted()) 6658 // Explain why this defaulted function was deleted. 6659 DiagnoseDeletedDefaultedFunction(MD); 6660 return; 6661 } 6662 }; 6663 6664 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool { 6665 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted()) 6666 return false; 6667 6668 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD); 6669 if (DFK.asComparison() == DefaultedComparisonKind::NotEqual || 6670 DFK.asComparison() == DefaultedComparisonKind::Relational) { 6671 DefaultedSecondaryComparisons.push_back(FD); 6672 return true; 6673 } 6674 6675 CheckExplicitlyDefaultedFunction(S, FD); 6676 return false; 6677 }; 6678 6679 auto CompleteMemberFunction = [&](CXXMethodDecl *M) { 6680 // Check whether the explicitly-defaulted members are valid. 6681 bool Incomplete = CheckForDefaultedFunction(M); 6682 6683 // Skip the rest of the checks for a member of a dependent class. 6684 if (Record->isDependentType()) 6685 return; 6686 6687 // For an explicitly defaulted or deleted special member, we defer 6688 // determining triviality until the class is complete. That time is now! 6689 CXXSpecialMember CSM = getSpecialMember(M); 6690 if (!M->isImplicit() && !M->isUserProvided()) { 6691 if (CSM != CXXInvalid) { 6692 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 6693 // Inform the class that we've finished declaring this member. 6694 Record->finishedDefaultedOrDeletedMember(M); 6695 M->setTrivialForCall( 6696 HasTrivialABI || 6697 SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI)); 6698 Record->setTrivialForCallFlags(M); 6699 } 6700 } 6701 6702 // Set triviality for the purpose of calls if this is a user-provided 6703 // copy/move constructor or destructor. 6704 if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor || 6705 CSM == CXXDestructor) && M->isUserProvided()) { 6706 M->setTrivialForCall(HasTrivialABI); 6707 Record->setTrivialForCallFlags(M); 6708 } 6709 6710 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() && 6711 M->hasAttr<DLLExportAttr>()) { 6712 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 6713 M->isTrivial() && 6714 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor || 6715 CSM == CXXDestructor)) 6716 M->dropAttr<DLLExportAttr>(); 6717 6718 if (M->hasAttr<DLLExportAttr>()) { 6719 // Define after any fields with in-class initializers have been parsed. 6720 DelayedDllExportMemberFunctions.push_back(M); 6721 } 6722 } 6723 6724 // Define defaulted constexpr virtual functions that override a base class 6725 // function right away. 6726 // FIXME: We can defer doing this until the vtable is marked as used. 6727 if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods()) 6728 DefineDefaultedFunction(*this, M, M->getLocation()); 6729 6730 if (!Incomplete) 6731 CheckCompletedMemberFunction(M); 6732 }; 6733 6734 // Check the destructor before any other member function. We need to 6735 // determine whether it's trivial in order to determine whether the claas 6736 // type is a literal type, which is a prerequisite for determining whether 6737 // other special member functions are valid and whether they're implicitly 6738 // 'constexpr'. 6739 if (CXXDestructorDecl *Dtor = Record->getDestructor()) 6740 CompleteMemberFunction(Dtor); 6741 6742 bool HasMethodWithOverrideControl = false, 6743 HasOverridingMethodWithoutOverrideControl = false; 6744 for (auto *D : Record->decls()) { 6745 if (auto *M = dyn_cast<CXXMethodDecl>(D)) { 6746 // FIXME: We could do this check for dependent types with non-dependent 6747 // bases. 6748 if (!Record->isDependentType()) { 6749 // See if a method overloads virtual methods in a base 6750 // class without overriding any. 6751 if (!M->isStatic()) 6752 DiagnoseHiddenVirtualMethods(M); 6753 if (M->hasAttr<OverrideAttr>()) 6754 HasMethodWithOverrideControl = true; 6755 else if (M->size_overridden_methods() > 0) 6756 HasOverridingMethodWithoutOverrideControl = true; 6757 } 6758 6759 if (!isa<CXXDestructorDecl>(M)) 6760 CompleteMemberFunction(M); 6761 } else if (auto *F = dyn_cast<FriendDecl>(D)) { 6762 CheckForDefaultedFunction( 6763 dyn_cast_or_null<FunctionDecl>(F->getFriendDecl())); 6764 } 6765 } 6766 6767 if (HasOverridingMethodWithoutOverrideControl) { 6768 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl; 6769 for (auto *M : Record->methods()) 6770 DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl); 6771 } 6772 6773 // Check the defaulted secondary comparisons after any other member functions. 6774 for (FunctionDecl *FD : DefaultedSecondaryComparisons) { 6775 CheckExplicitlyDefaultedFunction(S, FD); 6776 6777 // If this is a member function, we deferred checking it until now. 6778 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) 6779 CheckCompletedMemberFunction(MD); 6780 } 6781 6782 // ms_struct is a request to use the same ABI rules as MSVC. Check 6783 // whether this class uses any C++ features that are implemented 6784 // completely differently in MSVC, and if so, emit a diagnostic. 6785 // That diagnostic defaults to an error, but we allow projects to 6786 // map it down to a warning (or ignore it). It's a fairly common 6787 // practice among users of the ms_struct pragma to mass-annotate 6788 // headers, sweeping up a bunch of types that the project doesn't 6789 // really rely on MSVC-compatible layout for. We must therefore 6790 // support "ms_struct except for C++ stuff" as a secondary ABI. 6791 // Don't emit this diagnostic if the feature was enabled as a 6792 // language option (as opposed to via a pragma or attribute), as 6793 // the option -mms-bitfields otherwise essentially makes it impossible 6794 // to build C++ code, unless this diagnostic is turned off. 6795 if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields && 6796 (Record->isPolymorphic() || Record->getNumBases())) { 6797 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 6798 } 6799 6800 checkClassLevelDLLAttribute(Record); 6801 checkClassLevelCodeSegAttribute(Record); 6802 6803 bool ClangABICompat4 = 6804 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4; 6805 TargetInfo::CallingConvKind CCK = 6806 Context.getTargetInfo().getCallingConvKind(ClangABICompat4); 6807 bool CanPass = canPassInRegisters(*this, Record, CCK); 6808 6809 // Do not change ArgPassingRestrictions if it has already been set to 6810 // APK_CanNeverPassInRegs. 6811 if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs) 6812 Record->setArgPassingRestrictions(CanPass 6813 ? RecordDecl::APK_CanPassInRegs 6814 : RecordDecl::APK_CannotPassInRegs); 6815 6816 // If canPassInRegisters returns true despite the record having a non-trivial 6817 // destructor, the record is destructed in the callee. This happens only when 6818 // the record or one of its subobjects has a field annotated with trivial_abi 6819 // or a field qualified with ObjC __strong/__weak. 6820 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee()) 6821 Record->setParamDestroyedInCallee(true); 6822 else if (Record->hasNonTrivialDestructor()) 6823 Record->setParamDestroyedInCallee(CanPass); 6824 6825 if (getLangOpts().ForceEmitVTables) { 6826 // If we want to emit all the vtables, we need to mark it as used. This 6827 // is especially required for cases like vtable assumption loads. 6828 MarkVTableUsed(Record->getInnerLocStart(), Record); 6829 } 6830 6831 if (getLangOpts().CUDA) { 6832 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>()) 6833 checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record); 6834 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>()) 6835 checkCUDADeviceBuiltinTextureClassTemplate(*this, Record); 6836 } 6837 } 6838 6839 /// Look up the special member function that would be called by a special 6840 /// member function for a subobject of class type. 6841 /// 6842 /// \param Class The class type of the subobject. 6843 /// \param CSM The kind of special member function. 6844 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 6845 /// \param ConstRHS True if this is a copy operation with a const object 6846 /// on its RHS, that is, if the argument to the outer special member 6847 /// function is 'const' and this is not a field marked 'mutable'. 6848 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember( 6849 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 6850 unsigned FieldQuals, bool ConstRHS) { 6851 unsigned LHSQuals = 0; 6852 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 6853 LHSQuals = FieldQuals; 6854 6855 unsigned RHSQuals = FieldQuals; 6856 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 6857 RHSQuals = 0; 6858 else if (ConstRHS) 6859 RHSQuals |= Qualifiers::Const; 6860 6861 return S.LookupSpecialMember(Class, CSM, 6862 RHSQuals & Qualifiers::Const, 6863 RHSQuals & Qualifiers::Volatile, 6864 false, 6865 LHSQuals & Qualifiers::Const, 6866 LHSQuals & Qualifiers::Volatile); 6867 } 6868 6869 class Sema::InheritedConstructorInfo { 6870 Sema &S; 6871 SourceLocation UseLoc; 6872 6873 /// A mapping from the base classes through which the constructor was 6874 /// inherited to the using shadow declaration in that base class (or a null 6875 /// pointer if the constructor was declared in that base class). 6876 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *> 6877 InheritedFromBases; 6878 6879 public: 6880 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, 6881 ConstructorUsingShadowDecl *Shadow) 6882 : S(S), UseLoc(UseLoc) { 6883 bool DiagnosedMultipleConstructedBases = false; 6884 CXXRecordDecl *ConstructedBase = nullptr; 6885 UsingDecl *ConstructedBaseUsing = nullptr; 6886 6887 // Find the set of such base class subobjects and check that there's a 6888 // unique constructed subobject. 6889 for (auto *D : Shadow->redecls()) { 6890 auto *DShadow = cast<ConstructorUsingShadowDecl>(D); 6891 auto *DNominatedBase = DShadow->getNominatedBaseClass(); 6892 auto *DConstructedBase = DShadow->getConstructedBaseClass(); 6893 6894 InheritedFromBases.insert( 6895 std::make_pair(DNominatedBase->getCanonicalDecl(), 6896 DShadow->getNominatedBaseClassShadowDecl())); 6897 if (DShadow->constructsVirtualBase()) 6898 InheritedFromBases.insert( 6899 std::make_pair(DConstructedBase->getCanonicalDecl(), 6900 DShadow->getConstructedBaseClassShadowDecl())); 6901 else 6902 assert(DNominatedBase == DConstructedBase); 6903 6904 // [class.inhctor.init]p2: 6905 // If the constructor was inherited from multiple base class subobjects 6906 // of type B, the program is ill-formed. 6907 if (!ConstructedBase) { 6908 ConstructedBase = DConstructedBase; 6909 ConstructedBaseUsing = D->getUsingDecl(); 6910 } else if (ConstructedBase != DConstructedBase && 6911 !Shadow->isInvalidDecl()) { 6912 if (!DiagnosedMultipleConstructedBases) { 6913 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor) 6914 << Shadow->getTargetDecl(); 6915 S.Diag(ConstructedBaseUsing->getLocation(), 6916 diag::note_ambiguous_inherited_constructor_using) 6917 << ConstructedBase; 6918 DiagnosedMultipleConstructedBases = true; 6919 } 6920 S.Diag(D->getUsingDecl()->getLocation(), 6921 diag::note_ambiguous_inherited_constructor_using) 6922 << DConstructedBase; 6923 } 6924 } 6925 6926 if (DiagnosedMultipleConstructedBases) 6927 Shadow->setInvalidDecl(); 6928 } 6929 6930 /// Find the constructor to use for inherited construction of a base class, 6931 /// and whether that base class constructor inherits the constructor from a 6932 /// virtual base class (in which case it won't actually invoke it). 6933 std::pair<CXXConstructorDecl *, bool> 6934 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const { 6935 auto It = InheritedFromBases.find(Base->getCanonicalDecl()); 6936 if (It == InheritedFromBases.end()) 6937 return std::make_pair(nullptr, false); 6938 6939 // This is an intermediary class. 6940 if (It->second) 6941 return std::make_pair( 6942 S.findInheritingConstructor(UseLoc, Ctor, It->second), 6943 It->second->constructsVirtualBase()); 6944 6945 // This is the base class from which the constructor was inherited. 6946 return std::make_pair(Ctor, false); 6947 } 6948 }; 6949 6950 /// Is the special member function which would be selected to perform the 6951 /// specified operation on the specified class type a constexpr constructor? 6952 static bool 6953 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 6954 Sema::CXXSpecialMember CSM, unsigned Quals, 6955 bool ConstRHS, 6956 CXXConstructorDecl *InheritedCtor = nullptr, 6957 Sema::InheritedConstructorInfo *Inherited = nullptr) { 6958 // If we're inheriting a constructor, see if we need to call it for this base 6959 // class. 6960 if (InheritedCtor) { 6961 assert(CSM == Sema::CXXDefaultConstructor); 6962 auto BaseCtor = 6963 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first; 6964 if (BaseCtor) 6965 return BaseCtor->isConstexpr(); 6966 } 6967 6968 if (CSM == Sema::CXXDefaultConstructor) 6969 return ClassDecl->hasConstexprDefaultConstructor(); 6970 if (CSM == Sema::CXXDestructor) 6971 return ClassDecl->hasConstexprDestructor(); 6972 6973 Sema::SpecialMemberOverloadResult SMOR = 6974 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 6975 if (!SMOR.getMethod()) 6976 // A constructor we wouldn't select can't be "involved in initializing" 6977 // anything. 6978 return true; 6979 return SMOR.getMethod()->isConstexpr(); 6980 } 6981 6982 /// Determine whether the specified special member function would be constexpr 6983 /// if it were implicitly defined. 6984 static bool defaultedSpecialMemberIsConstexpr( 6985 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, 6986 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr, 6987 Sema::InheritedConstructorInfo *Inherited = nullptr) { 6988 if (!S.getLangOpts().CPlusPlus11) 6989 return false; 6990 6991 // C++11 [dcl.constexpr]p4: 6992 // In the definition of a constexpr constructor [...] 6993 bool Ctor = true; 6994 switch (CSM) { 6995 case Sema::CXXDefaultConstructor: 6996 if (Inherited) 6997 break; 6998 // Since default constructor lookup is essentially trivial (and cannot 6999 // involve, for instance, template instantiation), we compute whether a 7000 // defaulted default constructor is constexpr directly within CXXRecordDecl. 7001 // 7002 // This is important for performance; we need to know whether the default 7003 // constructor is constexpr to determine whether the type is a literal type. 7004 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 7005 7006 case Sema::CXXCopyConstructor: 7007 case Sema::CXXMoveConstructor: 7008 // For copy or move constructors, we need to perform overload resolution. 7009 break; 7010 7011 case Sema::CXXCopyAssignment: 7012 case Sema::CXXMoveAssignment: 7013 if (!S.getLangOpts().CPlusPlus14) 7014 return false; 7015 // In C++1y, we need to perform overload resolution. 7016 Ctor = false; 7017 break; 7018 7019 case Sema::CXXDestructor: 7020 return ClassDecl->defaultedDestructorIsConstexpr(); 7021 7022 case Sema::CXXInvalid: 7023 return false; 7024 } 7025 7026 // -- if the class is a non-empty union, or for each non-empty anonymous 7027 // union member of a non-union class, exactly one non-static data member 7028 // shall be initialized; [DR1359] 7029 // 7030 // If we squint, this is guaranteed, since exactly one non-static data member 7031 // will be initialized (if the constructor isn't deleted), we just don't know 7032 // which one. 7033 if (Ctor && ClassDecl->isUnion()) 7034 return CSM == Sema::CXXDefaultConstructor 7035 ? ClassDecl->hasInClassInitializer() || 7036 !ClassDecl->hasVariantMembers() 7037 : true; 7038 7039 // -- the class shall not have any virtual base classes; 7040 if (Ctor && ClassDecl->getNumVBases()) 7041 return false; 7042 7043 // C++1y [class.copy]p26: 7044 // -- [the class] is a literal type, and 7045 if (!Ctor && !ClassDecl->isLiteral()) 7046 return false; 7047 7048 // -- every constructor involved in initializing [...] base class 7049 // sub-objects shall be a constexpr constructor; 7050 // -- the assignment operator selected to copy/move each direct base 7051 // class is a constexpr function, and 7052 for (const auto &B : ClassDecl->bases()) { 7053 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 7054 if (!BaseType) continue; 7055 7056 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7057 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg, 7058 InheritedCtor, Inherited)) 7059 return false; 7060 } 7061 7062 // -- every constructor involved in initializing non-static data members 7063 // [...] shall be a constexpr constructor; 7064 // -- every non-static data member and base class sub-object shall be 7065 // initialized 7066 // -- for each non-static data member of X that is of class type (or array 7067 // thereof), the assignment operator selected to copy/move that member is 7068 // a constexpr function 7069 for (const auto *F : ClassDecl->fields()) { 7070 if (F->isInvalidDecl()) 7071 continue; 7072 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer()) 7073 continue; 7074 QualType BaseType = S.Context.getBaseElementType(F->getType()); 7075 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 7076 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 7077 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 7078 BaseType.getCVRQualifiers(), 7079 ConstArg && !F->isMutable())) 7080 return false; 7081 } else if (CSM == Sema::CXXDefaultConstructor) { 7082 return false; 7083 } 7084 } 7085 7086 // All OK, it's constexpr! 7087 return true; 7088 } 7089 7090 namespace { 7091 /// RAII object to register a defaulted function as having its exception 7092 /// specification computed. 7093 struct ComputingExceptionSpec { 7094 Sema &S; 7095 7096 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc) 7097 : S(S) { 7098 Sema::CodeSynthesisContext Ctx; 7099 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation; 7100 Ctx.PointOfInstantiation = Loc; 7101 Ctx.Entity = FD; 7102 S.pushCodeSynthesisContext(Ctx); 7103 } 7104 ~ComputingExceptionSpec() { 7105 S.popCodeSynthesisContext(); 7106 } 7107 }; 7108 } 7109 7110 static Sema::ImplicitExceptionSpecification 7111 ComputeDefaultedSpecialMemberExceptionSpec( 7112 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 7113 Sema::InheritedConstructorInfo *ICI); 7114 7115 static Sema::ImplicitExceptionSpecification 7116 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, 7117 FunctionDecl *FD, 7118 Sema::DefaultedComparisonKind DCK); 7119 7120 static Sema::ImplicitExceptionSpecification 7121 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) { 7122 auto DFK = S.getDefaultedFunctionKind(FD); 7123 if (DFK.isSpecialMember()) 7124 return ComputeDefaultedSpecialMemberExceptionSpec( 7125 S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr); 7126 if (DFK.isComparison()) 7127 return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD, 7128 DFK.asComparison()); 7129 7130 auto *CD = cast<CXXConstructorDecl>(FD); 7131 assert(CD->getInheritedConstructor() && 7132 "only defaulted functions and inherited constructors have implicit " 7133 "exception specs"); 7134 Sema::InheritedConstructorInfo ICI( 7135 S, Loc, CD->getInheritedConstructor().getShadowDecl()); 7136 return ComputeDefaultedSpecialMemberExceptionSpec( 7137 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI); 7138 } 7139 7140 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 7141 CXXMethodDecl *MD) { 7142 FunctionProtoType::ExtProtoInfo EPI; 7143 7144 // Build an exception specification pointing back at this member. 7145 EPI.ExceptionSpec.Type = EST_Unevaluated; 7146 EPI.ExceptionSpec.SourceDecl = MD; 7147 7148 // Set the calling convention to the default for C++ instance methods. 7149 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 7150 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 7151 /*IsCXXMethod=*/true)); 7152 return EPI; 7153 } 7154 7155 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) { 7156 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>(); 7157 if (FPT->getExceptionSpecType() != EST_Unevaluated) 7158 return; 7159 7160 // Evaluate the exception specification. 7161 auto IES = computeImplicitExceptionSpec(*this, Loc, FD); 7162 auto ESI = IES.getExceptionSpec(); 7163 7164 // Update the type of the special member to use it. 7165 UpdateExceptionSpec(FD, ESI); 7166 } 7167 7168 void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) { 7169 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted"); 7170 7171 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD); 7172 if (!DefKind) { 7173 assert(FD->getDeclContext()->isDependentContext()); 7174 return; 7175 } 7176 7177 if (DefKind.isSpecialMember() 7178 ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD), 7179 DefKind.asSpecialMember()) 7180 : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison())) 7181 FD->setInvalidDecl(); 7182 } 7183 7184 bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD, 7185 CXXSpecialMember CSM) { 7186 CXXRecordDecl *RD = MD->getParent(); 7187 7188 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 7189 "not an explicitly-defaulted special member"); 7190 7191 // Defer all checking for special members of a dependent type. 7192 if (RD->isDependentType()) 7193 return false; 7194 7195 // Whether this was the first-declared instance of the constructor. 7196 // This affects whether we implicitly add an exception spec and constexpr. 7197 bool First = MD == MD->getCanonicalDecl(); 7198 7199 bool HadError = false; 7200 7201 // C++11 [dcl.fct.def.default]p1: 7202 // A function that is explicitly defaulted shall 7203 // -- be a special member function [...] (checked elsewhere), 7204 // -- have the same type (except for ref-qualifiers, and except that a 7205 // copy operation can take a non-const reference) as an implicit 7206 // declaration, and 7207 // -- not have default arguments. 7208 // C++2a changes the second bullet to instead delete the function if it's 7209 // defaulted on its first declaration, unless it's "an assignment operator, 7210 // and its return type differs or its parameter type is not a reference". 7211 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First; 7212 bool ShouldDeleteForTypeMismatch = false; 7213 unsigned ExpectedParams = 1; 7214 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 7215 ExpectedParams = 0; 7216 if (MD->getNumParams() != ExpectedParams) { 7217 // This checks for default arguments: a copy or move constructor with a 7218 // default argument is classified as a default constructor, and assignment 7219 // operations and destructors can't have default arguments. 7220 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 7221 << CSM << MD->getSourceRange(); 7222 HadError = true; 7223 } else if (MD->isVariadic()) { 7224 if (DeleteOnTypeMismatch) 7225 ShouldDeleteForTypeMismatch = true; 7226 else { 7227 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 7228 << CSM << MD->getSourceRange(); 7229 HadError = true; 7230 } 7231 } 7232 7233 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 7234 7235 bool CanHaveConstParam = false; 7236 if (CSM == CXXCopyConstructor) 7237 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 7238 else if (CSM == CXXCopyAssignment) 7239 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 7240 7241 QualType ReturnType = Context.VoidTy; 7242 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 7243 // Check for return type matching. 7244 ReturnType = Type->getReturnType(); 7245 7246 QualType DeclType = Context.getTypeDeclType(RD); 7247 DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace()); 7248 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType); 7249 7250 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 7251 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 7252 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 7253 HadError = true; 7254 } 7255 7256 // A defaulted special member cannot have cv-qualifiers. 7257 if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) { 7258 if (DeleteOnTypeMismatch) 7259 ShouldDeleteForTypeMismatch = true; 7260 else { 7261 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 7262 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 7263 HadError = true; 7264 } 7265 } 7266 } 7267 7268 // Check for parameter type matching. 7269 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 7270 bool HasConstParam = false; 7271 if (ExpectedParams && ArgType->isReferenceType()) { 7272 // Argument must be reference to possibly-const T. 7273 QualType ReferentType = ArgType->getPointeeType(); 7274 HasConstParam = ReferentType.isConstQualified(); 7275 7276 if (ReferentType.isVolatileQualified()) { 7277 if (DeleteOnTypeMismatch) 7278 ShouldDeleteForTypeMismatch = true; 7279 else { 7280 Diag(MD->getLocation(), 7281 diag::err_defaulted_special_member_volatile_param) << CSM; 7282 HadError = true; 7283 } 7284 } 7285 7286 if (HasConstParam && !CanHaveConstParam) { 7287 if (DeleteOnTypeMismatch) 7288 ShouldDeleteForTypeMismatch = true; 7289 else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 7290 Diag(MD->getLocation(), 7291 diag::err_defaulted_special_member_copy_const_param) 7292 << (CSM == CXXCopyAssignment); 7293 // FIXME: Explain why this special member can't be const. 7294 HadError = true; 7295 } else { 7296 Diag(MD->getLocation(), 7297 diag::err_defaulted_special_member_move_const_param) 7298 << (CSM == CXXMoveAssignment); 7299 HadError = true; 7300 } 7301 } 7302 } else if (ExpectedParams) { 7303 // A copy assignment operator can take its argument by value, but a 7304 // defaulted one cannot. 7305 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 7306 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 7307 HadError = true; 7308 } 7309 7310 // C++11 [dcl.fct.def.default]p2: 7311 // An explicitly-defaulted function may be declared constexpr only if it 7312 // would have been implicitly declared as constexpr, 7313 // Do not apply this rule to members of class templates, since core issue 1358 7314 // makes such functions always instantiate to constexpr functions. For 7315 // functions which cannot be constexpr (for non-constructors in C++11 and for 7316 // destructors in C++14 and C++17), this is checked elsewhere. 7317 // 7318 // FIXME: This should not apply if the member is deleted. 7319 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 7320 HasConstParam); 7321 if ((getLangOpts().CPlusPlus20 || 7322 (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 7323 : isa<CXXConstructorDecl>(MD))) && 7324 MD->isConstexpr() && !Constexpr && 7325 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 7326 Diag(MD->getBeginLoc(), MD->isConsteval() 7327 ? diag::err_incorrect_defaulted_consteval 7328 : diag::err_incorrect_defaulted_constexpr) 7329 << CSM; 7330 // FIXME: Explain why the special member can't be constexpr. 7331 HadError = true; 7332 } 7333 7334 if (First) { 7335 // C++2a [dcl.fct.def.default]p3: 7336 // If a function is explicitly defaulted on its first declaration, it is 7337 // implicitly considered to be constexpr if the implicit declaration 7338 // would be. 7339 MD->setConstexprKind( 7340 Constexpr ? (MD->isConsteval() ? CSK_consteval : CSK_constexpr) 7341 : CSK_unspecified); 7342 7343 if (!Type->hasExceptionSpec()) { 7344 // C++2a [except.spec]p3: 7345 // If a declaration of a function does not have a noexcept-specifier 7346 // [and] is defaulted on its first declaration, [...] the exception 7347 // specification is as specified below 7348 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 7349 EPI.ExceptionSpec.Type = EST_Unevaluated; 7350 EPI.ExceptionSpec.SourceDecl = MD; 7351 MD->setType(Context.getFunctionType(ReturnType, 7352 llvm::makeArrayRef(&ArgType, 7353 ExpectedParams), 7354 EPI)); 7355 } 7356 } 7357 7358 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) { 7359 if (First) { 7360 SetDeclDeleted(MD, MD->getLocation()); 7361 if (!inTemplateInstantiation() && !HadError) { 7362 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM; 7363 if (ShouldDeleteForTypeMismatch) { 7364 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM; 7365 } else { 7366 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 7367 } 7368 } 7369 if (ShouldDeleteForTypeMismatch && !HadError) { 7370 Diag(MD->getLocation(), 7371 diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM; 7372 } 7373 } else { 7374 // C++11 [dcl.fct.def.default]p4: 7375 // [For a] user-provided explicitly-defaulted function [...] if such a 7376 // function is implicitly defined as deleted, the program is ill-formed. 7377 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 7378 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl"); 7379 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 7380 HadError = true; 7381 } 7382 } 7383 7384 return HadError; 7385 } 7386 7387 namespace { 7388 /// Helper class for building and checking a defaulted comparison. 7389 /// 7390 /// Defaulted functions are built in two phases: 7391 /// 7392 /// * First, the set of operations that the function will perform are 7393 /// identified, and some of them are checked. If any of the checked 7394 /// operations is invalid in certain ways, the comparison function is 7395 /// defined as deleted and no body is built. 7396 /// * Then, if the function is not defined as deleted, the body is built. 7397 /// 7398 /// This is accomplished by performing two visitation steps over the eventual 7399 /// body of the function. 7400 template<typename Derived, typename ResultList, typename Result, 7401 typename Subobject> 7402 class DefaultedComparisonVisitor { 7403 public: 7404 using DefaultedComparisonKind = Sema::DefaultedComparisonKind; 7405 7406 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7407 DefaultedComparisonKind DCK) 7408 : S(S), RD(RD), FD(FD), DCK(DCK) { 7409 if (auto *Info = FD->getDefaultedFunctionInfo()) { 7410 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an 7411 // UnresolvedSet to avoid this copy. 7412 Fns.assign(Info->getUnqualifiedLookups().begin(), 7413 Info->getUnqualifiedLookups().end()); 7414 } 7415 } 7416 7417 ResultList visit() { 7418 // The type of an lvalue naming a parameter of this function. 7419 QualType ParamLvalType = 7420 FD->getParamDecl(0)->getType().getNonReferenceType(); 7421 7422 ResultList Results; 7423 7424 switch (DCK) { 7425 case DefaultedComparisonKind::None: 7426 llvm_unreachable("not a defaulted comparison"); 7427 7428 case DefaultedComparisonKind::Equal: 7429 case DefaultedComparisonKind::ThreeWay: 7430 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers()); 7431 return Results; 7432 7433 case DefaultedComparisonKind::NotEqual: 7434 case DefaultedComparisonKind::Relational: 7435 Results.add(getDerived().visitExpandedSubobject( 7436 ParamLvalType, getDerived().getCompleteObject())); 7437 return Results; 7438 } 7439 llvm_unreachable(""); 7440 } 7441 7442 protected: 7443 Derived &getDerived() { return static_cast<Derived&>(*this); } 7444 7445 /// Visit the expanded list of subobjects of the given type, as specified in 7446 /// C++2a [class.compare.default]. 7447 /// 7448 /// \return \c true if the ResultList object said we're done, \c false if not. 7449 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record, 7450 Qualifiers Quals) { 7451 // C++2a [class.compare.default]p4: 7452 // The direct base class subobjects of C 7453 for (CXXBaseSpecifier &Base : Record->bases()) 7454 if (Results.add(getDerived().visitSubobject( 7455 S.Context.getQualifiedType(Base.getType(), Quals), 7456 getDerived().getBase(&Base)))) 7457 return true; 7458 7459 // followed by the non-static data members of C 7460 for (FieldDecl *Field : Record->fields()) { 7461 // Recursively expand anonymous structs. 7462 if (Field->isAnonymousStructOrUnion()) { 7463 if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(), 7464 Quals)) 7465 return true; 7466 continue; 7467 } 7468 7469 // Figure out the type of an lvalue denoting this field. 7470 Qualifiers FieldQuals = Quals; 7471 if (Field->isMutable()) 7472 FieldQuals.removeConst(); 7473 QualType FieldType = 7474 S.Context.getQualifiedType(Field->getType(), FieldQuals); 7475 7476 if (Results.add(getDerived().visitSubobject( 7477 FieldType, getDerived().getField(Field)))) 7478 return true; 7479 } 7480 7481 // form a list of subobjects. 7482 return false; 7483 } 7484 7485 Result visitSubobject(QualType Type, Subobject Subobj) { 7486 // In that list, any subobject of array type is recursively expanded 7487 const ArrayType *AT = S.Context.getAsArrayType(Type); 7488 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT)) 7489 return getDerived().visitSubobjectArray(CAT->getElementType(), 7490 CAT->getSize(), Subobj); 7491 return getDerived().visitExpandedSubobject(Type, Subobj); 7492 } 7493 7494 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size, 7495 Subobject Subobj) { 7496 return getDerived().visitSubobject(Type, Subobj); 7497 } 7498 7499 protected: 7500 Sema &S; 7501 CXXRecordDecl *RD; 7502 FunctionDecl *FD; 7503 DefaultedComparisonKind DCK; 7504 UnresolvedSet<16> Fns; 7505 }; 7506 7507 /// Information about a defaulted comparison, as determined by 7508 /// DefaultedComparisonAnalyzer. 7509 struct DefaultedComparisonInfo { 7510 bool Deleted = false; 7511 bool Constexpr = true; 7512 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering; 7513 7514 static DefaultedComparisonInfo deleted() { 7515 DefaultedComparisonInfo Deleted; 7516 Deleted.Deleted = true; 7517 return Deleted; 7518 } 7519 7520 bool add(const DefaultedComparisonInfo &R) { 7521 Deleted |= R.Deleted; 7522 Constexpr &= R.Constexpr; 7523 Category = commonComparisonType(Category, R.Category); 7524 return Deleted; 7525 } 7526 }; 7527 7528 /// An element in the expanded list of subobjects of a defaulted comparison, as 7529 /// specified in C++2a [class.compare.default]p4. 7530 struct DefaultedComparisonSubobject { 7531 enum { CompleteObject, Member, Base } Kind; 7532 NamedDecl *Decl; 7533 SourceLocation Loc; 7534 }; 7535 7536 /// A visitor over the notional body of a defaulted comparison that determines 7537 /// whether that body would be deleted or constexpr. 7538 class DefaultedComparisonAnalyzer 7539 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer, 7540 DefaultedComparisonInfo, 7541 DefaultedComparisonInfo, 7542 DefaultedComparisonSubobject> { 7543 public: 7544 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr }; 7545 7546 private: 7547 DiagnosticKind Diagnose; 7548 7549 public: 7550 using Base = DefaultedComparisonVisitor; 7551 using Result = DefaultedComparisonInfo; 7552 using Subobject = DefaultedComparisonSubobject; 7553 7554 friend Base; 7555 7556 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7557 DefaultedComparisonKind DCK, 7558 DiagnosticKind Diagnose = NoDiagnostics) 7559 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {} 7560 7561 Result visit() { 7562 if ((DCK == DefaultedComparisonKind::Equal || 7563 DCK == DefaultedComparisonKind::ThreeWay) && 7564 RD->hasVariantMembers()) { 7565 // C++2a [class.compare.default]p2 [P2002R0]: 7566 // A defaulted comparison operator function for class C is defined as 7567 // deleted if [...] C has variant members. 7568 if (Diagnose == ExplainDeleted) { 7569 S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union) 7570 << FD << RD->isUnion() << RD; 7571 } 7572 return Result::deleted(); 7573 } 7574 7575 return Base::visit(); 7576 } 7577 7578 private: 7579 Subobject getCompleteObject() { 7580 return Subobject{Subobject::CompleteObject, nullptr, FD->getLocation()}; 7581 } 7582 7583 Subobject getBase(CXXBaseSpecifier *Base) { 7584 return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(), 7585 Base->getBaseTypeLoc()}; 7586 } 7587 7588 Subobject getField(FieldDecl *Field) { 7589 return Subobject{Subobject::Member, Field, Field->getLocation()}; 7590 } 7591 7592 Result visitExpandedSubobject(QualType Type, Subobject Subobj) { 7593 // C++2a [class.compare.default]p2 [P2002R0]: 7594 // A defaulted <=> or == operator function for class C is defined as 7595 // deleted if any non-static data member of C is of reference type 7596 if (Type->isReferenceType()) { 7597 if (Diagnose == ExplainDeleted) { 7598 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member) 7599 << FD << RD; 7600 } 7601 return Result::deleted(); 7602 } 7603 7604 // [...] Let xi be an lvalue denoting the ith element [...] 7605 OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue); 7606 Expr *Args[] = {&Xi, &Xi}; 7607 7608 // All operators start by trying to apply that same operator recursively. 7609 OverloadedOperatorKind OO = FD->getOverloadedOperator(); 7610 assert(OO != OO_None && "not an overloaded operator!"); 7611 return visitBinaryOperator(OO, Args, Subobj); 7612 } 7613 7614 Result 7615 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args, 7616 Subobject Subobj, 7617 OverloadCandidateSet *SpaceshipCandidates = nullptr) { 7618 // Note that there is no need to consider rewritten candidates here if 7619 // we've already found there is no viable 'operator<=>' candidate (and are 7620 // considering synthesizing a '<=>' from '==' and '<'). 7621 OverloadCandidateSet CandidateSet( 7622 FD->getLocation(), OverloadCandidateSet::CSK_Operator, 7623 OverloadCandidateSet::OperatorRewriteInfo( 7624 OO, /*AllowRewrittenCandidates=*/!SpaceshipCandidates)); 7625 7626 /// C++2a [class.compare.default]p1 [P2002R0]: 7627 /// [...] the defaulted function itself is never a candidate for overload 7628 /// resolution [...] 7629 CandidateSet.exclude(FD); 7630 7631 if (Args[0]->getType()->isOverloadableType()) 7632 S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args); 7633 else { 7634 // FIXME: We determine whether this is a valid expression by checking to 7635 // see if there's a viable builtin operator candidate for it. That isn't 7636 // really what the rules ask us to do, but should give the right results. 7637 S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet); 7638 } 7639 7640 Result R; 7641 7642 OverloadCandidateSet::iterator Best; 7643 switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) { 7644 case OR_Success: { 7645 // C++2a [class.compare.secondary]p2 [P2002R0]: 7646 // The operator function [...] is defined as deleted if [...] the 7647 // candidate selected by overload resolution is not a rewritten 7648 // candidate. 7649 if ((DCK == DefaultedComparisonKind::NotEqual || 7650 DCK == DefaultedComparisonKind::Relational) && 7651 !Best->RewriteKind) { 7652 if (Diagnose == ExplainDeleted) { 7653 S.Diag(Best->Function->getLocation(), 7654 diag::note_defaulted_comparison_not_rewritten_callee) 7655 << FD; 7656 } 7657 return Result::deleted(); 7658 } 7659 7660 // Throughout C++2a [class.compare]: if overload resolution does not 7661 // result in a usable function, the candidate function is defined as 7662 // deleted. This requires that we selected an accessible function. 7663 // 7664 // Note that this only considers the access of the function when named 7665 // within the type of the subobject, and not the access path for any 7666 // derived-to-base conversion. 7667 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl(); 7668 if (ArgClass && Best->FoundDecl.getDecl() && 7669 Best->FoundDecl.getDecl()->isCXXClassMember()) { 7670 QualType ObjectType = Subobj.Kind == Subobject::Member 7671 ? Args[0]->getType() 7672 : S.Context.getRecordType(RD); 7673 if (!S.isMemberAccessibleForDeletion( 7674 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc, 7675 Diagnose == ExplainDeleted 7676 ? S.PDiag(diag::note_defaulted_comparison_inaccessible) 7677 << FD << Subobj.Kind << Subobj.Decl 7678 : S.PDiag())) 7679 return Result::deleted(); 7680 } 7681 7682 // C++2a [class.compare.default]p3 [P2002R0]: 7683 // A defaulted comparison function is constexpr-compatible if [...] 7684 // no overlod resolution performed [...] results in a non-constexpr 7685 // function. 7686 if (FunctionDecl *BestFD = Best->Function) { 7687 assert(!BestFD->isDeleted() && "wrong overload resolution result"); 7688 // If it's not constexpr, explain why not. 7689 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) { 7690 if (Subobj.Kind != Subobject::CompleteObject) 7691 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr) 7692 << Subobj.Kind << Subobj.Decl; 7693 S.Diag(BestFD->getLocation(), 7694 diag::note_defaulted_comparison_not_constexpr_here); 7695 // Bail out after explaining; we don't want any more notes. 7696 return Result::deleted(); 7697 } 7698 R.Constexpr &= BestFD->isConstexpr(); 7699 } 7700 7701 if (OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType()) { 7702 if (auto *BestFD = Best->Function) { 7703 // If any callee has an undeduced return type, deduce it now. 7704 // FIXME: It's not clear how a failure here should be handled. For 7705 // now, we produce an eager diagnostic, because that is forward 7706 // compatible with most (all?) other reasonable options. 7707 if (BestFD->getReturnType()->isUndeducedType() && 7708 S.DeduceReturnType(BestFD, FD->getLocation(), 7709 /*Diagnose=*/false)) { 7710 // Don't produce a duplicate error when asked to explain why the 7711 // comparison is deleted: we diagnosed that when initially checking 7712 // the defaulted operator. 7713 if (Diagnose == NoDiagnostics) { 7714 S.Diag( 7715 FD->getLocation(), 7716 diag::err_defaulted_comparison_cannot_deduce_undeduced_auto) 7717 << Subobj.Kind << Subobj.Decl; 7718 S.Diag( 7719 Subobj.Loc, 7720 diag::note_defaulted_comparison_cannot_deduce_undeduced_auto) 7721 << Subobj.Kind << Subobj.Decl; 7722 S.Diag(BestFD->getLocation(), 7723 diag::note_defaulted_comparison_cannot_deduce_callee) 7724 << Subobj.Kind << Subobj.Decl; 7725 } 7726 return Result::deleted(); 7727 } 7728 if (auto *Info = S.Context.CompCategories.lookupInfoForType( 7729 BestFD->getCallResultType())) { 7730 R.Category = Info->Kind; 7731 } else { 7732 if (Diagnose == ExplainDeleted) { 7733 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce) 7734 << Subobj.Kind << Subobj.Decl 7735 << BestFD->getCallResultType().withoutLocalFastQualifiers(); 7736 S.Diag(BestFD->getLocation(), 7737 diag::note_defaulted_comparison_cannot_deduce_callee) 7738 << Subobj.Kind << Subobj.Decl; 7739 } 7740 return Result::deleted(); 7741 } 7742 } else { 7743 Optional<ComparisonCategoryType> Cat = 7744 getComparisonCategoryForBuiltinCmp(Args[0]->getType()); 7745 assert(Cat && "no category for builtin comparison?"); 7746 R.Category = *Cat; 7747 } 7748 } 7749 7750 // Note that we might be rewriting to a different operator. That call is 7751 // not considered until we come to actually build the comparison function. 7752 break; 7753 } 7754 7755 case OR_Ambiguous: 7756 if (Diagnose == ExplainDeleted) { 7757 unsigned Kind = 0; 7758 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship) 7759 Kind = OO == OO_EqualEqual ? 1 : 2; 7760 CandidateSet.NoteCandidates( 7761 PartialDiagnosticAt( 7762 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous) 7763 << FD << Kind << Subobj.Kind << Subobj.Decl), 7764 S, OCD_AmbiguousCandidates, Args); 7765 } 7766 R = Result::deleted(); 7767 break; 7768 7769 case OR_Deleted: 7770 if (Diagnose == ExplainDeleted) { 7771 if ((DCK == DefaultedComparisonKind::NotEqual || 7772 DCK == DefaultedComparisonKind::Relational) && 7773 !Best->RewriteKind) { 7774 S.Diag(Best->Function->getLocation(), 7775 diag::note_defaulted_comparison_not_rewritten_callee) 7776 << FD; 7777 } else { 7778 S.Diag(Subobj.Loc, 7779 diag::note_defaulted_comparison_calls_deleted) 7780 << FD << Subobj.Kind << Subobj.Decl; 7781 S.NoteDeletedFunction(Best->Function); 7782 } 7783 } 7784 R = Result::deleted(); 7785 break; 7786 7787 case OR_No_Viable_Function: 7788 // If there's no usable candidate, we're done unless we can rewrite a 7789 // '<=>' in terms of '==' and '<'. 7790 if (OO == OO_Spaceship && 7791 S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) { 7792 // For any kind of comparison category return type, we need a usable 7793 // '==' and a usable '<'. 7794 if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj, 7795 &CandidateSet))) 7796 R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet)); 7797 break; 7798 } 7799 7800 if (Diagnose == ExplainDeleted) { 7801 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function) 7802 << FD << Subobj.Kind << Subobj.Decl; 7803 7804 // For a three-way comparison, list both the candidates for the 7805 // original operator and the candidates for the synthesized operator. 7806 if (SpaceshipCandidates) { 7807 SpaceshipCandidates->NoteCandidates( 7808 S, Args, 7809 SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates, 7810 Args, FD->getLocation())); 7811 S.Diag(Subobj.Loc, 7812 diag::note_defaulted_comparison_no_viable_function_synthesized) 7813 << (OO == OO_EqualEqual ? 0 : 1); 7814 } 7815 7816 CandidateSet.NoteCandidates( 7817 S, Args, 7818 CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args, 7819 FD->getLocation())); 7820 } 7821 R = Result::deleted(); 7822 break; 7823 } 7824 7825 return R; 7826 } 7827 }; 7828 7829 /// A list of statements. 7830 struct StmtListResult { 7831 bool IsInvalid = false; 7832 llvm::SmallVector<Stmt*, 16> Stmts; 7833 7834 bool add(const StmtResult &S) { 7835 IsInvalid |= S.isInvalid(); 7836 if (IsInvalid) 7837 return true; 7838 Stmts.push_back(S.get()); 7839 return false; 7840 } 7841 }; 7842 7843 /// A visitor over the notional body of a defaulted comparison that synthesizes 7844 /// the actual body. 7845 class DefaultedComparisonSynthesizer 7846 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer, 7847 StmtListResult, StmtResult, 7848 std::pair<ExprResult, ExprResult>> { 7849 SourceLocation Loc; 7850 unsigned ArrayDepth = 0; 7851 7852 public: 7853 using Base = DefaultedComparisonVisitor; 7854 using ExprPair = std::pair<ExprResult, ExprResult>; 7855 7856 friend Base; 7857 7858 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7859 DefaultedComparisonKind DCK, 7860 SourceLocation BodyLoc) 7861 : Base(S, RD, FD, DCK), Loc(BodyLoc) {} 7862 7863 /// Build a suitable function body for this defaulted comparison operator. 7864 StmtResult build() { 7865 Sema::CompoundScopeRAII CompoundScope(S); 7866 7867 StmtListResult Stmts = visit(); 7868 if (Stmts.IsInvalid) 7869 return StmtError(); 7870 7871 ExprResult RetVal; 7872 switch (DCK) { 7873 case DefaultedComparisonKind::None: 7874 llvm_unreachable("not a defaulted comparison"); 7875 7876 case DefaultedComparisonKind::Equal: { 7877 // C++2a [class.eq]p3: 7878 // [...] compar[e] the corresponding elements [...] until the first 7879 // index i where xi == yi yields [...] false. If no such index exists, 7880 // V is true. Otherwise, V is false. 7881 // 7882 // Join the comparisons with '&&'s and return the result. Use a right 7883 // fold (traversing the conditions right-to-left), because that 7884 // short-circuits more naturally. 7885 auto OldStmts = std::move(Stmts.Stmts); 7886 Stmts.Stmts.clear(); 7887 ExprResult CmpSoFar; 7888 // Finish a particular comparison chain. 7889 auto FinishCmp = [&] { 7890 if (Expr *Prior = CmpSoFar.get()) { 7891 // Convert the last expression to 'return ...;' 7892 if (RetVal.isUnset() && Stmts.Stmts.empty()) 7893 RetVal = CmpSoFar; 7894 // Convert any prior comparison to 'if (!(...)) return false;' 7895 else if (Stmts.add(buildIfNotCondReturnFalse(Prior))) 7896 return true; 7897 CmpSoFar = ExprResult(); 7898 } 7899 return false; 7900 }; 7901 for (Stmt *EAsStmt : llvm::reverse(OldStmts)) { 7902 Expr *E = dyn_cast<Expr>(EAsStmt); 7903 if (!E) { 7904 // Found an array comparison. 7905 if (FinishCmp() || Stmts.add(EAsStmt)) 7906 return StmtError(); 7907 continue; 7908 } 7909 7910 if (CmpSoFar.isUnset()) { 7911 CmpSoFar = E; 7912 continue; 7913 } 7914 CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get()); 7915 if (CmpSoFar.isInvalid()) 7916 return StmtError(); 7917 } 7918 if (FinishCmp()) 7919 return StmtError(); 7920 std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end()); 7921 // If no such index exists, V is true. 7922 if (RetVal.isUnset()) 7923 RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true); 7924 break; 7925 } 7926 7927 case DefaultedComparisonKind::ThreeWay: { 7928 // Per C++2a [class.spaceship]p3, as a fallback add: 7929 // return static_cast<R>(std::strong_ordering::equal); 7930 QualType StrongOrdering = S.CheckComparisonCategoryType( 7931 ComparisonCategoryType::StrongOrdering, Loc, 7932 Sema::ComparisonCategoryUsage::DefaultedOperator); 7933 if (StrongOrdering.isNull()) 7934 return StmtError(); 7935 VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering) 7936 .getValueInfo(ComparisonCategoryResult::Equal) 7937 ->VD; 7938 RetVal = getDecl(EqualVD); 7939 if (RetVal.isInvalid()) 7940 return StmtError(); 7941 RetVal = buildStaticCastToR(RetVal.get()); 7942 break; 7943 } 7944 7945 case DefaultedComparisonKind::NotEqual: 7946 case DefaultedComparisonKind::Relational: 7947 RetVal = cast<Expr>(Stmts.Stmts.pop_back_val()); 7948 break; 7949 } 7950 7951 // Build the final return statement. 7952 if (RetVal.isInvalid()) 7953 return StmtError(); 7954 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get()); 7955 if (ReturnStmt.isInvalid()) 7956 return StmtError(); 7957 Stmts.Stmts.push_back(ReturnStmt.get()); 7958 7959 return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false); 7960 } 7961 7962 private: 7963 ExprResult getDecl(ValueDecl *VD) { 7964 return S.BuildDeclarationNameExpr( 7965 CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD); 7966 } 7967 7968 ExprResult getParam(unsigned I) { 7969 ParmVarDecl *PD = FD->getParamDecl(I); 7970 return getDecl(PD); 7971 } 7972 7973 ExprPair getCompleteObject() { 7974 unsigned Param = 0; 7975 ExprResult LHS; 7976 if (isa<CXXMethodDecl>(FD)) { 7977 // LHS is '*this'. 7978 LHS = S.ActOnCXXThis(Loc); 7979 if (!LHS.isInvalid()) 7980 LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get()); 7981 } else { 7982 LHS = getParam(Param++); 7983 } 7984 ExprResult RHS = getParam(Param++); 7985 assert(Param == FD->getNumParams()); 7986 return {LHS, RHS}; 7987 } 7988 7989 ExprPair getBase(CXXBaseSpecifier *Base) { 7990 ExprPair Obj = getCompleteObject(); 7991 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 7992 return {ExprError(), ExprError()}; 7993 CXXCastPath Path = {Base}; 7994 return {S.ImpCastExprToType(Obj.first.get(), Base->getType(), 7995 CK_DerivedToBase, VK_LValue, &Path), 7996 S.ImpCastExprToType(Obj.second.get(), Base->getType(), 7997 CK_DerivedToBase, VK_LValue, &Path)}; 7998 } 7999 8000 ExprPair getField(FieldDecl *Field) { 8001 ExprPair Obj = getCompleteObject(); 8002 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 8003 return {ExprError(), ExprError()}; 8004 8005 DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess()); 8006 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc); 8007 return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc, 8008 CXXScopeSpec(), Field, Found, NameInfo), 8009 S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc, 8010 CXXScopeSpec(), Field, Found, NameInfo)}; 8011 } 8012 8013 // FIXME: When expanding a subobject, register a note in the code synthesis 8014 // stack to say which subobject we're comparing. 8015 8016 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) { 8017 if (Cond.isInvalid()) 8018 return StmtError(); 8019 8020 ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get()); 8021 if (NotCond.isInvalid()) 8022 return StmtError(); 8023 8024 ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false); 8025 assert(!False.isInvalid() && "should never fail"); 8026 StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get()); 8027 if (ReturnFalse.isInvalid()) 8028 return StmtError(); 8029 8030 return S.ActOnIfStmt(Loc, false, Loc, nullptr, 8031 S.ActOnCondition(nullptr, Loc, NotCond.get(), 8032 Sema::ConditionKind::Boolean), 8033 Loc, ReturnFalse.get(), SourceLocation(), nullptr); 8034 } 8035 8036 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size, 8037 ExprPair Subobj) { 8038 QualType SizeType = S.Context.getSizeType(); 8039 Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType)); 8040 8041 // Build 'size_t i$n = 0'. 8042 IdentifierInfo *IterationVarName = nullptr; 8043 { 8044 SmallString<8> Str; 8045 llvm::raw_svector_ostream OS(Str); 8046 OS << "i" << ArrayDepth; 8047 IterationVarName = &S.Context.Idents.get(OS.str()); 8048 } 8049 VarDecl *IterationVar = VarDecl::Create( 8050 S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType, 8051 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None); 8052 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 8053 IterationVar->setInit( 8054 IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 8055 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc); 8056 8057 auto IterRef = [&] { 8058 ExprResult Ref = S.BuildDeclarationNameExpr( 8059 CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc), 8060 IterationVar); 8061 assert(!Ref.isInvalid() && "can't reference our own variable?"); 8062 return Ref.get(); 8063 }; 8064 8065 // Build 'i$n != Size'. 8066 ExprResult Cond = S.CreateBuiltinBinOp( 8067 Loc, BO_NE, IterRef(), 8068 IntegerLiteral::Create(S.Context, Size, SizeType, Loc)); 8069 assert(!Cond.isInvalid() && "should never fail"); 8070 8071 // Build '++i$n'. 8072 ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef()); 8073 assert(!Inc.isInvalid() && "should never fail"); 8074 8075 // Build 'a[i$n]' and 'b[i$n]'. 8076 auto Index = [&](ExprResult E) { 8077 if (E.isInvalid()) 8078 return ExprError(); 8079 return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc); 8080 }; 8081 Subobj.first = Index(Subobj.first); 8082 Subobj.second = Index(Subobj.second); 8083 8084 // Compare the array elements. 8085 ++ArrayDepth; 8086 StmtResult Substmt = visitSubobject(Type, Subobj); 8087 --ArrayDepth; 8088 8089 if (Substmt.isInvalid()) 8090 return StmtError(); 8091 8092 // For the inner level of an 'operator==', build 'if (!cmp) return false;'. 8093 // For outer levels or for an 'operator<=>' we already have a suitable 8094 // statement that returns as necessary. 8095 if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) { 8096 assert(DCK == DefaultedComparisonKind::Equal && 8097 "should have non-expression statement"); 8098 Substmt = buildIfNotCondReturnFalse(ElemCmp); 8099 if (Substmt.isInvalid()) 8100 return StmtError(); 8101 } 8102 8103 // Build 'for (...) ...' 8104 return S.ActOnForStmt(Loc, Loc, Init, 8105 S.ActOnCondition(nullptr, Loc, Cond.get(), 8106 Sema::ConditionKind::Boolean), 8107 S.MakeFullDiscardedValueExpr(Inc.get()), Loc, 8108 Substmt.get()); 8109 } 8110 8111 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) { 8112 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 8113 return StmtError(); 8114 8115 OverloadedOperatorKind OO = FD->getOverloadedOperator(); 8116 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO); 8117 ExprResult Op; 8118 if (Type->isOverloadableType()) 8119 Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(), 8120 Obj.second.get(), /*PerformADL=*/true, 8121 /*AllowRewrittenCandidates=*/true, FD); 8122 else 8123 Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get()); 8124 if (Op.isInvalid()) 8125 return StmtError(); 8126 8127 switch (DCK) { 8128 case DefaultedComparisonKind::None: 8129 llvm_unreachable("not a defaulted comparison"); 8130 8131 case DefaultedComparisonKind::Equal: 8132 // Per C++2a [class.eq]p2, each comparison is individually contextually 8133 // converted to bool. 8134 Op = S.PerformContextuallyConvertToBool(Op.get()); 8135 if (Op.isInvalid()) 8136 return StmtError(); 8137 return Op.get(); 8138 8139 case DefaultedComparisonKind::ThreeWay: { 8140 // Per C++2a [class.spaceship]p3, form: 8141 // if (R cmp = static_cast<R>(op); cmp != 0) 8142 // return cmp; 8143 QualType R = FD->getReturnType(); 8144 Op = buildStaticCastToR(Op.get()); 8145 if (Op.isInvalid()) 8146 return StmtError(); 8147 8148 // R cmp = ...; 8149 IdentifierInfo *Name = &S.Context.Idents.get("cmp"); 8150 VarDecl *VD = 8151 VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R, 8152 S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None); 8153 S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false); 8154 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc); 8155 8156 // cmp != 0 8157 ExprResult VDRef = getDecl(VD); 8158 if (VDRef.isInvalid()) 8159 return StmtError(); 8160 llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0); 8161 Expr *Zero = 8162 IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc); 8163 ExprResult Comp; 8164 if (VDRef.get()->getType()->isOverloadableType()) 8165 Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true, 8166 true, FD); 8167 else 8168 Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero); 8169 if (Comp.isInvalid()) 8170 return StmtError(); 8171 Sema::ConditionResult Cond = S.ActOnCondition( 8172 nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean); 8173 if (Cond.isInvalid()) 8174 return StmtError(); 8175 8176 // return cmp; 8177 VDRef = getDecl(VD); 8178 if (VDRef.isInvalid()) 8179 return StmtError(); 8180 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get()); 8181 if (ReturnStmt.isInvalid()) 8182 return StmtError(); 8183 8184 // if (...) 8185 return S.ActOnIfStmt(Loc, /*IsConstexpr=*/false, Loc, InitStmt, Cond, Loc, 8186 ReturnStmt.get(), 8187 /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr); 8188 } 8189 8190 case DefaultedComparisonKind::NotEqual: 8191 case DefaultedComparisonKind::Relational: 8192 // C++2a [class.compare.secondary]p2: 8193 // Otherwise, the operator function yields x @ y. 8194 return Op.get(); 8195 } 8196 llvm_unreachable(""); 8197 } 8198 8199 /// Build "static_cast<R>(E)". 8200 ExprResult buildStaticCastToR(Expr *E) { 8201 QualType R = FD->getReturnType(); 8202 assert(!R->isUndeducedType() && "type should have been deduced already"); 8203 8204 // Don't bother forming a no-op cast in the common case. 8205 if (E->isRValue() && S.Context.hasSameType(E->getType(), R)) 8206 return E; 8207 return S.BuildCXXNamedCast(Loc, tok::kw_static_cast, 8208 S.Context.getTrivialTypeSourceInfo(R, Loc), E, 8209 SourceRange(Loc, Loc), SourceRange(Loc, Loc)); 8210 } 8211 }; 8212 } 8213 8214 /// Perform the unqualified lookups that might be needed to form a defaulted 8215 /// comparison function for the given operator. 8216 static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S, 8217 UnresolvedSetImpl &Operators, 8218 OverloadedOperatorKind Op) { 8219 auto Lookup = [&](OverloadedOperatorKind OO) { 8220 Self.LookupOverloadedOperatorName(OO, S, Operators); 8221 }; 8222 8223 // Every defaulted operator looks up itself. 8224 Lookup(Op); 8225 // ... and the rewritten form of itself, if any. 8226 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op)) 8227 Lookup(ExtraOp); 8228 8229 // For 'operator<=>', we also form a 'cmp != 0' expression, and might 8230 // synthesize a three-way comparison from '<' and '=='. In a dependent 8231 // context, we also need to look up '==' in case we implicitly declare a 8232 // defaulted 'operator=='. 8233 if (Op == OO_Spaceship) { 8234 Lookup(OO_ExclaimEqual); 8235 Lookup(OO_Less); 8236 Lookup(OO_EqualEqual); 8237 } 8238 } 8239 8240 bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD, 8241 DefaultedComparisonKind DCK) { 8242 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison"); 8243 8244 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()); 8245 assert(RD && "defaulted comparison is not defaulted in a class"); 8246 8247 // Perform any unqualified lookups we're going to need to default this 8248 // function. 8249 if (S) { 8250 UnresolvedSet<32> Operators; 8251 lookupOperatorsForDefaultedComparison(*this, S, Operators, 8252 FD->getOverloadedOperator()); 8253 FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create( 8254 Context, Operators.pairs())); 8255 } 8256 8257 // C++2a [class.compare.default]p1: 8258 // A defaulted comparison operator function for some class C shall be a 8259 // non-template function declared in the member-specification of C that is 8260 // -- a non-static const member of C having one parameter of type 8261 // const C&, or 8262 // -- a friend of C having two parameters of type const C& or two 8263 // parameters of type C. 8264 QualType ExpectedParmType1 = Context.getRecordType(RD); 8265 QualType ExpectedParmType2 = 8266 Context.getLValueReferenceType(ExpectedParmType1.withConst()); 8267 if (isa<CXXMethodDecl>(FD)) 8268 ExpectedParmType1 = ExpectedParmType2; 8269 for (const ParmVarDecl *Param : FD->parameters()) { 8270 if (!Param->getType()->isDependentType() && 8271 !Context.hasSameType(Param->getType(), ExpectedParmType1) && 8272 !Context.hasSameType(Param->getType(), ExpectedParmType2)) { 8273 // Don't diagnose an implicit 'operator=='; we will have diagnosed the 8274 // corresponding defaulted 'operator<=>' already. 8275 if (!FD->isImplicit()) { 8276 Diag(FD->getLocation(), diag::err_defaulted_comparison_param) 8277 << (int)DCK << Param->getType() << ExpectedParmType1 8278 << !isa<CXXMethodDecl>(FD) 8279 << ExpectedParmType2 << Param->getSourceRange(); 8280 } 8281 return true; 8282 } 8283 } 8284 if (FD->getNumParams() == 2 && 8285 !Context.hasSameType(FD->getParamDecl(0)->getType(), 8286 FD->getParamDecl(1)->getType())) { 8287 if (!FD->isImplicit()) { 8288 Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch) 8289 << (int)DCK 8290 << FD->getParamDecl(0)->getType() 8291 << FD->getParamDecl(0)->getSourceRange() 8292 << FD->getParamDecl(1)->getType() 8293 << FD->getParamDecl(1)->getSourceRange(); 8294 } 8295 return true; 8296 } 8297 8298 // ... non-static const member ... 8299 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 8300 assert(!MD->isStatic() && "comparison function cannot be a static member"); 8301 if (!MD->isConst()) { 8302 SourceLocation InsertLoc; 8303 if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc()) 8304 InsertLoc = getLocForEndOfToken(Loc.getRParenLoc()); 8305 // Don't diagnose an implicit 'operator=='; we will have diagnosed the 8306 // corresponding defaulted 'operator<=>' already. 8307 if (!MD->isImplicit()) { 8308 Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const) 8309 << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const"); 8310 } 8311 8312 // Add the 'const' to the type to recover. 8313 const auto *FPT = MD->getType()->castAs<FunctionProtoType>(); 8314 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8315 EPI.TypeQuals.addConst(); 8316 MD->setType(Context.getFunctionType(FPT->getReturnType(), 8317 FPT->getParamTypes(), EPI)); 8318 } 8319 } else { 8320 // A non-member function declared in a class must be a friend. 8321 assert(FD->getFriendObjectKind() && "expected a friend declaration"); 8322 } 8323 8324 // C++2a [class.eq]p1, [class.rel]p1: 8325 // A [defaulted comparison other than <=>] shall have a declared return 8326 // type bool. 8327 if (DCK != DefaultedComparisonKind::ThreeWay && 8328 !FD->getDeclaredReturnType()->isDependentType() && 8329 !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) { 8330 Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool) 8331 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy 8332 << FD->getReturnTypeSourceRange(); 8333 return true; 8334 } 8335 // C++2a [class.spaceship]p2 [P2002R0]: 8336 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise, 8337 // R shall not contain a placeholder type. 8338 if (DCK == DefaultedComparisonKind::ThreeWay && 8339 FD->getDeclaredReturnType()->getContainedDeducedType() && 8340 !Context.hasSameType(FD->getDeclaredReturnType(), 8341 Context.getAutoDeductType())) { 8342 Diag(FD->getLocation(), 8343 diag::err_defaulted_comparison_deduced_return_type_not_auto) 8344 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy 8345 << FD->getReturnTypeSourceRange(); 8346 return true; 8347 } 8348 8349 // For a defaulted function in a dependent class, defer all remaining checks 8350 // until instantiation. 8351 if (RD->isDependentType()) 8352 return false; 8353 8354 // Determine whether the function should be defined as deleted. 8355 DefaultedComparisonInfo Info = 8356 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit(); 8357 8358 bool First = FD == FD->getCanonicalDecl(); 8359 8360 // If we want to delete the function, then do so; there's nothing else to 8361 // check in that case. 8362 if (Info.Deleted) { 8363 if (!First) { 8364 // C++11 [dcl.fct.def.default]p4: 8365 // [For a] user-provided explicitly-defaulted function [...] if such a 8366 // function is implicitly defined as deleted, the program is ill-formed. 8367 // 8368 // This is really just a consequence of the general rule that you can 8369 // only delete a function on its first declaration. 8370 Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes) 8371 << FD->isImplicit() << (int)DCK; 8372 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8373 DefaultedComparisonAnalyzer::ExplainDeleted) 8374 .visit(); 8375 return true; 8376 } 8377 8378 SetDeclDeleted(FD, FD->getLocation()); 8379 if (!inTemplateInstantiation() && !FD->isImplicit()) { 8380 Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted) 8381 << (int)DCK; 8382 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8383 DefaultedComparisonAnalyzer::ExplainDeleted) 8384 .visit(); 8385 } 8386 return false; 8387 } 8388 8389 // C++2a [class.spaceship]p2: 8390 // The return type is deduced as the common comparison type of R0, R1, ... 8391 if (DCK == DefaultedComparisonKind::ThreeWay && 8392 FD->getDeclaredReturnType()->isUndeducedAutoType()) { 8393 SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin(); 8394 if (RetLoc.isInvalid()) 8395 RetLoc = FD->getBeginLoc(); 8396 // FIXME: Should we really care whether we have the complete type and the 8397 // 'enumerator' constants here? A forward declaration seems sufficient. 8398 QualType Cat = CheckComparisonCategoryType( 8399 Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator); 8400 if (Cat.isNull()) 8401 return true; 8402 Context.adjustDeducedFunctionResultType( 8403 FD, SubstAutoType(FD->getDeclaredReturnType(), Cat)); 8404 } 8405 8406 // C++2a [dcl.fct.def.default]p3 [P2002R0]: 8407 // An explicitly-defaulted function that is not defined as deleted may be 8408 // declared constexpr or consteval only if it is constexpr-compatible. 8409 // C++2a [class.compare.default]p3 [P2002R0]: 8410 // A defaulted comparison function is constexpr-compatible if it satisfies 8411 // the requirements for a constexpr function [...] 8412 // The only relevant requirements are that the parameter and return types are 8413 // literal types. The remaining conditions are checked by the analyzer. 8414 if (FD->isConstexpr()) { 8415 if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) && 8416 CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) && 8417 !Info.Constexpr) { 8418 Diag(FD->getBeginLoc(), 8419 diag::err_incorrect_defaulted_comparison_constexpr) 8420 << FD->isImplicit() << (int)DCK << FD->isConsteval(); 8421 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8422 DefaultedComparisonAnalyzer::ExplainConstexpr) 8423 .visit(); 8424 } 8425 } 8426 8427 // C++2a [dcl.fct.def.default]p3 [P2002R0]: 8428 // If a constexpr-compatible function is explicitly defaulted on its first 8429 // declaration, it is implicitly considered to be constexpr. 8430 // FIXME: Only applying this to the first declaration seems problematic, as 8431 // simple reorderings can affect the meaning of the program. 8432 if (First && !FD->isConstexpr() && Info.Constexpr) 8433 FD->setConstexprKind(CSK_constexpr); 8434 8435 // C++2a [except.spec]p3: 8436 // If a declaration of a function does not have a noexcept-specifier 8437 // [and] is defaulted on its first declaration, [...] the exception 8438 // specification is as specified below 8439 if (FD->getExceptionSpecType() == EST_None) { 8440 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 8441 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8442 EPI.ExceptionSpec.Type = EST_Unevaluated; 8443 EPI.ExceptionSpec.SourceDecl = FD; 8444 FD->setType(Context.getFunctionType(FPT->getReturnType(), 8445 FPT->getParamTypes(), EPI)); 8446 } 8447 8448 return false; 8449 } 8450 8451 void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD, 8452 FunctionDecl *Spaceship) { 8453 Sema::CodeSynthesisContext Ctx; 8454 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison; 8455 Ctx.PointOfInstantiation = Spaceship->getEndLoc(); 8456 Ctx.Entity = Spaceship; 8457 pushCodeSynthesisContext(Ctx); 8458 8459 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship)) 8460 EqualEqual->setImplicit(); 8461 8462 popCodeSynthesisContext(); 8463 } 8464 8465 void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD, 8466 DefaultedComparisonKind DCK) { 8467 assert(FD->isDefaulted() && !FD->isDeleted() && 8468 !FD->doesThisDeclarationHaveABody()); 8469 if (FD->willHaveBody() || FD->isInvalidDecl()) 8470 return; 8471 8472 SynthesizedFunctionScope Scope(*this, FD); 8473 8474 // Add a context note for diagnostics produced after this point. 8475 Scope.addContextNote(UseLoc); 8476 8477 { 8478 // Build and set up the function body. 8479 CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent()); 8480 SourceLocation BodyLoc = 8481 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation(); 8482 StmtResult Body = 8483 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build(); 8484 if (Body.isInvalid()) { 8485 FD->setInvalidDecl(); 8486 return; 8487 } 8488 FD->setBody(Body.get()); 8489 FD->markUsed(Context); 8490 } 8491 8492 // The exception specification is needed because we are defining the 8493 // function. Note that this will reuse the body we just built. 8494 ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>()); 8495 8496 if (ASTMutationListener *L = getASTMutationListener()) 8497 L->CompletedImplicitDefinition(FD); 8498 } 8499 8500 static Sema::ImplicitExceptionSpecification 8501 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, 8502 FunctionDecl *FD, 8503 Sema::DefaultedComparisonKind DCK) { 8504 ComputingExceptionSpec CES(S, FD, Loc); 8505 Sema::ImplicitExceptionSpecification ExceptSpec(S); 8506 8507 if (FD->isInvalidDecl()) 8508 return ExceptSpec; 8509 8510 // The common case is that we just defined the comparison function. In that 8511 // case, just look at whether the body can throw. 8512 if (FD->hasBody()) { 8513 ExceptSpec.CalledStmt(FD->getBody()); 8514 } else { 8515 // Otherwise, build a body so we can check it. This should ideally only 8516 // happen when we're not actually marking the function referenced. (This is 8517 // only really important for efficiency: we don't want to build and throw 8518 // away bodies for comparison functions more than we strictly need to.) 8519 8520 // Pretend to synthesize the function body in an unevaluated context. 8521 // Note that we can't actually just go ahead and define the function here: 8522 // we are not permitted to mark its callees as referenced. 8523 Sema::SynthesizedFunctionScope Scope(S, FD); 8524 EnterExpressionEvaluationContext Context( 8525 S, Sema::ExpressionEvaluationContext::Unevaluated); 8526 8527 CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent()); 8528 SourceLocation BodyLoc = 8529 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation(); 8530 StmtResult Body = 8531 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build(); 8532 if (!Body.isInvalid()) 8533 ExceptSpec.CalledStmt(Body.get()); 8534 8535 // FIXME: Can we hold onto this body and just transform it to potentially 8536 // evaluated when we're asked to define the function rather than rebuilding 8537 // it? Either that, or we should only build the bits of the body that we 8538 // need (the expressions, not the statements). 8539 } 8540 8541 return ExceptSpec; 8542 } 8543 8544 void Sema::CheckDelayedMemberExceptionSpecs() { 8545 decltype(DelayedOverridingExceptionSpecChecks) Overriding; 8546 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent; 8547 8548 std::swap(Overriding, DelayedOverridingExceptionSpecChecks); 8549 std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks); 8550 8551 // Perform any deferred checking of exception specifications for virtual 8552 // destructors. 8553 for (auto &Check : Overriding) 8554 CheckOverridingFunctionExceptionSpec(Check.first, Check.second); 8555 8556 // Perform any deferred checking of exception specifications for befriended 8557 // special members. 8558 for (auto &Check : Equivalent) 8559 CheckEquivalentExceptionSpec(Check.second, Check.first); 8560 } 8561 8562 namespace { 8563 /// CRTP base class for visiting operations performed by a special member 8564 /// function (or inherited constructor). 8565 template<typename Derived> 8566 struct SpecialMemberVisitor { 8567 Sema &S; 8568 CXXMethodDecl *MD; 8569 Sema::CXXSpecialMember CSM; 8570 Sema::InheritedConstructorInfo *ICI; 8571 8572 // Properties of the special member, computed for convenience. 8573 bool IsConstructor = false, IsAssignment = false, ConstArg = false; 8574 8575 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 8576 Sema::InheritedConstructorInfo *ICI) 8577 : S(S), MD(MD), CSM(CSM), ICI(ICI) { 8578 switch (CSM) { 8579 case Sema::CXXDefaultConstructor: 8580 case Sema::CXXCopyConstructor: 8581 case Sema::CXXMoveConstructor: 8582 IsConstructor = true; 8583 break; 8584 case Sema::CXXCopyAssignment: 8585 case Sema::CXXMoveAssignment: 8586 IsAssignment = true; 8587 break; 8588 case Sema::CXXDestructor: 8589 break; 8590 case Sema::CXXInvalid: 8591 llvm_unreachable("invalid special member kind"); 8592 } 8593 8594 if (MD->getNumParams()) { 8595 if (const ReferenceType *RT = 8596 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 8597 ConstArg = RT->getPointeeType().isConstQualified(); 8598 } 8599 } 8600 8601 Derived &getDerived() { return static_cast<Derived&>(*this); } 8602 8603 /// Is this a "move" special member? 8604 bool isMove() const { 8605 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment; 8606 } 8607 8608 /// Look up the corresponding special member in the given class. 8609 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class, 8610 unsigned Quals, bool IsMutable) { 8611 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 8612 ConstArg && !IsMutable); 8613 } 8614 8615 /// Look up the constructor for the specified base class to see if it's 8616 /// overridden due to this being an inherited constructor. 8617 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) { 8618 if (!ICI) 8619 return {}; 8620 assert(CSM == Sema::CXXDefaultConstructor); 8621 auto *BaseCtor = 8622 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor(); 8623 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first) 8624 return MD; 8625 return {}; 8626 } 8627 8628 /// A base or member subobject. 8629 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 8630 8631 /// Get the location to use for a subobject in diagnostics. 8632 static SourceLocation getSubobjectLoc(Subobject Subobj) { 8633 // FIXME: For an indirect virtual base, the direct base leading to 8634 // the indirect virtual base would be a more useful choice. 8635 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>()) 8636 return B->getBaseTypeLoc(); 8637 else 8638 return Subobj.get<FieldDecl*>()->getLocation(); 8639 } 8640 8641 enum BasesToVisit { 8642 /// Visit all non-virtual (direct) bases. 8643 VisitNonVirtualBases, 8644 /// Visit all direct bases, virtual or not. 8645 VisitDirectBases, 8646 /// Visit all non-virtual bases, and all virtual bases if the class 8647 /// is not abstract. 8648 VisitPotentiallyConstructedBases, 8649 /// Visit all direct or virtual bases. 8650 VisitAllBases 8651 }; 8652 8653 // Visit the bases and members of the class. 8654 bool visit(BasesToVisit Bases) { 8655 CXXRecordDecl *RD = MD->getParent(); 8656 8657 if (Bases == VisitPotentiallyConstructedBases) 8658 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases; 8659 8660 for (auto &B : RD->bases()) 8661 if ((Bases == VisitDirectBases || !B.isVirtual()) && 8662 getDerived().visitBase(&B)) 8663 return true; 8664 8665 if (Bases == VisitAllBases) 8666 for (auto &B : RD->vbases()) 8667 if (getDerived().visitBase(&B)) 8668 return true; 8669 8670 for (auto *F : RD->fields()) 8671 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() && 8672 getDerived().visitField(F)) 8673 return true; 8674 8675 return false; 8676 } 8677 }; 8678 } 8679 8680 namespace { 8681 struct SpecialMemberDeletionInfo 8682 : SpecialMemberVisitor<SpecialMemberDeletionInfo> { 8683 bool Diagnose; 8684 8685 SourceLocation Loc; 8686 8687 bool AllFieldsAreConst; 8688 8689 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 8690 Sema::CXXSpecialMember CSM, 8691 Sema::InheritedConstructorInfo *ICI, bool Diagnose) 8692 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose), 8693 Loc(MD->getLocation()), AllFieldsAreConst(true) {} 8694 8695 bool inUnion() const { return MD->getParent()->isUnion(); } 8696 8697 Sema::CXXSpecialMember getEffectiveCSM() { 8698 return ICI ? Sema::CXXInvalid : CSM; 8699 } 8700 8701 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType); 8702 8703 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); } 8704 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); } 8705 8706 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 8707 bool shouldDeleteForField(FieldDecl *FD); 8708 bool shouldDeleteForAllConstMembers(); 8709 8710 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 8711 unsigned Quals); 8712 bool shouldDeleteForSubobjectCall(Subobject Subobj, 8713 Sema::SpecialMemberOverloadResult SMOR, 8714 bool IsDtorCallInCtor); 8715 8716 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 8717 }; 8718 } 8719 8720 /// Is the given special member inaccessible when used on the given 8721 /// sub-object. 8722 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 8723 CXXMethodDecl *target) { 8724 /// If we're operating on a base class, the object type is the 8725 /// type of this special member. 8726 QualType objectTy; 8727 AccessSpecifier access = target->getAccess(); 8728 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 8729 objectTy = S.Context.getTypeDeclType(MD->getParent()); 8730 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 8731 8732 // If we're operating on a field, the object type is the type of the field. 8733 } else { 8734 objectTy = S.Context.getTypeDeclType(target->getParent()); 8735 } 8736 8737 return S.isMemberAccessibleForDeletion( 8738 target->getParent(), DeclAccessPair::make(target, access), objectTy); 8739 } 8740 8741 /// Check whether we should delete a special member due to the implicit 8742 /// definition containing a call to a special member of a subobject. 8743 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 8744 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR, 8745 bool IsDtorCallInCtor) { 8746 CXXMethodDecl *Decl = SMOR.getMethod(); 8747 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 8748 8749 int DiagKind = -1; 8750 8751 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 8752 DiagKind = !Decl ? 0 : 1; 8753 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 8754 DiagKind = 2; 8755 else if (!isAccessible(Subobj, Decl)) 8756 DiagKind = 3; 8757 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 8758 !Decl->isTrivial()) { 8759 // A member of a union must have a trivial corresponding special member. 8760 // As a weird special case, a destructor call from a union's constructor 8761 // must be accessible and non-deleted, but need not be trivial. Such a 8762 // destructor is never actually called, but is semantically checked as 8763 // if it were. 8764 DiagKind = 4; 8765 } 8766 8767 if (DiagKind == -1) 8768 return false; 8769 8770 if (Diagnose) { 8771 if (Field) { 8772 S.Diag(Field->getLocation(), 8773 diag::note_deleted_special_member_class_subobject) 8774 << getEffectiveCSM() << MD->getParent() << /*IsField*/true 8775 << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false; 8776 } else { 8777 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 8778 S.Diag(Base->getBeginLoc(), 8779 diag::note_deleted_special_member_class_subobject) 8780 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 8781 << Base->getType() << DiagKind << IsDtorCallInCtor 8782 << /*IsObjCPtr*/false; 8783 } 8784 8785 if (DiagKind == 1) 8786 S.NoteDeletedFunction(Decl); 8787 // FIXME: Explain inaccessibility if DiagKind == 3. 8788 } 8789 8790 return true; 8791 } 8792 8793 /// Check whether we should delete a special member function due to having a 8794 /// direct or virtual base class or non-static data member of class type M. 8795 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 8796 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 8797 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 8798 bool IsMutable = Field && Field->isMutable(); 8799 8800 // C++11 [class.ctor]p5: 8801 // -- any direct or virtual base class, or non-static data member with no 8802 // brace-or-equal-initializer, has class type M (or array thereof) and 8803 // either M has no default constructor or overload resolution as applied 8804 // to M's default constructor results in an ambiguity or in a function 8805 // that is deleted or inaccessible 8806 // C++11 [class.copy]p11, C++11 [class.copy]p23: 8807 // -- a direct or virtual base class B that cannot be copied/moved because 8808 // overload resolution, as applied to B's corresponding special member, 8809 // results in an ambiguity or a function that is deleted or inaccessible 8810 // from the defaulted special member 8811 // C++11 [class.dtor]p5: 8812 // -- any direct or virtual base class [...] has a type with a destructor 8813 // that is deleted or inaccessible 8814 if (!(CSM == Sema::CXXDefaultConstructor && 8815 Field && Field->hasInClassInitializer()) && 8816 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 8817 false)) 8818 return true; 8819 8820 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 8821 // -- any direct or virtual base class or non-static data member has a 8822 // type with a destructor that is deleted or inaccessible 8823 if (IsConstructor) { 8824 Sema::SpecialMemberOverloadResult SMOR = 8825 S.LookupSpecialMember(Class, Sema::CXXDestructor, 8826 false, false, false, false, false); 8827 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 8828 return true; 8829 } 8830 8831 return false; 8832 } 8833 8834 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember( 8835 FieldDecl *FD, QualType FieldType) { 8836 // The defaulted special functions are defined as deleted if this is a variant 8837 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak 8838 // type under ARC. 8839 if (!FieldType.hasNonTrivialObjCLifetime()) 8840 return false; 8841 8842 // Don't make the defaulted default constructor defined as deleted if the 8843 // member has an in-class initializer. 8844 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) 8845 return false; 8846 8847 if (Diagnose) { 8848 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent()); 8849 S.Diag(FD->getLocation(), 8850 diag::note_deleted_special_member_class_subobject) 8851 << getEffectiveCSM() << ParentClass << /*IsField*/true 8852 << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true; 8853 } 8854 8855 return true; 8856 } 8857 8858 /// Check whether we should delete a special member function due to the class 8859 /// having a particular direct or virtual base class. 8860 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 8861 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 8862 // If program is correct, BaseClass cannot be null, but if it is, the error 8863 // must be reported elsewhere. 8864 if (!BaseClass) 8865 return false; 8866 // If we have an inheriting constructor, check whether we're calling an 8867 // inherited constructor instead of a default constructor. 8868 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 8869 if (auto *BaseCtor = SMOR.getMethod()) { 8870 // Note that we do not check access along this path; other than that, 8871 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false); 8872 // FIXME: Check that the base has a usable destructor! Sink this into 8873 // shouldDeleteForClassSubobject. 8874 if (BaseCtor->isDeleted() && Diagnose) { 8875 S.Diag(Base->getBeginLoc(), 8876 diag::note_deleted_special_member_class_subobject) 8877 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 8878 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false 8879 << /*IsObjCPtr*/false; 8880 S.NoteDeletedFunction(BaseCtor); 8881 } 8882 return BaseCtor->isDeleted(); 8883 } 8884 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 8885 } 8886 8887 /// Check whether we should delete a special member function due to the class 8888 /// having a particular non-static data member. 8889 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 8890 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 8891 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 8892 8893 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType)) 8894 return true; 8895 8896 if (CSM == Sema::CXXDefaultConstructor) { 8897 // For a default constructor, all references must be initialized in-class 8898 // and, if a union, it must have a non-const member. 8899 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 8900 if (Diagnose) 8901 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 8902 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0; 8903 return true; 8904 } 8905 // C++11 [class.ctor]p5: any non-variant non-static data member of 8906 // const-qualified type (or array thereof) with no 8907 // brace-or-equal-initializer does not have a user-provided default 8908 // constructor. 8909 if (!inUnion() && FieldType.isConstQualified() && 8910 !FD->hasInClassInitializer() && 8911 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 8912 if (Diagnose) 8913 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 8914 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1; 8915 return true; 8916 } 8917 8918 if (inUnion() && !FieldType.isConstQualified()) 8919 AllFieldsAreConst = false; 8920 } else if (CSM == Sema::CXXCopyConstructor) { 8921 // For a copy constructor, data members must not be of rvalue reference 8922 // type. 8923 if (FieldType->isRValueReferenceType()) { 8924 if (Diagnose) 8925 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 8926 << MD->getParent() << FD << FieldType; 8927 return true; 8928 } 8929 } else if (IsAssignment) { 8930 // For an assignment operator, data members must not be of reference type. 8931 if (FieldType->isReferenceType()) { 8932 if (Diagnose) 8933 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 8934 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0; 8935 return true; 8936 } 8937 if (!FieldRecord && FieldType.isConstQualified()) { 8938 // C++11 [class.copy]p23: 8939 // -- a non-static data member of const non-class type (or array thereof) 8940 if (Diagnose) 8941 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 8942 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1; 8943 return true; 8944 } 8945 } 8946 8947 if (FieldRecord) { 8948 // Some additional restrictions exist on the variant members. 8949 if (!inUnion() && FieldRecord->isUnion() && 8950 FieldRecord->isAnonymousStructOrUnion()) { 8951 bool AllVariantFieldsAreConst = true; 8952 8953 // FIXME: Handle anonymous unions declared within anonymous unions. 8954 for (auto *UI : FieldRecord->fields()) { 8955 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 8956 8957 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType)) 8958 return true; 8959 8960 if (!UnionFieldType.isConstQualified()) 8961 AllVariantFieldsAreConst = false; 8962 8963 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 8964 if (UnionFieldRecord && 8965 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 8966 UnionFieldType.getCVRQualifiers())) 8967 return true; 8968 } 8969 8970 // At least one member in each anonymous union must be non-const 8971 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 8972 !FieldRecord->field_empty()) { 8973 if (Diagnose) 8974 S.Diag(FieldRecord->getLocation(), 8975 diag::note_deleted_default_ctor_all_const) 8976 << !!ICI << MD->getParent() << /*anonymous union*/1; 8977 return true; 8978 } 8979 8980 // Don't check the implicit member of the anonymous union type. 8981 // This is technically non-conformant, but sanity demands it. 8982 return false; 8983 } 8984 8985 if (shouldDeleteForClassSubobject(FieldRecord, FD, 8986 FieldType.getCVRQualifiers())) 8987 return true; 8988 } 8989 8990 return false; 8991 } 8992 8993 /// C++11 [class.ctor] p5: 8994 /// A defaulted default constructor for a class X is defined as deleted if 8995 /// X is a union and all of its variant members are of const-qualified type. 8996 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 8997 // This is a silly definition, because it gives an empty union a deleted 8998 // default constructor. Don't do that. 8999 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) { 9000 bool AnyFields = false; 9001 for (auto *F : MD->getParent()->fields()) 9002 if ((AnyFields = !F->isUnnamedBitfield())) 9003 break; 9004 if (!AnyFields) 9005 return false; 9006 if (Diagnose) 9007 S.Diag(MD->getParent()->getLocation(), 9008 diag::note_deleted_default_ctor_all_const) 9009 << !!ICI << MD->getParent() << /*not anonymous union*/0; 9010 return true; 9011 } 9012 return false; 9013 } 9014 9015 /// Determine whether a defaulted special member function should be defined as 9016 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 9017 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 9018 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 9019 InheritedConstructorInfo *ICI, 9020 bool Diagnose) { 9021 if (MD->isInvalidDecl()) 9022 return false; 9023 CXXRecordDecl *RD = MD->getParent(); 9024 assert(!RD->isDependentType() && "do deletion after instantiation"); 9025 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 9026 return false; 9027 9028 // C++11 [expr.lambda.prim]p19: 9029 // The closure type associated with a lambda-expression has a 9030 // deleted (8.4.3) default constructor and a deleted copy 9031 // assignment operator. 9032 // C++2a adds back these operators if the lambda has no lambda-capture. 9033 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() && 9034 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 9035 if (Diagnose) 9036 Diag(RD->getLocation(), diag::note_lambda_decl); 9037 return true; 9038 } 9039 9040 // For an anonymous struct or union, the copy and assignment special members 9041 // will never be used, so skip the check. For an anonymous union declared at 9042 // namespace scope, the constructor and destructor are used. 9043 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 9044 RD->isAnonymousStructOrUnion()) 9045 return false; 9046 9047 // C++11 [class.copy]p7, p18: 9048 // If the class definition declares a move constructor or move assignment 9049 // operator, an implicitly declared copy constructor or copy assignment 9050 // operator is defined as deleted. 9051 if (MD->isImplicit() && 9052 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 9053 CXXMethodDecl *UserDeclaredMove = nullptr; 9054 9055 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the 9056 // deletion of the corresponding copy operation, not both copy operations. 9057 // MSVC 2015 has adopted the standards conforming behavior. 9058 bool DeletesOnlyMatchingCopy = 9059 getLangOpts().MSVCCompat && 9060 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015); 9061 9062 if (RD->hasUserDeclaredMoveConstructor() && 9063 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) { 9064 if (!Diagnose) return true; 9065 9066 // Find any user-declared move constructor. 9067 for (auto *I : RD->ctors()) { 9068 if (I->isMoveConstructor()) { 9069 UserDeclaredMove = I; 9070 break; 9071 } 9072 } 9073 assert(UserDeclaredMove); 9074 } else if (RD->hasUserDeclaredMoveAssignment() && 9075 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) { 9076 if (!Diagnose) return true; 9077 9078 // Find any user-declared move assignment operator. 9079 for (auto *I : RD->methods()) { 9080 if (I->isMoveAssignmentOperator()) { 9081 UserDeclaredMove = I; 9082 break; 9083 } 9084 } 9085 assert(UserDeclaredMove); 9086 } 9087 9088 if (UserDeclaredMove) { 9089 Diag(UserDeclaredMove->getLocation(), 9090 diag::note_deleted_copy_user_declared_move) 9091 << (CSM == CXXCopyAssignment) << RD 9092 << UserDeclaredMove->isMoveAssignmentOperator(); 9093 return true; 9094 } 9095 } 9096 9097 // Do access control from the special member function 9098 ContextRAII MethodContext(*this, MD); 9099 9100 // C++11 [class.dtor]p5: 9101 // -- for a virtual destructor, lookup of the non-array deallocation function 9102 // results in an ambiguity or in a function that is deleted or inaccessible 9103 if (CSM == CXXDestructor && MD->isVirtual()) { 9104 FunctionDecl *OperatorDelete = nullptr; 9105 DeclarationName Name = 9106 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 9107 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 9108 OperatorDelete, /*Diagnose*/false)) { 9109 if (Diagnose) 9110 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 9111 return true; 9112 } 9113 } 9114 9115 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose); 9116 9117 // Per DR1611, do not consider virtual bases of constructors of abstract 9118 // classes, since we are not going to construct them. 9119 // Per DR1658, do not consider virtual bases of destructors of abstract 9120 // classes either. 9121 // Per DR2180, for assignment operators we only assign (and thus only 9122 // consider) direct bases. 9123 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases 9124 : SMI.VisitPotentiallyConstructedBases)) 9125 return true; 9126 9127 if (SMI.shouldDeleteForAllConstMembers()) 9128 return true; 9129 9130 if (getLangOpts().CUDA) { 9131 // We should delete the special member in CUDA mode if target inference 9132 // failed. 9133 // For inherited constructors (non-null ICI), CSM may be passed so that MD 9134 // is treated as certain special member, which may not reflect what special 9135 // member MD really is. However inferCUDATargetForImplicitSpecialMember 9136 // expects CSM to match MD, therefore recalculate CSM. 9137 assert(ICI || CSM == getSpecialMember(MD)); 9138 auto RealCSM = CSM; 9139 if (ICI) 9140 RealCSM = getSpecialMember(MD); 9141 9142 return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD, 9143 SMI.ConstArg, Diagnose); 9144 } 9145 9146 return false; 9147 } 9148 9149 void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) { 9150 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD); 9151 assert(DFK && "not a defaultable function"); 9152 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted"); 9153 9154 if (DFK.isSpecialMember()) { 9155 ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), 9156 nullptr, /*Diagnose=*/true); 9157 } else { 9158 DefaultedComparisonAnalyzer( 9159 *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD, 9160 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted) 9161 .visit(); 9162 } 9163 } 9164 9165 /// Perform lookup for a special member of the specified kind, and determine 9166 /// whether it is trivial. If the triviality can be determined without the 9167 /// lookup, skip it. This is intended for use when determining whether a 9168 /// special member of a containing object is trivial, and thus does not ever 9169 /// perform overload resolution for default constructors. 9170 /// 9171 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 9172 /// member that was most likely to be intended to be trivial, if any. 9173 /// 9174 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to 9175 /// determine whether the special member is trivial. 9176 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 9177 Sema::CXXSpecialMember CSM, unsigned Quals, 9178 bool ConstRHS, 9179 Sema::TrivialABIHandling TAH, 9180 CXXMethodDecl **Selected) { 9181 if (Selected) 9182 *Selected = nullptr; 9183 9184 switch (CSM) { 9185 case Sema::CXXInvalid: 9186 llvm_unreachable("not a special member"); 9187 9188 case Sema::CXXDefaultConstructor: 9189 // C++11 [class.ctor]p5: 9190 // A default constructor is trivial if: 9191 // - all the [direct subobjects] have trivial default constructors 9192 // 9193 // Note, no overload resolution is performed in this case. 9194 if (RD->hasTrivialDefaultConstructor()) 9195 return true; 9196 9197 if (Selected) { 9198 // If there's a default constructor which could have been trivial, dig it 9199 // out. Otherwise, if there's any user-provided default constructor, point 9200 // to that as an example of why there's not a trivial one. 9201 CXXConstructorDecl *DefCtor = nullptr; 9202 if (RD->needsImplicitDefaultConstructor()) 9203 S.DeclareImplicitDefaultConstructor(RD); 9204 for (auto *CI : RD->ctors()) { 9205 if (!CI->isDefaultConstructor()) 9206 continue; 9207 DefCtor = CI; 9208 if (!DefCtor->isUserProvided()) 9209 break; 9210 } 9211 9212 *Selected = DefCtor; 9213 } 9214 9215 return false; 9216 9217 case Sema::CXXDestructor: 9218 // C++11 [class.dtor]p5: 9219 // A destructor is trivial if: 9220 // - all the direct [subobjects] have trivial destructors 9221 if (RD->hasTrivialDestructor() || 9222 (TAH == Sema::TAH_ConsiderTrivialABI && 9223 RD->hasTrivialDestructorForCall())) 9224 return true; 9225 9226 if (Selected) { 9227 if (RD->needsImplicitDestructor()) 9228 S.DeclareImplicitDestructor(RD); 9229 *Selected = RD->getDestructor(); 9230 } 9231 9232 return false; 9233 9234 case Sema::CXXCopyConstructor: 9235 // C++11 [class.copy]p12: 9236 // A copy constructor is trivial if: 9237 // - the constructor selected to copy each direct [subobject] is trivial 9238 if (RD->hasTrivialCopyConstructor() || 9239 (TAH == Sema::TAH_ConsiderTrivialABI && 9240 RD->hasTrivialCopyConstructorForCall())) { 9241 if (Quals == Qualifiers::Const) 9242 // We must either select the trivial copy constructor or reach an 9243 // ambiguity; no need to actually perform overload resolution. 9244 return true; 9245 } else if (!Selected) { 9246 return false; 9247 } 9248 // In C++98, we are not supposed to perform overload resolution here, but we 9249 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 9250 // cases like B as having a non-trivial copy constructor: 9251 // struct A { template<typename T> A(T&); }; 9252 // struct B { mutable A a; }; 9253 goto NeedOverloadResolution; 9254 9255 case Sema::CXXCopyAssignment: 9256 // C++11 [class.copy]p25: 9257 // A copy assignment operator is trivial if: 9258 // - the assignment operator selected to copy each direct [subobject] is 9259 // trivial 9260 if (RD->hasTrivialCopyAssignment()) { 9261 if (Quals == Qualifiers::Const) 9262 return true; 9263 } else if (!Selected) { 9264 return false; 9265 } 9266 // In C++98, we are not supposed to perform overload resolution here, but we 9267 // treat that as a language defect. 9268 goto NeedOverloadResolution; 9269 9270 case Sema::CXXMoveConstructor: 9271 case Sema::CXXMoveAssignment: 9272 NeedOverloadResolution: 9273 Sema::SpecialMemberOverloadResult SMOR = 9274 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 9275 9276 // The standard doesn't describe how to behave if the lookup is ambiguous. 9277 // We treat it as not making the member non-trivial, just like the standard 9278 // mandates for the default constructor. This should rarely matter, because 9279 // the member will also be deleted. 9280 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 9281 return true; 9282 9283 if (!SMOR.getMethod()) { 9284 assert(SMOR.getKind() == 9285 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 9286 return false; 9287 } 9288 9289 // We deliberately don't check if we found a deleted special member. We're 9290 // not supposed to! 9291 if (Selected) 9292 *Selected = SMOR.getMethod(); 9293 9294 if (TAH == Sema::TAH_ConsiderTrivialABI && 9295 (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor)) 9296 return SMOR.getMethod()->isTrivialForCall(); 9297 return SMOR.getMethod()->isTrivial(); 9298 } 9299 9300 llvm_unreachable("unknown special method kind"); 9301 } 9302 9303 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 9304 for (auto *CI : RD->ctors()) 9305 if (!CI->isImplicit()) 9306 return CI; 9307 9308 // Look for constructor templates. 9309 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 9310 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 9311 if (CXXConstructorDecl *CD = 9312 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 9313 return CD; 9314 } 9315 9316 return nullptr; 9317 } 9318 9319 /// The kind of subobject we are checking for triviality. The values of this 9320 /// enumeration are used in diagnostics. 9321 enum TrivialSubobjectKind { 9322 /// The subobject is a base class. 9323 TSK_BaseClass, 9324 /// The subobject is a non-static data member. 9325 TSK_Field, 9326 /// The object is actually the complete object. 9327 TSK_CompleteObject 9328 }; 9329 9330 /// Check whether the special member selected for a given type would be trivial. 9331 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 9332 QualType SubType, bool ConstRHS, 9333 Sema::CXXSpecialMember CSM, 9334 TrivialSubobjectKind Kind, 9335 Sema::TrivialABIHandling TAH, bool Diagnose) { 9336 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 9337 if (!SubRD) 9338 return true; 9339 9340 CXXMethodDecl *Selected; 9341 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 9342 ConstRHS, TAH, Diagnose ? &Selected : nullptr)) 9343 return true; 9344 9345 if (Diagnose) { 9346 if (ConstRHS) 9347 SubType.addConst(); 9348 9349 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 9350 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 9351 << Kind << SubType.getUnqualifiedType(); 9352 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 9353 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 9354 } else if (!Selected) 9355 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 9356 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 9357 else if (Selected->isUserProvided()) { 9358 if (Kind == TSK_CompleteObject) 9359 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 9360 << Kind << SubType.getUnqualifiedType() << CSM; 9361 else { 9362 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 9363 << Kind << SubType.getUnqualifiedType() << CSM; 9364 S.Diag(Selected->getLocation(), diag::note_declared_at); 9365 } 9366 } else { 9367 if (Kind != TSK_CompleteObject) 9368 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 9369 << Kind << SubType.getUnqualifiedType() << CSM; 9370 9371 // Explain why the defaulted or deleted special member isn't trivial. 9372 S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI, 9373 Diagnose); 9374 } 9375 } 9376 9377 return false; 9378 } 9379 9380 /// Check whether the members of a class type allow a special member to be 9381 /// trivial. 9382 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 9383 Sema::CXXSpecialMember CSM, 9384 bool ConstArg, 9385 Sema::TrivialABIHandling TAH, 9386 bool Diagnose) { 9387 for (const auto *FI : RD->fields()) { 9388 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 9389 continue; 9390 9391 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 9392 9393 // Pretend anonymous struct or union members are members of this class. 9394 if (FI->isAnonymousStructOrUnion()) { 9395 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 9396 CSM, ConstArg, TAH, Diagnose)) 9397 return false; 9398 continue; 9399 } 9400 9401 // C++11 [class.ctor]p5: 9402 // A default constructor is trivial if [...] 9403 // -- no non-static data member of its class has a 9404 // brace-or-equal-initializer 9405 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 9406 if (Diagnose) 9407 S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init) 9408 << FI; 9409 return false; 9410 } 9411 9412 // Objective C ARC 4.3.5: 9413 // [...] nontrivally ownership-qualified types are [...] not trivially 9414 // default constructible, copy constructible, move constructible, copy 9415 // assignable, move assignable, or destructible [...] 9416 if (FieldType.hasNonTrivialObjCLifetime()) { 9417 if (Diagnose) 9418 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 9419 << RD << FieldType.getObjCLifetime(); 9420 return false; 9421 } 9422 9423 bool ConstRHS = ConstArg && !FI->isMutable(); 9424 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 9425 CSM, TSK_Field, TAH, Diagnose)) 9426 return false; 9427 } 9428 9429 return true; 9430 } 9431 9432 /// Diagnose why the specified class does not have a trivial special member of 9433 /// the given kind. 9434 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 9435 QualType Ty = Context.getRecordType(RD); 9436 9437 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 9438 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 9439 TSK_CompleteObject, TAH_IgnoreTrivialABI, 9440 /*Diagnose*/true); 9441 } 9442 9443 /// Determine whether a defaulted or deleted special member function is trivial, 9444 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 9445 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 9446 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 9447 TrivialABIHandling TAH, bool Diagnose) { 9448 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 9449 9450 CXXRecordDecl *RD = MD->getParent(); 9451 9452 bool ConstArg = false; 9453 9454 // C++11 [class.copy]p12, p25: [DR1593] 9455 // A [special member] is trivial if [...] its parameter-type-list is 9456 // equivalent to the parameter-type-list of an implicit declaration [...] 9457 switch (CSM) { 9458 case CXXDefaultConstructor: 9459 case CXXDestructor: 9460 // Trivial default constructors and destructors cannot have parameters. 9461 break; 9462 9463 case CXXCopyConstructor: 9464 case CXXCopyAssignment: { 9465 // Trivial copy operations always have const, non-volatile parameter types. 9466 ConstArg = true; 9467 const ParmVarDecl *Param0 = MD->getParamDecl(0); 9468 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 9469 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 9470 if (Diagnose) 9471 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 9472 << Param0->getSourceRange() << Param0->getType() 9473 << Context.getLValueReferenceType( 9474 Context.getRecordType(RD).withConst()); 9475 return false; 9476 } 9477 break; 9478 } 9479 9480 case CXXMoveConstructor: 9481 case CXXMoveAssignment: { 9482 // Trivial move operations always have non-cv-qualified parameters. 9483 const ParmVarDecl *Param0 = MD->getParamDecl(0); 9484 const RValueReferenceType *RT = 9485 Param0->getType()->getAs<RValueReferenceType>(); 9486 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 9487 if (Diagnose) 9488 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 9489 << Param0->getSourceRange() << Param0->getType() 9490 << Context.getRValueReferenceType(Context.getRecordType(RD)); 9491 return false; 9492 } 9493 break; 9494 } 9495 9496 case CXXInvalid: 9497 llvm_unreachable("not a special member"); 9498 } 9499 9500 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 9501 if (Diagnose) 9502 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 9503 diag::note_nontrivial_default_arg) 9504 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 9505 return false; 9506 } 9507 if (MD->isVariadic()) { 9508 if (Diagnose) 9509 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 9510 return false; 9511 } 9512 9513 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 9514 // A copy/move [constructor or assignment operator] is trivial if 9515 // -- the [member] selected to copy/move each direct base class subobject 9516 // is trivial 9517 // 9518 // C++11 [class.copy]p12, C++11 [class.copy]p25: 9519 // A [default constructor or destructor] is trivial if 9520 // -- all the direct base classes have trivial [default constructors or 9521 // destructors] 9522 for (const auto &BI : RD->bases()) 9523 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(), 9524 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose)) 9525 return false; 9526 9527 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 9528 // A copy/move [constructor or assignment operator] for a class X is 9529 // trivial if 9530 // -- for each non-static data member of X that is of class type (or array 9531 // thereof), the constructor selected to copy/move that member is 9532 // trivial 9533 // 9534 // C++11 [class.copy]p12, C++11 [class.copy]p25: 9535 // A [default constructor or destructor] is trivial if 9536 // -- for all of the non-static data members of its class that are of class 9537 // type (or array thereof), each such class has a trivial [default 9538 // constructor or destructor] 9539 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose)) 9540 return false; 9541 9542 // C++11 [class.dtor]p5: 9543 // A destructor is trivial if [...] 9544 // -- the destructor is not virtual 9545 if (CSM == CXXDestructor && MD->isVirtual()) { 9546 if (Diagnose) 9547 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 9548 return false; 9549 } 9550 9551 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 9552 // A [special member] for class X is trivial if [...] 9553 // -- class X has no virtual functions and no virtual base classes 9554 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 9555 if (!Diagnose) 9556 return false; 9557 9558 if (RD->getNumVBases()) { 9559 // Check for virtual bases. We already know that the corresponding 9560 // member in all bases is trivial, so vbases must all be direct. 9561 CXXBaseSpecifier &BS = *RD->vbases_begin(); 9562 assert(BS.isVirtual()); 9563 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1; 9564 return false; 9565 } 9566 9567 // Must have a virtual method. 9568 for (const auto *MI : RD->methods()) { 9569 if (MI->isVirtual()) { 9570 SourceLocation MLoc = MI->getBeginLoc(); 9571 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 9572 return false; 9573 } 9574 } 9575 9576 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 9577 } 9578 9579 // Looks like it's trivial! 9580 return true; 9581 } 9582 9583 namespace { 9584 struct FindHiddenVirtualMethod { 9585 Sema *S; 9586 CXXMethodDecl *Method; 9587 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 9588 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 9589 9590 private: 9591 /// Check whether any most overridden method from MD in Methods 9592 static bool CheckMostOverridenMethods( 9593 const CXXMethodDecl *MD, 9594 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) { 9595 if (MD->size_overridden_methods() == 0) 9596 return Methods.count(MD->getCanonicalDecl()); 9597 for (const CXXMethodDecl *O : MD->overridden_methods()) 9598 if (CheckMostOverridenMethods(O, Methods)) 9599 return true; 9600 return false; 9601 } 9602 9603 public: 9604 /// Member lookup function that determines whether a given C++ 9605 /// method overloads virtual methods in a base class without overriding any, 9606 /// to be used with CXXRecordDecl::lookupInBases(). 9607 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 9608 RecordDecl *BaseRecord = 9609 Specifier->getType()->castAs<RecordType>()->getDecl(); 9610 9611 DeclarationName Name = Method->getDeclName(); 9612 assert(Name.getNameKind() == DeclarationName::Identifier); 9613 9614 bool foundSameNameMethod = false; 9615 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 9616 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 9617 Path.Decls = Path.Decls.slice(1)) { 9618 NamedDecl *D = Path.Decls.front(); 9619 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 9620 MD = MD->getCanonicalDecl(); 9621 foundSameNameMethod = true; 9622 // Interested only in hidden virtual methods. 9623 if (!MD->isVirtual()) 9624 continue; 9625 // If the method we are checking overrides a method from its base 9626 // don't warn about the other overloaded methods. Clang deviates from 9627 // GCC by only diagnosing overloads of inherited virtual functions that 9628 // do not override any other virtual functions in the base. GCC's 9629 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 9630 // function from a base class. These cases may be better served by a 9631 // warning (not specific to virtual functions) on call sites when the 9632 // call would select a different function from the base class, were it 9633 // visible. 9634 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 9635 if (!S->IsOverload(Method, MD, false)) 9636 return true; 9637 // Collect the overload only if its hidden. 9638 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods)) 9639 overloadedMethods.push_back(MD); 9640 } 9641 } 9642 9643 if (foundSameNameMethod) 9644 OverloadedMethods.append(overloadedMethods.begin(), 9645 overloadedMethods.end()); 9646 return foundSameNameMethod; 9647 } 9648 }; 9649 } // end anonymous namespace 9650 9651 /// Add the most overriden methods from MD to Methods 9652 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 9653 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 9654 if (MD->size_overridden_methods() == 0) 9655 Methods.insert(MD->getCanonicalDecl()); 9656 else 9657 for (const CXXMethodDecl *O : MD->overridden_methods()) 9658 AddMostOverridenMethods(O, Methods); 9659 } 9660 9661 /// Check if a method overloads virtual methods in a base class without 9662 /// overriding any. 9663 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 9664 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 9665 if (!MD->getDeclName().isIdentifier()) 9666 return; 9667 9668 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 9669 /*bool RecordPaths=*/false, 9670 /*bool DetectVirtual=*/false); 9671 FindHiddenVirtualMethod FHVM; 9672 FHVM.Method = MD; 9673 FHVM.S = this; 9674 9675 // Keep the base methods that were overridden or introduced in the subclass 9676 // by 'using' in a set. A base method not in this set is hidden. 9677 CXXRecordDecl *DC = MD->getParent(); 9678 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 9679 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 9680 NamedDecl *ND = *I; 9681 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 9682 ND = shad->getTargetDecl(); 9683 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 9684 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods); 9685 } 9686 9687 if (DC->lookupInBases(FHVM, Paths)) 9688 OverloadedMethods = FHVM.OverloadedMethods; 9689 } 9690 9691 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 9692 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 9693 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 9694 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 9695 PartialDiagnostic PD = PDiag( 9696 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 9697 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 9698 Diag(overloadedMD->getLocation(), PD); 9699 } 9700 } 9701 9702 /// Diagnose methods which overload virtual methods in a base class 9703 /// without overriding any. 9704 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 9705 if (MD->isInvalidDecl()) 9706 return; 9707 9708 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 9709 return; 9710 9711 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 9712 FindHiddenVirtualMethods(MD, OverloadedMethods); 9713 if (!OverloadedMethods.empty()) { 9714 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 9715 << MD << (OverloadedMethods.size() > 1); 9716 9717 NoteHiddenVirtualMethods(MD, OverloadedMethods); 9718 } 9719 } 9720 9721 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) { 9722 auto PrintDiagAndRemoveAttr = [&](unsigned N) { 9723 // No diagnostics if this is a template instantiation. 9724 if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) { 9725 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), 9726 diag::ext_cannot_use_trivial_abi) << &RD; 9727 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), 9728 diag::note_cannot_use_trivial_abi_reason) << &RD << N; 9729 } 9730 RD.dropAttr<TrivialABIAttr>(); 9731 }; 9732 9733 // Ill-formed if the copy and move constructors are deleted. 9734 auto HasNonDeletedCopyOrMoveConstructor = [&]() { 9735 // If the type is dependent, then assume it might have 9736 // implicit copy or move ctor because we won't know yet at this point. 9737 if (RD.isDependentType()) 9738 return true; 9739 if (RD.needsImplicitCopyConstructor() && 9740 !RD.defaultedCopyConstructorIsDeleted()) 9741 return true; 9742 if (RD.needsImplicitMoveConstructor() && 9743 !RD.defaultedMoveConstructorIsDeleted()) 9744 return true; 9745 for (const CXXConstructorDecl *CD : RD.ctors()) 9746 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted()) 9747 return true; 9748 return false; 9749 }; 9750 9751 if (!HasNonDeletedCopyOrMoveConstructor()) { 9752 PrintDiagAndRemoveAttr(0); 9753 return; 9754 } 9755 9756 // Ill-formed if the struct has virtual functions. 9757 if (RD.isPolymorphic()) { 9758 PrintDiagAndRemoveAttr(1); 9759 return; 9760 } 9761 9762 for (const auto &B : RD.bases()) { 9763 // Ill-formed if the base class is non-trivial for the purpose of calls or a 9764 // virtual base. 9765 if (!B.getType()->isDependentType() && 9766 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) { 9767 PrintDiagAndRemoveAttr(2); 9768 return; 9769 } 9770 9771 if (B.isVirtual()) { 9772 PrintDiagAndRemoveAttr(3); 9773 return; 9774 } 9775 } 9776 9777 for (const auto *FD : RD.fields()) { 9778 // Ill-formed if the field is an ObjectiveC pointer or of a type that is 9779 // non-trivial for the purpose of calls. 9780 QualType FT = FD->getType(); 9781 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) { 9782 PrintDiagAndRemoveAttr(4); 9783 return; 9784 } 9785 9786 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>()) 9787 if (!RT->isDependentType() && 9788 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) { 9789 PrintDiagAndRemoveAttr(5); 9790 return; 9791 } 9792 } 9793 } 9794 9795 void Sema::ActOnFinishCXXMemberSpecification( 9796 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, 9797 SourceLocation RBrac, const ParsedAttributesView &AttrList) { 9798 if (!TagDecl) 9799 return; 9800 9801 AdjustDeclIfTemplate(TagDecl); 9802 9803 for (const ParsedAttr &AL : AttrList) { 9804 if (AL.getKind() != ParsedAttr::AT_Visibility) 9805 continue; 9806 AL.setInvalid(); 9807 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL; 9808 } 9809 9810 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 9811 // strict aliasing violation! 9812 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 9813 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 9814 9815 CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl)); 9816 } 9817 9818 /// Find the equality comparison functions that should be implicitly declared 9819 /// in a given class definition, per C++2a [class.compare.default]p3. 9820 static void findImplicitlyDeclaredEqualityComparisons( 9821 ASTContext &Ctx, CXXRecordDecl *RD, 9822 llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) { 9823 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual); 9824 if (!RD->lookup(EqEq).empty()) 9825 // Member operator== explicitly declared: no implicit operator==s. 9826 return; 9827 9828 // Traverse friends looking for an '==' or a '<=>'. 9829 for (FriendDecl *Friend : RD->friends()) { 9830 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl()); 9831 if (!FD) continue; 9832 9833 if (FD->getOverloadedOperator() == OO_EqualEqual) { 9834 // Friend operator== explicitly declared: no implicit operator==s. 9835 Spaceships.clear(); 9836 return; 9837 } 9838 9839 if (FD->getOverloadedOperator() == OO_Spaceship && 9840 FD->isExplicitlyDefaulted()) 9841 Spaceships.push_back(FD); 9842 } 9843 9844 // Look for members named 'operator<=>'. 9845 DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship); 9846 for (NamedDecl *ND : RD->lookup(Cmp)) { 9847 // Note that we could find a non-function here (either a function template 9848 // or a using-declaration). Neither case results in an implicit 9849 // 'operator=='. 9850 if (auto *FD = dyn_cast<FunctionDecl>(ND)) 9851 if (FD->isExplicitlyDefaulted()) 9852 Spaceships.push_back(FD); 9853 } 9854 } 9855 9856 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 9857 /// special functions, such as the default constructor, copy 9858 /// constructor, or destructor, to the given C++ class (C++ 9859 /// [special]p1). This routine can only be executed just before the 9860 /// definition of the class is complete. 9861 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 9862 // Don't add implicit special members to templated classes. 9863 // FIXME: This means unqualified lookups for 'operator=' within a class 9864 // template don't work properly. 9865 if (!ClassDecl->isDependentType()) { 9866 if (ClassDecl->needsImplicitDefaultConstructor()) { 9867 ++getASTContext().NumImplicitDefaultConstructors; 9868 9869 if (ClassDecl->hasInheritedConstructor()) 9870 DeclareImplicitDefaultConstructor(ClassDecl); 9871 } 9872 9873 if (ClassDecl->needsImplicitCopyConstructor()) { 9874 ++getASTContext().NumImplicitCopyConstructors; 9875 9876 // If the properties or semantics of the copy constructor couldn't be 9877 // determined while the class was being declared, force a declaration 9878 // of it now. 9879 if (ClassDecl->needsOverloadResolutionForCopyConstructor() || 9880 ClassDecl->hasInheritedConstructor()) 9881 DeclareImplicitCopyConstructor(ClassDecl); 9882 // For the MS ABI we need to know whether the copy ctor is deleted. A 9883 // prerequisite for deleting the implicit copy ctor is that the class has 9884 // a move ctor or move assignment that is either user-declared or whose 9885 // semantics are inherited from a subobject. FIXME: We should provide a 9886 // more direct way for CodeGen to ask whether the constructor was deleted. 9887 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 9888 (ClassDecl->hasUserDeclaredMoveConstructor() || 9889 ClassDecl->needsOverloadResolutionForMoveConstructor() || 9890 ClassDecl->hasUserDeclaredMoveAssignment() || 9891 ClassDecl->needsOverloadResolutionForMoveAssignment())) 9892 DeclareImplicitCopyConstructor(ClassDecl); 9893 } 9894 9895 if (getLangOpts().CPlusPlus11 && 9896 ClassDecl->needsImplicitMoveConstructor()) { 9897 ++getASTContext().NumImplicitMoveConstructors; 9898 9899 if (ClassDecl->needsOverloadResolutionForMoveConstructor() || 9900 ClassDecl->hasInheritedConstructor()) 9901 DeclareImplicitMoveConstructor(ClassDecl); 9902 } 9903 9904 if (ClassDecl->needsImplicitCopyAssignment()) { 9905 ++getASTContext().NumImplicitCopyAssignmentOperators; 9906 9907 // If we have a dynamic class, then the copy assignment operator may be 9908 // virtual, so we have to declare it immediately. This ensures that, e.g., 9909 // it shows up in the right place in the vtable and that we diagnose 9910 // problems with the implicit exception specification. 9911 if (ClassDecl->isDynamicClass() || 9912 ClassDecl->needsOverloadResolutionForCopyAssignment() || 9913 ClassDecl->hasInheritedAssignment()) 9914 DeclareImplicitCopyAssignment(ClassDecl); 9915 } 9916 9917 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 9918 ++getASTContext().NumImplicitMoveAssignmentOperators; 9919 9920 // Likewise for the move assignment operator. 9921 if (ClassDecl->isDynamicClass() || 9922 ClassDecl->needsOverloadResolutionForMoveAssignment() || 9923 ClassDecl->hasInheritedAssignment()) 9924 DeclareImplicitMoveAssignment(ClassDecl); 9925 } 9926 9927 if (ClassDecl->needsImplicitDestructor()) { 9928 ++getASTContext().NumImplicitDestructors; 9929 9930 // If we have a dynamic class, then the destructor may be virtual, so we 9931 // have to declare the destructor immediately. This ensures that, e.g., it 9932 // shows up in the right place in the vtable and that we diagnose problems 9933 // with the implicit exception specification. 9934 if (ClassDecl->isDynamicClass() || 9935 ClassDecl->needsOverloadResolutionForDestructor()) 9936 DeclareImplicitDestructor(ClassDecl); 9937 } 9938 } 9939 9940 // C++2a [class.compare.default]p3: 9941 // If the member-specification does not explicitly declare any member or 9942 // friend named operator==, an == operator function is declared implicitly 9943 // for each defaulted three-way comparison operator function defined in 9944 // the member-specification 9945 // FIXME: Consider doing this lazily. 9946 // We do this during the initial parse for a class template, not during 9947 // instantiation, so that we can handle unqualified lookups for 'operator==' 9948 // when parsing the template. 9949 if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) { 9950 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships; 9951 findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl, 9952 DefaultedSpaceships); 9953 for (auto *FD : DefaultedSpaceships) 9954 DeclareImplicitEqualityComparison(ClassDecl, FD); 9955 } 9956 } 9957 9958 unsigned 9959 Sema::ActOnReenterTemplateScope(Decl *D, 9960 llvm::function_ref<Scope *()> EnterScope) { 9961 if (!D) 9962 return 0; 9963 AdjustDeclIfTemplate(D); 9964 9965 // In order to get name lookup right, reenter template scopes in order from 9966 // outermost to innermost. 9967 SmallVector<TemplateParameterList *, 4> ParameterLists; 9968 DeclContext *LookupDC = dyn_cast<DeclContext>(D); 9969 9970 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 9971 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 9972 ParameterLists.push_back(DD->getTemplateParameterList(i)); 9973 9974 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 9975 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 9976 ParameterLists.push_back(FTD->getTemplateParameters()); 9977 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 9978 LookupDC = VD->getDeclContext(); 9979 9980 if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate()) 9981 ParameterLists.push_back(VTD->getTemplateParameters()); 9982 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D)) 9983 ParameterLists.push_back(PSD->getTemplateParameters()); 9984 } 9985 } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 9986 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 9987 ParameterLists.push_back(TD->getTemplateParameterList(i)); 9988 9989 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 9990 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 9991 ParameterLists.push_back(CTD->getTemplateParameters()); 9992 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 9993 ParameterLists.push_back(PSD->getTemplateParameters()); 9994 } 9995 } 9996 // FIXME: Alias declarations and concepts. 9997 9998 unsigned Count = 0; 9999 Scope *InnermostTemplateScope = nullptr; 10000 for (TemplateParameterList *Params : ParameterLists) { 10001 // Ignore explicit specializations; they don't contribute to the template 10002 // depth. 10003 if (Params->size() == 0) 10004 continue; 10005 10006 InnermostTemplateScope = EnterScope(); 10007 for (NamedDecl *Param : *Params) { 10008 if (Param->getDeclName()) { 10009 InnermostTemplateScope->AddDecl(Param); 10010 IdResolver.AddDecl(Param); 10011 } 10012 } 10013 ++Count; 10014 } 10015 10016 // Associate the new template scopes with the corresponding entities. 10017 if (InnermostTemplateScope) { 10018 assert(LookupDC && "no enclosing DeclContext for template lookup"); 10019 EnterTemplatedContext(InnermostTemplateScope, LookupDC); 10020 } 10021 10022 return Count; 10023 } 10024 10025 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 10026 if (!RecordD) return; 10027 AdjustDeclIfTemplate(RecordD); 10028 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 10029 PushDeclContext(S, Record); 10030 } 10031 10032 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 10033 if (!RecordD) return; 10034 PopDeclContext(); 10035 } 10036 10037 /// This is used to implement the constant expression evaluation part of the 10038 /// attribute enable_if extension. There is nothing in standard C++ which would 10039 /// require reentering parameters. 10040 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 10041 if (!Param) 10042 return; 10043 10044 S->AddDecl(Param); 10045 if (Param->getDeclName()) 10046 IdResolver.AddDecl(Param); 10047 } 10048 10049 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 10050 /// parsing a top-level (non-nested) C++ class, and we are now 10051 /// parsing those parts of the given Method declaration that could 10052 /// not be parsed earlier (C++ [class.mem]p2), such as default 10053 /// arguments. This action should enter the scope of the given 10054 /// Method declaration as if we had just parsed the qualified method 10055 /// name. However, it should not bring the parameters into scope; 10056 /// that will be performed by ActOnDelayedCXXMethodParameter. 10057 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 10058 } 10059 10060 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 10061 /// C++ method declaration. We're (re-)introducing the given 10062 /// function parameter into scope for use in parsing later parts of 10063 /// the method declaration. For example, we could see an 10064 /// ActOnParamDefaultArgument event for this parameter. 10065 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 10066 if (!ParamD) 10067 return; 10068 10069 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 10070 10071 S->AddDecl(Param); 10072 if (Param->getDeclName()) 10073 IdResolver.AddDecl(Param); 10074 } 10075 10076 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 10077 /// processing the delayed method declaration for Method. The method 10078 /// declaration is now considered finished. There may be a separate 10079 /// ActOnStartOfFunctionDef action later (not necessarily 10080 /// immediately!) for this method, if it was also defined inside the 10081 /// class body. 10082 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 10083 if (!MethodD) 10084 return; 10085 10086 AdjustDeclIfTemplate(MethodD); 10087 10088 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 10089 10090 // Now that we have our default arguments, check the constructor 10091 // again. It could produce additional diagnostics or affect whether 10092 // the class has implicitly-declared destructors, among other 10093 // things. 10094 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 10095 CheckConstructor(Constructor); 10096 10097 // Check the default arguments, which we may have added. 10098 if (!Method->isInvalidDecl()) 10099 CheckCXXDefaultArguments(Method); 10100 } 10101 10102 // Emit the given diagnostic for each non-address-space qualifier. 10103 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator. 10104 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) { 10105 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10106 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) { 10107 bool DiagOccured = false; 10108 FTI.MethodQualifiers->forEachQualifier( 10109 [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName, 10110 SourceLocation SL) { 10111 // This diagnostic should be emitted on any qualifier except an addr 10112 // space qualifier. However, forEachQualifier currently doesn't visit 10113 // addr space qualifiers, so there's no way to write this condition 10114 // right now; we just diagnose on everything. 10115 S.Diag(SL, DiagID) << QualName << SourceRange(SL); 10116 DiagOccured = true; 10117 }); 10118 if (DiagOccured) 10119 D.setInvalidType(); 10120 } 10121 } 10122 10123 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 10124 /// the well-formedness of the constructor declarator @p D with type @p 10125 /// R. If there are any errors in the declarator, this routine will 10126 /// emit diagnostics and set the invalid bit to true. In any case, the type 10127 /// will be updated to reflect a well-formed type for the constructor and 10128 /// returned. 10129 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 10130 StorageClass &SC) { 10131 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 10132 10133 // C++ [class.ctor]p3: 10134 // A constructor shall not be virtual (10.3) or static (9.4). A 10135 // constructor can be invoked for a const, volatile or const 10136 // volatile object. A constructor shall not be declared const, 10137 // volatile, or const volatile (9.3.2). 10138 if (isVirtual) { 10139 if (!D.isInvalidType()) 10140 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 10141 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 10142 << SourceRange(D.getIdentifierLoc()); 10143 D.setInvalidType(); 10144 } 10145 if (SC == SC_Static) { 10146 if (!D.isInvalidType()) 10147 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 10148 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10149 << SourceRange(D.getIdentifierLoc()); 10150 D.setInvalidType(); 10151 SC = SC_None; 10152 } 10153 10154 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 10155 diagnoseIgnoredQualifiers( 10156 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 10157 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 10158 D.getDeclSpec().getRestrictSpecLoc(), 10159 D.getDeclSpec().getAtomicSpecLoc()); 10160 D.setInvalidType(); 10161 } 10162 10163 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor); 10164 10165 // C++0x [class.ctor]p4: 10166 // A constructor shall not be declared with a ref-qualifier. 10167 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10168 if (FTI.hasRefQualifier()) { 10169 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 10170 << FTI.RefQualifierIsLValueRef 10171 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 10172 D.setInvalidType(); 10173 } 10174 10175 // Rebuild the function type "R" without any type qualifiers (in 10176 // case any of the errors above fired) and with "void" as the 10177 // return type, since constructors don't have return types. 10178 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>(); 10179 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 10180 return R; 10181 10182 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 10183 EPI.TypeQuals = Qualifiers(); 10184 EPI.RefQualifier = RQ_None; 10185 10186 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 10187 } 10188 10189 /// CheckConstructor - Checks a fully-formed constructor for 10190 /// well-formedness, issuing any diagnostics required. Returns true if 10191 /// the constructor declarator is invalid. 10192 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 10193 CXXRecordDecl *ClassDecl 10194 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 10195 if (!ClassDecl) 10196 return Constructor->setInvalidDecl(); 10197 10198 // C++ [class.copy]p3: 10199 // A declaration of a constructor for a class X is ill-formed if 10200 // its first parameter is of type (optionally cv-qualified) X and 10201 // either there are no other parameters or else all other 10202 // parameters have default arguments. 10203 if (!Constructor->isInvalidDecl() && 10204 Constructor->hasOneParamOrDefaultArgs() && 10205 Constructor->getTemplateSpecializationKind() != 10206 TSK_ImplicitInstantiation) { 10207 QualType ParamType = Constructor->getParamDecl(0)->getType(); 10208 QualType ClassTy = Context.getTagDeclType(ClassDecl); 10209 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 10210 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 10211 const char *ConstRef 10212 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 10213 : " const &"; 10214 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 10215 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 10216 10217 // FIXME: Rather that making the constructor invalid, we should endeavor 10218 // to fix the type. 10219 Constructor->setInvalidDecl(); 10220 } 10221 } 10222 } 10223 10224 /// CheckDestructor - Checks a fully-formed destructor definition for 10225 /// well-formedness, issuing any diagnostics required. Returns true 10226 /// on error. 10227 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 10228 CXXRecordDecl *RD = Destructor->getParent(); 10229 10230 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 10231 SourceLocation Loc; 10232 10233 if (!Destructor->isImplicit()) 10234 Loc = Destructor->getLocation(); 10235 else 10236 Loc = RD->getLocation(); 10237 10238 // If we have a virtual destructor, look up the deallocation function 10239 if (FunctionDecl *OperatorDelete = 10240 FindDeallocationFunctionForDestructor(Loc, RD)) { 10241 Expr *ThisArg = nullptr; 10242 10243 // If the notional 'delete this' expression requires a non-trivial 10244 // conversion from 'this' to the type of a destroying operator delete's 10245 // first parameter, perform that conversion now. 10246 if (OperatorDelete->isDestroyingOperatorDelete()) { 10247 QualType ParamType = OperatorDelete->getParamDecl(0)->getType(); 10248 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) { 10249 // C++ [class.dtor]p13: 10250 // ... as if for the expression 'delete this' appearing in a 10251 // non-virtual destructor of the destructor's class. 10252 ContextRAII SwitchContext(*this, Destructor); 10253 ExprResult This = 10254 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation()); 10255 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?"); 10256 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing); 10257 if (This.isInvalid()) { 10258 // FIXME: Register this as a context note so that it comes out 10259 // in the right order. 10260 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here); 10261 return true; 10262 } 10263 ThisArg = This.get(); 10264 } 10265 } 10266 10267 DiagnoseUseOfDecl(OperatorDelete, Loc); 10268 MarkFunctionReferenced(Loc, OperatorDelete); 10269 Destructor->setOperatorDelete(OperatorDelete, ThisArg); 10270 } 10271 } 10272 10273 return false; 10274 } 10275 10276 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 10277 /// the well-formednes of the destructor declarator @p D with type @p 10278 /// R. If there are any errors in the declarator, this routine will 10279 /// emit diagnostics and set the declarator to invalid. Even if this happens, 10280 /// will be updated to reflect a well-formed type for the destructor and 10281 /// returned. 10282 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 10283 StorageClass& SC) { 10284 // C++ [class.dtor]p1: 10285 // [...] A typedef-name that names a class is a class-name 10286 // (7.1.3); however, a typedef-name that names a class shall not 10287 // be used as the identifier in the declarator for a destructor 10288 // declaration. 10289 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 10290 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 10291 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name) 10292 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 10293 else if (const TemplateSpecializationType *TST = 10294 DeclaratorType->getAs<TemplateSpecializationType>()) 10295 if (TST->isTypeAlias()) 10296 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name) 10297 << DeclaratorType << 1; 10298 10299 // C++ [class.dtor]p2: 10300 // A destructor is used to destroy objects of its class type. A 10301 // destructor takes no parameters, and no return type can be 10302 // specified for it (not even void). The address of a destructor 10303 // shall not be taken. A destructor shall not be static. A 10304 // destructor can be invoked for a const, volatile or const 10305 // volatile object. A destructor shall not be declared const, 10306 // volatile or const volatile (9.3.2). 10307 if (SC == SC_Static) { 10308 if (!D.isInvalidType()) 10309 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 10310 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10311 << SourceRange(D.getIdentifierLoc()) 10312 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 10313 10314 SC = SC_None; 10315 } 10316 if (!D.isInvalidType()) { 10317 // Destructors don't have return types, but the parser will 10318 // happily parse something like: 10319 // 10320 // class X { 10321 // float ~X(); 10322 // }; 10323 // 10324 // The return type will be eliminated later. 10325 if (D.getDeclSpec().hasTypeSpecifier()) 10326 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 10327 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 10328 << SourceRange(D.getIdentifierLoc()); 10329 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 10330 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 10331 SourceLocation(), 10332 D.getDeclSpec().getConstSpecLoc(), 10333 D.getDeclSpec().getVolatileSpecLoc(), 10334 D.getDeclSpec().getRestrictSpecLoc(), 10335 D.getDeclSpec().getAtomicSpecLoc()); 10336 D.setInvalidType(); 10337 } 10338 } 10339 10340 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor); 10341 10342 // C++0x [class.dtor]p2: 10343 // A destructor shall not be declared with a ref-qualifier. 10344 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10345 if (FTI.hasRefQualifier()) { 10346 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 10347 << FTI.RefQualifierIsLValueRef 10348 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 10349 D.setInvalidType(); 10350 } 10351 10352 // Make sure we don't have any parameters. 10353 if (FTIHasNonVoidParameters(FTI)) { 10354 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 10355 10356 // Delete the parameters. 10357 FTI.freeParams(); 10358 D.setInvalidType(); 10359 } 10360 10361 // Make sure the destructor isn't variadic. 10362 if (FTI.isVariadic) { 10363 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 10364 D.setInvalidType(); 10365 } 10366 10367 // Rebuild the function type "R" without any type qualifiers or 10368 // parameters (in case any of the errors above fired) and with 10369 // "void" as the return type, since destructors don't have return 10370 // types. 10371 if (!D.isInvalidType()) 10372 return R; 10373 10374 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>(); 10375 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 10376 EPI.Variadic = false; 10377 EPI.TypeQuals = Qualifiers(); 10378 EPI.RefQualifier = RQ_None; 10379 return Context.getFunctionType(Context.VoidTy, None, EPI); 10380 } 10381 10382 static void extendLeft(SourceRange &R, SourceRange Before) { 10383 if (Before.isInvalid()) 10384 return; 10385 R.setBegin(Before.getBegin()); 10386 if (R.getEnd().isInvalid()) 10387 R.setEnd(Before.getEnd()); 10388 } 10389 10390 static void extendRight(SourceRange &R, SourceRange After) { 10391 if (After.isInvalid()) 10392 return; 10393 if (R.getBegin().isInvalid()) 10394 R.setBegin(After.getBegin()); 10395 R.setEnd(After.getEnd()); 10396 } 10397 10398 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 10399 /// well-formednes of the conversion function declarator @p D with 10400 /// type @p R. If there are any errors in the declarator, this routine 10401 /// will emit diagnostics and return true. Otherwise, it will return 10402 /// false. Either way, the type @p R will be updated to reflect a 10403 /// well-formed type for the conversion operator. 10404 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 10405 StorageClass& SC) { 10406 // C++ [class.conv.fct]p1: 10407 // Neither parameter types nor return type can be specified. The 10408 // type of a conversion function (8.3.5) is "function taking no 10409 // parameter returning conversion-type-id." 10410 if (SC == SC_Static) { 10411 if (!D.isInvalidType()) 10412 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 10413 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10414 << D.getName().getSourceRange(); 10415 D.setInvalidType(); 10416 SC = SC_None; 10417 } 10418 10419 TypeSourceInfo *ConvTSI = nullptr; 10420 QualType ConvType = 10421 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); 10422 10423 const DeclSpec &DS = D.getDeclSpec(); 10424 if (DS.hasTypeSpecifier() && !D.isInvalidType()) { 10425 // Conversion functions don't have return types, but the parser will 10426 // happily parse something like: 10427 // 10428 // class X { 10429 // float operator bool(); 10430 // }; 10431 // 10432 // The return type will be changed later anyway. 10433 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 10434 << SourceRange(DS.getTypeSpecTypeLoc()) 10435 << SourceRange(D.getIdentifierLoc()); 10436 D.setInvalidType(); 10437 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) { 10438 // It's also plausible that the user writes type qualifiers in the wrong 10439 // place, such as: 10440 // struct S { const operator int(); }; 10441 // FIXME: we could provide a fixit to move the qualifiers onto the 10442 // conversion type. 10443 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 10444 << SourceRange(D.getIdentifierLoc()) << 0; 10445 D.setInvalidType(); 10446 } 10447 10448 const auto *Proto = R->castAs<FunctionProtoType>(); 10449 10450 // Make sure we don't have any parameters. 10451 if (Proto->getNumParams() > 0) { 10452 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 10453 10454 // Delete the parameters. 10455 D.getFunctionTypeInfo().freeParams(); 10456 D.setInvalidType(); 10457 } else if (Proto->isVariadic()) { 10458 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 10459 D.setInvalidType(); 10460 } 10461 10462 // Diagnose "&operator bool()" and other such nonsense. This 10463 // is actually a gcc extension which we don't support. 10464 if (Proto->getReturnType() != ConvType) { 10465 bool NeedsTypedef = false; 10466 SourceRange Before, After; 10467 10468 // Walk the chunks and extract information on them for our diagnostic. 10469 bool PastFunctionChunk = false; 10470 for (auto &Chunk : D.type_objects()) { 10471 switch (Chunk.Kind) { 10472 case DeclaratorChunk::Function: 10473 if (!PastFunctionChunk) { 10474 if (Chunk.Fun.HasTrailingReturnType) { 10475 TypeSourceInfo *TRT = nullptr; 10476 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); 10477 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); 10478 } 10479 PastFunctionChunk = true; 10480 break; 10481 } 10482 LLVM_FALLTHROUGH; 10483 case DeclaratorChunk::Array: 10484 NeedsTypedef = true; 10485 extendRight(After, Chunk.getSourceRange()); 10486 break; 10487 10488 case DeclaratorChunk::Pointer: 10489 case DeclaratorChunk::BlockPointer: 10490 case DeclaratorChunk::Reference: 10491 case DeclaratorChunk::MemberPointer: 10492 case DeclaratorChunk::Pipe: 10493 extendLeft(Before, Chunk.getSourceRange()); 10494 break; 10495 10496 case DeclaratorChunk::Paren: 10497 extendLeft(Before, Chunk.Loc); 10498 extendRight(After, Chunk.EndLoc); 10499 break; 10500 } 10501 } 10502 10503 SourceLocation Loc = Before.isValid() ? Before.getBegin() : 10504 After.isValid() ? After.getBegin() : 10505 D.getIdentifierLoc(); 10506 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); 10507 DB << Before << After; 10508 10509 if (!NeedsTypedef) { 10510 DB << /*don't need a typedef*/0; 10511 10512 // If we can provide a correct fix-it hint, do so. 10513 if (After.isInvalid() && ConvTSI) { 10514 SourceLocation InsertLoc = 10515 getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc()); 10516 DB << FixItHint::CreateInsertion(InsertLoc, " ") 10517 << FixItHint::CreateInsertionFromRange( 10518 InsertLoc, CharSourceRange::getTokenRange(Before)) 10519 << FixItHint::CreateRemoval(Before); 10520 } 10521 } else if (!Proto->getReturnType()->isDependentType()) { 10522 DB << /*typedef*/1 << Proto->getReturnType(); 10523 } else if (getLangOpts().CPlusPlus11) { 10524 DB << /*alias template*/2 << Proto->getReturnType(); 10525 } else { 10526 DB << /*might not be fixable*/3; 10527 } 10528 10529 // Recover by incorporating the other type chunks into the result type. 10530 // Note, this does *not* change the name of the function. This is compatible 10531 // with the GCC extension: 10532 // struct S { &operator int(); } s; 10533 // int &r = s.operator int(); // ok in GCC 10534 // S::operator int&() {} // error in GCC, function name is 'operator int'. 10535 ConvType = Proto->getReturnType(); 10536 } 10537 10538 // C++ [class.conv.fct]p4: 10539 // The conversion-type-id shall not represent a function type nor 10540 // an array type. 10541 if (ConvType->isArrayType()) { 10542 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 10543 ConvType = Context.getPointerType(ConvType); 10544 D.setInvalidType(); 10545 } else if (ConvType->isFunctionType()) { 10546 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 10547 ConvType = Context.getPointerType(ConvType); 10548 D.setInvalidType(); 10549 } 10550 10551 // Rebuild the function type "R" without any parameters (in case any 10552 // of the errors above fired) and with the conversion type as the 10553 // return type. 10554 if (D.isInvalidType()) 10555 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 10556 10557 // C++0x explicit conversion operators. 10558 if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20) 10559 Diag(DS.getExplicitSpecLoc(), 10560 getLangOpts().CPlusPlus11 10561 ? diag::warn_cxx98_compat_explicit_conversion_functions 10562 : diag::ext_explicit_conversion_functions) 10563 << SourceRange(DS.getExplicitSpecRange()); 10564 } 10565 10566 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 10567 /// the declaration of the given C++ conversion function. This routine 10568 /// is responsible for recording the conversion function in the C++ 10569 /// class, if possible. 10570 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 10571 assert(Conversion && "Expected to receive a conversion function declaration"); 10572 10573 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 10574 10575 // Make sure we aren't redeclaring the conversion function. 10576 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 10577 // C++ [class.conv.fct]p1: 10578 // [...] A conversion function is never used to convert a 10579 // (possibly cv-qualified) object to the (possibly cv-qualified) 10580 // same object type (or a reference to it), to a (possibly 10581 // cv-qualified) base class of that type (or a reference to it), 10582 // or to (possibly cv-qualified) void. 10583 QualType ClassType 10584 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 10585 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 10586 ConvType = ConvTypeRef->getPointeeType(); 10587 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 10588 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 10589 /* Suppress diagnostics for instantiations. */; 10590 else if (Conversion->size_overridden_methods() != 0) 10591 /* Suppress diagnostics for overriding virtual function in a base class. */; 10592 else if (ConvType->isRecordType()) { 10593 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 10594 if (ConvType == ClassType) 10595 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 10596 << ClassType; 10597 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType)) 10598 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 10599 << ClassType << ConvType; 10600 } else if (ConvType->isVoidType()) { 10601 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 10602 << ClassType << ConvType; 10603 } 10604 10605 if (FunctionTemplateDecl *ConversionTemplate 10606 = Conversion->getDescribedFunctionTemplate()) 10607 return ConversionTemplate; 10608 10609 return Conversion; 10610 } 10611 10612 namespace { 10613 /// Utility class to accumulate and print a diagnostic listing the invalid 10614 /// specifier(s) on a declaration. 10615 struct BadSpecifierDiagnoser { 10616 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID) 10617 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {} 10618 ~BadSpecifierDiagnoser() { 10619 Diagnostic << Specifiers; 10620 } 10621 10622 template<typename T> void check(SourceLocation SpecLoc, T Spec) { 10623 return check(SpecLoc, DeclSpec::getSpecifierName(Spec)); 10624 } 10625 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) { 10626 return check(SpecLoc, 10627 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy())); 10628 } 10629 void check(SourceLocation SpecLoc, const char *Spec) { 10630 if (SpecLoc.isInvalid()) return; 10631 Diagnostic << SourceRange(SpecLoc, SpecLoc); 10632 if (!Specifiers.empty()) Specifiers += " "; 10633 Specifiers += Spec; 10634 } 10635 10636 Sema &S; 10637 Sema::SemaDiagnosticBuilder Diagnostic; 10638 std::string Specifiers; 10639 }; 10640 } 10641 10642 /// Check the validity of a declarator that we parsed for a deduction-guide. 10643 /// These aren't actually declarators in the grammar, so we need to check that 10644 /// the user didn't specify any pieces that are not part of the deduction-guide 10645 /// grammar. 10646 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R, 10647 StorageClass &SC) { 10648 TemplateName GuidedTemplate = D.getName().TemplateName.get().get(); 10649 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl(); 10650 assert(GuidedTemplateDecl && "missing template decl for deduction guide"); 10651 10652 // C++ [temp.deduct.guide]p3: 10653 // A deduction-gide shall be declared in the same scope as the 10654 // corresponding class template. 10655 if (!CurContext->getRedeclContext()->Equals( 10656 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) { 10657 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope) 10658 << GuidedTemplateDecl; 10659 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here); 10660 } 10661 10662 auto &DS = D.getMutableDeclSpec(); 10663 // We leave 'friend' and 'virtual' to be rejected in the normal way. 10664 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() || 10665 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() || 10666 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) { 10667 BadSpecifierDiagnoser Diagnoser( 10668 *this, D.getIdentifierLoc(), 10669 diag::err_deduction_guide_invalid_specifier); 10670 10671 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec()); 10672 DS.ClearStorageClassSpecs(); 10673 SC = SC_None; 10674 10675 // 'explicit' is permitted. 10676 Diagnoser.check(DS.getInlineSpecLoc(), "inline"); 10677 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn"); 10678 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr"); 10679 DS.ClearConstexprSpec(); 10680 10681 Diagnoser.check(DS.getConstSpecLoc(), "const"); 10682 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict"); 10683 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile"); 10684 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic"); 10685 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned"); 10686 DS.ClearTypeQualifiers(); 10687 10688 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex()); 10689 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign()); 10690 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth()); 10691 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType()); 10692 DS.ClearTypeSpecType(); 10693 } 10694 10695 if (D.isInvalidType()) 10696 return; 10697 10698 // Check the declarator is simple enough. 10699 bool FoundFunction = false; 10700 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) { 10701 if (Chunk.Kind == DeclaratorChunk::Paren) 10702 continue; 10703 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) { 10704 Diag(D.getDeclSpec().getBeginLoc(), 10705 diag::err_deduction_guide_with_complex_decl) 10706 << D.getSourceRange(); 10707 break; 10708 } 10709 if (!Chunk.Fun.hasTrailingReturnType()) { 10710 Diag(D.getName().getBeginLoc(), 10711 diag::err_deduction_guide_no_trailing_return_type); 10712 break; 10713 } 10714 10715 // Check that the return type is written as a specialization of 10716 // the template specified as the deduction-guide's name. 10717 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType(); 10718 TypeSourceInfo *TSI = nullptr; 10719 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI); 10720 assert(TSI && "deduction guide has valid type but invalid return type?"); 10721 bool AcceptableReturnType = false; 10722 bool MightInstantiateToSpecialization = false; 10723 if (auto RetTST = 10724 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) { 10725 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName(); 10726 bool TemplateMatches = 10727 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate); 10728 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches) 10729 AcceptableReturnType = true; 10730 else { 10731 // This could still instantiate to the right type, unless we know it 10732 // names the wrong class template. 10733 auto *TD = SpecifiedName.getAsTemplateDecl(); 10734 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) && 10735 !TemplateMatches); 10736 } 10737 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) { 10738 MightInstantiateToSpecialization = true; 10739 } 10740 10741 if (!AcceptableReturnType) { 10742 Diag(TSI->getTypeLoc().getBeginLoc(), 10743 diag::err_deduction_guide_bad_trailing_return_type) 10744 << GuidedTemplate << TSI->getType() 10745 << MightInstantiateToSpecialization 10746 << TSI->getTypeLoc().getSourceRange(); 10747 } 10748 10749 // Keep going to check that we don't have any inner declarator pieces (we 10750 // could still have a function returning a pointer to a function). 10751 FoundFunction = true; 10752 } 10753 10754 if (D.isFunctionDefinition()) 10755 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function); 10756 } 10757 10758 //===----------------------------------------------------------------------===// 10759 // Namespace Handling 10760 //===----------------------------------------------------------------------===// 10761 10762 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is 10763 /// reopened. 10764 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 10765 SourceLocation Loc, 10766 IdentifierInfo *II, bool *IsInline, 10767 NamespaceDecl *PrevNS) { 10768 assert(*IsInline != PrevNS->isInline()); 10769 10770 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 10771 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 10772 // inline namespaces, with the intention of bringing names into namespace std. 10773 // 10774 // We support this just well enough to get that case working; this is not 10775 // sufficient to support reopening namespaces as inline in general. 10776 if (*IsInline && II && II->getName().startswith("__atomic") && 10777 S.getSourceManager().isInSystemHeader(Loc)) { 10778 // Mark all prior declarations of the namespace as inline. 10779 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 10780 NS = NS->getPreviousDecl()) 10781 NS->setInline(*IsInline); 10782 // Patch up the lookup table for the containing namespace. This isn't really 10783 // correct, but it's good enough for this particular case. 10784 for (auto *I : PrevNS->decls()) 10785 if (auto *ND = dyn_cast<NamedDecl>(I)) 10786 PrevNS->getParent()->makeDeclVisibleInContext(ND); 10787 return; 10788 } 10789 10790 if (PrevNS->isInline()) 10791 // The user probably just forgot the 'inline', so suggest that it 10792 // be added back. 10793 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 10794 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 10795 else 10796 S.Diag(Loc, diag::err_inline_namespace_mismatch); 10797 10798 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 10799 *IsInline = PrevNS->isInline(); 10800 } 10801 10802 /// ActOnStartNamespaceDef - This is called at the start of a namespace 10803 /// definition. 10804 Decl *Sema::ActOnStartNamespaceDef( 10805 Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc, 10806 SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace, 10807 const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) { 10808 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 10809 // For anonymous namespace, take the location of the left brace. 10810 SourceLocation Loc = II ? IdentLoc : LBrace; 10811 bool IsInline = InlineLoc.isValid(); 10812 bool IsInvalid = false; 10813 bool IsStd = false; 10814 bool AddToKnown = false; 10815 Scope *DeclRegionScope = NamespcScope->getParent(); 10816 10817 NamespaceDecl *PrevNS = nullptr; 10818 if (II) { 10819 // C++ [namespace.def]p2: 10820 // The identifier in an original-namespace-definition shall not 10821 // have been previously defined in the declarative region in 10822 // which the original-namespace-definition appears. The 10823 // identifier in an original-namespace-definition is the name of 10824 // the namespace. Subsequently in that declarative region, it is 10825 // treated as an original-namespace-name. 10826 // 10827 // Since namespace names are unique in their scope, and we don't 10828 // look through using directives, just look for any ordinary names 10829 // as if by qualified name lookup. 10830 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, 10831 ForExternalRedeclaration); 10832 LookupQualifiedName(R, CurContext->getRedeclContext()); 10833 NamedDecl *PrevDecl = 10834 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr; 10835 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 10836 10837 if (PrevNS) { 10838 // This is an extended namespace definition. 10839 if (IsInline != PrevNS->isInline()) 10840 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 10841 &IsInline, PrevNS); 10842 } else if (PrevDecl) { 10843 // This is an invalid name redefinition. 10844 Diag(Loc, diag::err_redefinition_different_kind) 10845 << II; 10846 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 10847 IsInvalid = true; 10848 // Continue on to push Namespc as current DeclContext and return it. 10849 } else if (II->isStr("std") && 10850 CurContext->getRedeclContext()->isTranslationUnit()) { 10851 // This is the first "real" definition of the namespace "std", so update 10852 // our cache of the "std" namespace to point at this definition. 10853 PrevNS = getStdNamespace(); 10854 IsStd = true; 10855 AddToKnown = !IsInline; 10856 } else { 10857 // We've seen this namespace for the first time. 10858 AddToKnown = !IsInline; 10859 } 10860 } else { 10861 // Anonymous namespaces. 10862 10863 // Determine whether the parent already has an anonymous namespace. 10864 DeclContext *Parent = CurContext->getRedeclContext(); 10865 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 10866 PrevNS = TU->getAnonymousNamespace(); 10867 } else { 10868 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 10869 PrevNS = ND->getAnonymousNamespace(); 10870 } 10871 10872 if (PrevNS && IsInline != PrevNS->isInline()) 10873 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 10874 &IsInline, PrevNS); 10875 } 10876 10877 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 10878 StartLoc, Loc, II, PrevNS); 10879 if (IsInvalid) 10880 Namespc->setInvalidDecl(); 10881 10882 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 10883 AddPragmaAttributes(DeclRegionScope, Namespc); 10884 10885 // FIXME: Should we be merging attributes? 10886 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 10887 PushNamespaceVisibilityAttr(Attr, Loc); 10888 10889 if (IsStd) 10890 StdNamespace = Namespc; 10891 if (AddToKnown) 10892 KnownNamespaces[Namespc] = false; 10893 10894 if (II) { 10895 PushOnScopeChains(Namespc, DeclRegionScope); 10896 } else { 10897 // Link the anonymous namespace into its parent. 10898 DeclContext *Parent = CurContext->getRedeclContext(); 10899 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 10900 TU->setAnonymousNamespace(Namespc); 10901 } else { 10902 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 10903 } 10904 10905 CurContext->addDecl(Namespc); 10906 10907 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 10908 // behaves as if it were replaced by 10909 // namespace unique { /* empty body */ } 10910 // using namespace unique; 10911 // namespace unique { namespace-body } 10912 // where all occurrences of 'unique' in a translation unit are 10913 // replaced by the same identifier and this identifier differs 10914 // from all other identifiers in the entire program. 10915 10916 // We just create the namespace with an empty name and then add an 10917 // implicit using declaration, just like the standard suggests. 10918 // 10919 // CodeGen enforces the "universally unique" aspect by giving all 10920 // declarations semantically contained within an anonymous 10921 // namespace internal linkage. 10922 10923 if (!PrevNS) { 10924 UD = UsingDirectiveDecl::Create(Context, Parent, 10925 /* 'using' */ LBrace, 10926 /* 'namespace' */ SourceLocation(), 10927 /* qualifier */ NestedNameSpecifierLoc(), 10928 /* identifier */ SourceLocation(), 10929 Namespc, 10930 /* Ancestor */ Parent); 10931 UD->setImplicit(); 10932 Parent->addDecl(UD); 10933 } 10934 } 10935 10936 ActOnDocumentableDecl(Namespc); 10937 10938 // Although we could have an invalid decl (i.e. the namespace name is a 10939 // redefinition), push it as current DeclContext and try to continue parsing. 10940 // FIXME: We should be able to push Namespc here, so that the each DeclContext 10941 // for the namespace has the declarations that showed up in that particular 10942 // namespace definition. 10943 PushDeclContext(NamespcScope, Namespc); 10944 return Namespc; 10945 } 10946 10947 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 10948 /// is a namespace alias, returns the namespace it points to. 10949 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 10950 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 10951 return AD->getNamespace(); 10952 return dyn_cast_or_null<NamespaceDecl>(D); 10953 } 10954 10955 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 10956 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 10957 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 10958 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 10959 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 10960 Namespc->setRBraceLoc(RBrace); 10961 PopDeclContext(); 10962 if (Namespc->hasAttr<VisibilityAttr>()) 10963 PopPragmaVisibility(true, RBrace); 10964 // If this namespace contains an export-declaration, export it now. 10965 if (DeferredExportedNamespaces.erase(Namespc)) 10966 Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported); 10967 } 10968 10969 CXXRecordDecl *Sema::getStdBadAlloc() const { 10970 return cast_or_null<CXXRecordDecl>( 10971 StdBadAlloc.get(Context.getExternalSource())); 10972 } 10973 10974 EnumDecl *Sema::getStdAlignValT() const { 10975 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource())); 10976 } 10977 10978 NamespaceDecl *Sema::getStdNamespace() const { 10979 return cast_or_null<NamespaceDecl>( 10980 StdNamespace.get(Context.getExternalSource())); 10981 } 10982 10983 NamespaceDecl *Sema::lookupStdExperimentalNamespace() { 10984 if (!StdExperimentalNamespaceCache) { 10985 if (auto Std = getStdNamespace()) { 10986 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"), 10987 SourceLocation(), LookupNamespaceName); 10988 if (!LookupQualifiedName(Result, Std) || 10989 !(StdExperimentalNamespaceCache = 10990 Result.getAsSingle<NamespaceDecl>())) 10991 Result.suppressDiagnostics(); 10992 } 10993 } 10994 return StdExperimentalNamespaceCache; 10995 } 10996 10997 namespace { 10998 10999 enum UnsupportedSTLSelect { 11000 USS_InvalidMember, 11001 USS_MissingMember, 11002 USS_NonTrivial, 11003 USS_Other 11004 }; 11005 11006 struct InvalidSTLDiagnoser { 11007 Sema &S; 11008 SourceLocation Loc; 11009 QualType TyForDiags; 11010 11011 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "", 11012 const VarDecl *VD = nullptr) { 11013 { 11014 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported) 11015 << TyForDiags << ((int)Sel); 11016 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) { 11017 assert(!Name.empty()); 11018 D << Name; 11019 } 11020 } 11021 if (Sel == USS_InvalidMember) { 11022 S.Diag(VD->getLocation(), diag::note_var_declared_here) 11023 << VD << VD->getSourceRange(); 11024 } 11025 return QualType(); 11026 } 11027 }; 11028 } // namespace 11029 11030 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind, 11031 SourceLocation Loc, 11032 ComparisonCategoryUsage Usage) { 11033 assert(getLangOpts().CPlusPlus && 11034 "Looking for comparison category type outside of C++."); 11035 11036 // Use an elaborated type for diagnostics which has a name containing the 11037 // prepended 'std' namespace but not any inline namespace names. 11038 auto TyForDiags = [&](ComparisonCategoryInfo *Info) { 11039 auto *NNS = 11040 NestedNameSpecifier::Create(Context, nullptr, getStdNamespace()); 11041 return Context.getElaboratedType(ETK_None, NNS, Info->getType()); 11042 }; 11043 11044 // Check if we've already successfully checked the comparison category type 11045 // before. If so, skip checking it again. 11046 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind); 11047 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) { 11048 // The only thing we need to check is that the type has a reachable 11049 // definition in the current context. 11050 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type)) 11051 return QualType(); 11052 11053 return Info->getType(); 11054 } 11055 11056 // If lookup failed 11057 if (!Info) { 11058 std::string NameForDiags = "std::"; 11059 NameForDiags += ComparisonCategories::getCategoryString(Kind); 11060 Diag(Loc, diag::err_implied_comparison_category_type_not_found) 11061 << NameForDiags << (int)Usage; 11062 return QualType(); 11063 } 11064 11065 assert(Info->Kind == Kind); 11066 assert(Info->Record); 11067 11068 // Update the Record decl in case we encountered a forward declaration on our 11069 // first pass. FIXME: This is a bit of a hack. 11070 if (Info->Record->hasDefinition()) 11071 Info->Record = Info->Record->getDefinition(); 11072 11073 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type)) 11074 return QualType(); 11075 11076 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)}; 11077 11078 if (!Info->Record->isTriviallyCopyable()) 11079 return UnsupportedSTLError(USS_NonTrivial); 11080 11081 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) { 11082 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl(); 11083 // Tolerate empty base classes. 11084 if (Base->isEmpty()) 11085 continue; 11086 // Reject STL implementations which have at least one non-empty base. 11087 return UnsupportedSTLError(); 11088 } 11089 11090 // Check that the STL has implemented the types using a single integer field. 11091 // This expectation allows better codegen for builtin operators. We require: 11092 // (1) The class has exactly one field. 11093 // (2) The field is an integral or enumeration type. 11094 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end(); 11095 if (std::distance(FIt, FEnd) != 1 || 11096 !FIt->getType()->isIntegralOrEnumerationType()) { 11097 return UnsupportedSTLError(); 11098 } 11099 11100 // Build each of the require values and store them in Info. 11101 for (ComparisonCategoryResult CCR : 11102 ComparisonCategories::getPossibleResultsForType(Kind)) { 11103 StringRef MemName = ComparisonCategories::getResultString(CCR); 11104 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR); 11105 11106 if (!ValInfo) 11107 return UnsupportedSTLError(USS_MissingMember, MemName); 11108 11109 VarDecl *VD = ValInfo->VD; 11110 assert(VD && "should not be null!"); 11111 11112 // Attempt to diagnose reasons why the STL definition of this type 11113 // might be foobar, including it failing to be a constant expression. 11114 // TODO Handle more ways the lookup or result can be invalid. 11115 if (!VD->isStaticDataMember() || 11116 !VD->isUsableInConstantExpressions(Context)) 11117 return UnsupportedSTLError(USS_InvalidMember, MemName, VD); 11118 11119 // Attempt to evaluate the var decl as a constant expression and extract 11120 // the value of its first field as a ICE. If this fails, the STL 11121 // implementation is not supported. 11122 if (!ValInfo->hasValidIntValue()) 11123 return UnsupportedSTLError(); 11124 11125 MarkVariableReferenced(Loc, VD); 11126 } 11127 11128 // We've successfully built the required types and expressions. Update 11129 // the cache and return the newly cached value. 11130 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true; 11131 return Info->getType(); 11132 } 11133 11134 /// Retrieve the special "std" namespace, which may require us to 11135 /// implicitly define the namespace. 11136 NamespaceDecl *Sema::getOrCreateStdNamespace() { 11137 if (!StdNamespace) { 11138 // The "std" namespace has not yet been defined, so build one implicitly. 11139 StdNamespace = NamespaceDecl::Create(Context, 11140 Context.getTranslationUnitDecl(), 11141 /*Inline=*/false, 11142 SourceLocation(), SourceLocation(), 11143 &PP.getIdentifierTable().get("std"), 11144 /*PrevDecl=*/nullptr); 11145 getStdNamespace()->setImplicit(true); 11146 } 11147 11148 return getStdNamespace(); 11149 } 11150 11151 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 11152 assert(getLangOpts().CPlusPlus && 11153 "Looking for std::initializer_list outside of C++."); 11154 11155 // We're looking for implicit instantiations of 11156 // template <typename E> class std::initializer_list. 11157 11158 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 11159 return false; 11160 11161 ClassTemplateDecl *Template = nullptr; 11162 const TemplateArgument *Arguments = nullptr; 11163 11164 if (const RecordType *RT = Ty->getAs<RecordType>()) { 11165 11166 ClassTemplateSpecializationDecl *Specialization = 11167 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 11168 if (!Specialization) 11169 return false; 11170 11171 Template = Specialization->getSpecializedTemplate(); 11172 Arguments = Specialization->getTemplateArgs().data(); 11173 } else if (const TemplateSpecializationType *TST = 11174 Ty->getAs<TemplateSpecializationType>()) { 11175 Template = dyn_cast_or_null<ClassTemplateDecl>( 11176 TST->getTemplateName().getAsTemplateDecl()); 11177 Arguments = TST->getArgs(); 11178 } 11179 if (!Template) 11180 return false; 11181 11182 if (!StdInitializerList) { 11183 // Haven't recognized std::initializer_list yet, maybe this is it. 11184 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 11185 if (TemplateClass->getIdentifier() != 11186 &PP.getIdentifierTable().get("initializer_list") || 11187 !getStdNamespace()->InEnclosingNamespaceSetOf( 11188 TemplateClass->getDeclContext())) 11189 return false; 11190 // This is a template called std::initializer_list, but is it the right 11191 // template? 11192 TemplateParameterList *Params = Template->getTemplateParameters(); 11193 if (Params->getMinRequiredArguments() != 1) 11194 return false; 11195 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 11196 return false; 11197 11198 // It's the right template. 11199 StdInitializerList = Template; 11200 } 11201 11202 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) 11203 return false; 11204 11205 // This is an instance of std::initializer_list. Find the argument type. 11206 if (Element) 11207 *Element = Arguments[0].getAsType(); 11208 return true; 11209 } 11210 11211 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 11212 NamespaceDecl *Std = S.getStdNamespace(); 11213 if (!Std) { 11214 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 11215 return nullptr; 11216 } 11217 11218 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 11219 Loc, Sema::LookupOrdinaryName); 11220 if (!S.LookupQualifiedName(Result, Std)) { 11221 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 11222 return nullptr; 11223 } 11224 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 11225 if (!Template) { 11226 Result.suppressDiagnostics(); 11227 // We found something weird. Complain about the first thing we found. 11228 NamedDecl *Found = *Result.begin(); 11229 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 11230 return nullptr; 11231 } 11232 11233 // We found some template called std::initializer_list. Now verify that it's 11234 // correct. 11235 TemplateParameterList *Params = Template->getTemplateParameters(); 11236 if (Params->getMinRequiredArguments() != 1 || 11237 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 11238 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 11239 return nullptr; 11240 } 11241 11242 return Template; 11243 } 11244 11245 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 11246 if (!StdInitializerList) { 11247 StdInitializerList = LookupStdInitializerList(*this, Loc); 11248 if (!StdInitializerList) 11249 return QualType(); 11250 } 11251 11252 TemplateArgumentListInfo Args(Loc, Loc); 11253 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 11254 Context.getTrivialTypeSourceInfo(Element, 11255 Loc))); 11256 return Context.getCanonicalType( 11257 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 11258 } 11259 11260 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) { 11261 // C++ [dcl.init.list]p2: 11262 // A constructor is an initializer-list constructor if its first parameter 11263 // is of type std::initializer_list<E> or reference to possibly cv-qualified 11264 // std::initializer_list<E> for some type E, and either there are no other 11265 // parameters or else all other parameters have default arguments. 11266 if (!Ctor->hasOneParamOrDefaultArgs()) 11267 return false; 11268 11269 QualType ArgType = Ctor->getParamDecl(0)->getType(); 11270 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 11271 ArgType = RT->getPointeeType().getUnqualifiedType(); 11272 11273 return isStdInitializerList(ArgType, nullptr); 11274 } 11275 11276 /// Determine whether a using statement is in a context where it will be 11277 /// apply in all contexts. 11278 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 11279 switch (CurContext->getDeclKind()) { 11280 case Decl::TranslationUnit: 11281 return true; 11282 case Decl::LinkageSpec: 11283 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 11284 default: 11285 return false; 11286 } 11287 } 11288 11289 namespace { 11290 11291 // Callback to only accept typo corrections that are namespaces. 11292 class NamespaceValidatorCCC final : public CorrectionCandidateCallback { 11293 public: 11294 bool ValidateCandidate(const TypoCorrection &candidate) override { 11295 if (NamedDecl *ND = candidate.getCorrectionDecl()) 11296 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 11297 return false; 11298 } 11299 11300 std::unique_ptr<CorrectionCandidateCallback> clone() override { 11301 return std::make_unique<NamespaceValidatorCCC>(*this); 11302 } 11303 }; 11304 11305 } 11306 11307 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 11308 CXXScopeSpec &SS, 11309 SourceLocation IdentLoc, 11310 IdentifierInfo *Ident) { 11311 R.clear(); 11312 NamespaceValidatorCCC CCC{}; 11313 if (TypoCorrection Corrected = 11314 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC, 11315 Sema::CTK_ErrorRecovery)) { 11316 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 11317 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 11318 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 11319 Ident->getName().equals(CorrectedStr); 11320 S.diagnoseTypo(Corrected, 11321 S.PDiag(diag::err_using_directive_member_suggest) 11322 << Ident << DC << DroppedSpecifier << SS.getRange(), 11323 S.PDiag(diag::note_namespace_defined_here)); 11324 } else { 11325 S.diagnoseTypo(Corrected, 11326 S.PDiag(diag::err_using_directive_suggest) << Ident, 11327 S.PDiag(diag::note_namespace_defined_here)); 11328 } 11329 R.addDecl(Corrected.getFoundDecl()); 11330 return true; 11331 } 11332 return false; 11333 } 11334 11335 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc, 11336 SourceLocation NamespcLoc, CXXScopeSpec &SS, 11337 SourceLocation IdentLoc, 11338 IdentifierInfo *NamespcName, 11339 const ParsedAttributesView &AttrList) { 11340 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 11341 assert(NamespcName && "Invalid NamespcName."); 11342 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 11343 11344 // This can only happen along a recovery path. 11345 while (S->isTemplateParamScope()) 11346 S = S->getParent(); 11347 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 11348 11349 UsingDirectiveDecl *UDir = nullptr; 11350 NestedNameSpecifier *Qualifier = nullptr; 11351 if (SS.isSet()) 11352 Qualifier = SS.getScopeRep(); 11353 11354 // Lookup namespace name. 11355 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 11356 LookupParsedName(R, S, &SS); 11357 if (R.isAmbiguous()) 11358 return nullptr; 11359 11360 if (R.empty()) { 11361 R.clear(); 11362 // Allow "using namespace std;" or "using namespace ::std;" even if 11363 // "std" hasn't been defined yet, for GCC compatibility. 11364 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 11365 NamespcName->isStr("std")) { 11366 Diag(IdentLoc, diag::ext_using_undefined_std); 11367 R.addDecl(getOrCreateStdNamespace()); 11368 R.resolveKind(); 11369 } 11370 // Otherwise, attempt typo correction. 11371 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 11372 } 11373 11374 if (!R.empty()) { 11375 NamedDecl *Named = R.getRepresentativeDecl(); 11376 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>(); 11377 assert(NS && "expected namespace decl"); 11378 11379 // The use of a nested name specifier may trigger deprecation warnings. 11380 DiagnoseUseOfDecl(Named, IdentLoc); 11381 11382 // C++ [namespace.udir]p1: 11383 // A using-directive specifies that the names in the nominated 11384 // namespace can be used in the scope in which the 11385 // using-directive appears after the using-directive. During 11386 // unqualified name lookup (3.4.1), the names appear as if they 11387 // were declared in the nearest enclosing namespace which 11388 // contains both the using-directive and the nominated 11389 // namespace. [Note: in this context, "contains" means "contains 11390 // directly or indirectly". ] 11391 11392 // Find enclosing context containing both using-directive and 11393 // nominated namespace. 11394 DeclContext *CommonAncestor = NS; 11395 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 11396 CommonAncestor = CommonAncestor->getParent(); 11397 11398 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 11399 SS.getWithLocInContext(Context), 11400 IdentLoc, Named, CommonAncestor); 11401 11402 if (IsUsingDirectiveInToplevelContext(CurContext) && 11403 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 11404 Diag(IdentLoc, diag::warn_using_directive_in_header); 11405 } 11406 11407 PushUsingDirective(S, UDir); 11408 } else { 11409 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 11410 } 11411 11412 if (UDir) 11413 ProcessDeclAttributeList(S, UDir, AttrList); 11414 11415 return UDir; 11416 } 11417 11418 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 11419 // If the scope has an associated entity and the using directive is at 11420 // namespace or translation unit scope, add the UsingDirectiveDecl into 11421 // its lookup structure so qualified name lookup can find it. 11422 DeclContext *Ctx = S->getEntity(); 11423 if (Ctx && !Ctx->isFunctionOrMethod()) 11424 Ctx->addDecl(UDir); 11425 else 11426 // Otherwise, it is at block scope. The using-directives will affect lookup 11427 // only to the end of the scope. 11428 S->PushUsingDirective(UDir); 11429 } 11430 11431 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS, 11432 SourceLocation UsingLoc, 11433 SourceLocation TypenameLoc, CXXScopeSpec &SS, 11434 UnqualifiedId &Name, 11435 SourceLocation EllipsisLoc, 11436 const ParsedAttributesView &AttrList) { 11437 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 11438 11439 if (SS.isEmpty()) { 11440 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname); 11441 return nullptr; 11442 } 11443 11444 switch (Name.getKind()) { 11445 case UnqualifiedIdKind::IK_ImplicitSelfParam: 11446 case UnqualifiedIdKind::IK_Identifier: 11447 case UnqualifiedIdKind::IK_OperatorFunctionId: 11448 case UnqualifiedIdKind::IK_LiteralOperatorId: 11449 case UnqualifiedIdKind::IK_ConversionFunctionId: 11450 break; 11451 11452 case UnqualifiedIdKind::IK_ConstructorName: 11453 case UnqualifiedIdKind::IK_ConstructorTemplateId: 11454 // C++11 inheriting constructors. 11455 Diag(Name.getBeginLoc(), 11456 getLangOpts().CPlusPlus11 11457 ? diag::warn_cxx98_compat_using_decl_constructor 11458 : diag::err_using_decl_constructor) 11459 << SS.getRange(); 11460 11461 if (getLangOpts().CPlusPlus11) break; 11462 11463 return nullptr; 11464 11465 case UnqualifiedIdKind::IK_DestructorName: 11466 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange(); 11467 return nullptr; 11468 11469 case UnqualifiedIdKind::IK_TemplateId: 11470 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id) 11471 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 11472 return nullptr; 11473 11474 case UnqualifiedIdKind::IK_DeductionGuideName: 11475 llvm_unreachable("cannot parse qualified deduction guide name"); 11476 } 11477 11478 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 11479 DeclarationName TargetName = TargetNameInfo.getName(); 11480 if (!TargetName) 11481 return nullptr; 11482 11483 // Warn about access declarations. 11484 if (UsingLoc.isInvalid()) { 11485 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11 11486 ? diag::err_access_decl 11487 : diag::warn_access_decl_deprecated) 11488 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 11489 } 11490 11491 if (EllipsisLoc.isInvalid()) { 11492 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 11493 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 11494 return nullptr; 11495 } else { 11496 if (!SS.getScopeRep()->containsUnexpandedParameterPack() && 11497 !TargetNameInfo.containsUnexpandedParameterPack()) { 11498 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 11499 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc()); 11500 EllipsisLoc = SourceLocation(); 11501 } 11502 } 11503 11504 NamedDecl *UD = 11505 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc, 11506 SS, TargetNameInfo, EllipsisLoc, AttrList, 11507 /*IsInstantiation*/false); 11508 if (UD) 11509 PushOnScopeChains(UD, S, /*AddToContext*/ false); 11510 11511 return UD; 11512 } 11513 11514 /// Determine whether a using declaration considers the given 11515 /// declarations as "equivalent", e.g., if they are redeclarations of 11516 /// the same entity or are both typedefs of the same type. 11517 static bool 11518 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 11519 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 11520 return true; 11521 11522 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 11523 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 11524 return Context.hasSameType(TD1->getUnderlyingType(), 11525 TD2->getUnderlyingType()); 11526 11527 return false; 11528 } 11529 11530 11531 /// Determines whether to create a using shadow decl for a particular 11532 /// decl, given the set of decls existing prior to this using lookup. 11533 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 11534 const LookupResult &Previous, 11535 UsingShadowDecl *&PrevShadow) { 11536 // Diagnose finding a decl which is not from a base class of the 11537 // current class. We do this now because there are cases where this 11538 // function will silently decide not to build a shadow decl, which 11539 // will pre-empt further diagnostics. 11540 // 11541 // We don't need to do this in C++11 because we do the check once on 11542 // the qualifier. 11543 // 11544 // FIXME: diagnose the following if we care enough: 11545 // struct A { int foo; }; 11546 // struct B : A { using A::foo; }; 11547 // template <class T> struct C : A {}; 11548 // template <class T> struct D : C<T> { using B::foo; } // <--- 11549 // This is invalid (during instantiation) in C++03 because B::foo 11550 // resolves to the using decl in B, which is not a base class of D<T>. 11551 // We can't diagnose it immediately because C<T> is an unknown 11552 // specialization. The UsingShadowDecl in D<T> then points directly 11553 // to A::foo, which will look well-formed when we instantiate. 11554 // The right solution is to not collapse the shadow-decl chain. 11555 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 11556 DeclContext *OrigDC = Orig->getDeclContext(); 11557 11558 // Handle enums and anonymous structs. 11559 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 11560 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 11561 while (OrigRec->isAnonymousStructOrUnion()) 11562 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 11563 11564 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 11565 if (OrigDC == CurContext) { 11566 Diag(Using->getLocation(), 11567 diag::err_using_decl_nested_name_specifier_is_current_class) 11568 << Using->getQualifierLoc().getSourceRange(); 11569 Diag(Orig->getLocation(), diag::note_using_decl_target); 11570 Using->setInvalidDecl(); 11571 return true; 11572 } 11573 11574 Diag(Using->getQualifierLoc().getBeginLoc(), 11575 diag::err_using_decl_nested_name_specifier_is_not_base_class) 11576 << Using->getQualifier() 11577 << cast<CXXRecordDecl>(CurContext) 11578 << Using->getQualifierLoc().getSourceRange(); 11579 Diag(Orig->getLocation(), diag::note_using_decl_target); 11580 Using->setInvalidDecl(); 11581 return true; 11582 } 11583 } 11584 11585 if (Previous.empty()) return false; 11586 11587 NamedDecl *Target = Orig; 11588 if (isa<UsingShadowDecl>(Target)) 11589 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 11590 11591 // If the target happens to be one of the previous declarations, we 11592 // don't have a conflict. 11593 // 11594 // FIXME: but we might be increasing its access, in which case we 11595 // should redeclare it. 11596 NamedDecl *NonTag = nullptr, *Tag = nullptr; 11597 bool FoundEquivalentDecl = false; 11598 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 11599 I != E; ++I) { 11600 NamedDecl *D = (*I)->getUnderlyingDecl(); 11601 // We can have UsingDecls in our Previous results because we use the same 11602 // LookupResult for checking whether the UsingDecl itself is a valid 11603 // redeclaration. 11604 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D)) 11605 continue; 11606 11607 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 11608 // C++ [class.mem]p19: 11609 // If T is the name of a class, then [every named member other than 11610 // a non-static data member] shall have a name different from T 11611 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) && 11612 !isa<IndirectFieldDecl>(Target) && 11613 !isa<UnresolvedUsingValueDecl>(Target) && 11614 DiagnoseClassNameShadow( 11615 CurContext, 11616 DeclarationNameInfo(Using->getDeclName(), Using->getLocation()))) 11617 return true; 11618 } 11619 11620 if (IsEquivalentForUsingDecl(Context, D, Target)) { 11621 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 11622 PrevShadow = Shadow; 11623 FoundEquivalentDecl = true; 11624 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) { 11625 // We don't conflict with an existing using shadow decl of an equivalent 11626 // declaration, but we're not a redeclaration of it. 11627 FoundEquivalentDecl = true; 11628 } 11629 11630 if (isVisible(D)) 11631 (isa<TagDecl>(D) ? Tag : NonTag) = D; 11632 } 11633 11634 if (FoundEquivalentDecl) 11635 return false; 11636 11637 if (FunctionDecl *FD = Target->getAsFunction()) { 11638 NamedDecl *OldDecl = nullptr; 11639 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 11640 /*IsForUsingDecl*/ true)) { 11641 case Ovl_Overload: 11642 return false; 11643 11644 case Ovl_NonFunction: 11645 Diag(Using->getLocation(), diag::err_using_decl_conflict); 11646 break; 11647 11648 // We found a decl with the exact signature. 11649 case Ovl_Match: 11650 // If we're in a record, we want to hide the target, so we 11651 // return true (without a diagnostic) to tell the caller not to 11652 // build a shadow decl. 11653 if (CurContext->isRecord()) 11654 return true; 11655 11656 // If we're not in a record, this is an error. 11657 Diag(Using->getLocation(), diag::err_using_decl_conflict); 11658 break; 11659 } 11660 11661 Diag(Target->getLocation(), diag::note_using_decl_target); 11662 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 11663 Using->setInvalidDecl(); 11664 return true; 11665 } 11666 11667 // Target is not a function. 11668 11669 if (isa<TagDecl>(Target)) { 11670 // No conflict between a tag and a non-tag. 11671 if (!Tag) return false; 11672 11673 Diag(Using->getLocation(), diag::err_using_decl_conflict); 11674 Diag(Target->getLocation(), diag::note_using_decl_target); 11675 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 11676 Using->setInvalidDecl(); 11677 return true; 11678 } 11679 11680 // No conflict between a tag and a non-tag. 11681 if (!NonTag) return false; 11682 11683 Diag(Using->getLocation(), diag::err_using_decl_conflict); 11684 Diag(Target->getLocation(), diag::note_using_decl_target); 11685 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 11686 Using->setInvalidDecl(); 11687 return true; 11688 } 11689 11690 /// Determine whether a direct base class is a virtual base class. 11691 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) { 11692 if (!Derived->getNumVBases()) 11693 return false; 11694 for (auto &B : Derived->bases()) 11695 if (B.getType()->getAsCXXRecordDecl() == Base) 11696 return B.isVirtual(); 11697 llvm_unreachable("not a direct base class"); 11698 } 11699 11700 /// Builds a shadow declaration corresponding to a 'using' declaration. 11701 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 11702 UsingDecl *UD, 11703 NamedDecl *Orig, 11704 UsingShadowDecl *PrevDecl) { 11705 // If we resolved to another shadow declaration, just coalesce them. 11706 NamedDecl *Target = Orig; 11707 if (isa<UsingShadowDecl>(Target)) { 11708 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 11709 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 11710 } 11711 11712 NamedDecl *NonTemplateTarget = Target; 11713 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target)) 11714 NonTemplateTarget = TargetTD->getTemplatedDecl(); 11715 11716 UsingShadowDecl *Shadow; 11717 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) { 11718 bool IsVirtualBase = 11719 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext), 11720 UD->getQualifier()->getAsRecordDecl()); 11721 Shadow = ConstructorUsingShadowDecl::Create( 11722 Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase); 11723 } else { 11724 Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD, 11725 Target); 11726 } 11727 UD->addShadowDecl(Shadow); 11728 11729 Shadow->setAccess(UD->getAccess()); 11730 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 11731 Shadow->setInvalidDecl(); 11732 11733 Shadow->setPreviousDecl(PrevDecl); 11734 11735 if (S) 11736 PushOnScopeChains(Shadow, S); 11737 else 11738 CurContext->addDecl(Shadow); 11739 11740 11741 return Shadow; 11742 } 11743 11744 /// Hides a using shadow declaration. This is required by the current 11745 /// using-decl implementation when a resolvable using declaration in a 11746 /// class is followed by a declaration which would hide or override 11747 /// one or more of the using decl's targets; for example: 11748 /// 11749 /// struct Base { void foo(int); }; 11750 /// struct Derived : Base { 11751 /// using Base::foo; 11752 /// void foo(int); 11753 /// }; 11754 /// 11755 /// The governing language is C++03 [namespace.udecl]p12: 11756 /// 11757 /// When a using-declaration brings names from a base class into a 11758 /// derived class scope, member functions in the derived class 11759 /// override and/or hide member functions with the same name and 11760 /// parameter types in a base class (rather than conflicting). 11761 /// 11762 /// There are two ways to implement this: 11763 /// (1) optimistically create shadow decls when they're not hidden 11764 /// by existing declarations, or 11765 /// (2) don't create any shadow decls (or at least don't make them 11766 /// visible) until we've fully parsed/instantiated the class. 11767 /// The problem with (1) is that we might have to retroactively remove 11768 /// a shadow decl, which requires several O(n) operations because the 11769 /// decl structures are (very reasonably) not designed for removal. 11770 /// (2) avoids this but is very fiddly and phase-dependent. 11771 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 11772 if (Shadow->getDeclName().getNameKind() == 11773 DeclarationName::CXXConversionFunctionName) 11774 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 11775 11776 // Remove it from the DeclContext... 11777 Shadow->getDeclContext()->removeDecl(Shadow); 11778 11779 // ...and the scope, if applicable... 11780 if (S) { 11781 S->RemoveDecl(Shadow); 11782 IdResolver.RemoveDecl(Shadow); 11783 } 11784 11785 // ...and the using decl. 11786 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 11787 11788 // TODO: complain somehow if Shadow was used. It shouldn't 11789 // be possible for this to happen, because...? 11790 } 11791 11792 /// Find the base specifier for a base class with the given type. 11793 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 11794 QualType DesiredBase, 11795 bool &AnyDependentBases) { 11796 // Check whether the named type is a direct base class. 11797 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified() 11798 .getUnqualifiedType(); 11799 for (auto &Base : Derived->bases()) { 11800 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 11801 if (CanonicalDesiredBase == BaseType) 11802 return &Base; 11803 if (BaseType->isDependentType()) 11804 AnyDependentBases = true; 11805 } 11806 return nullptr; 11807 } 11808 11809 namespace { 11810 class UsingValidatorCCC final : public CorrectionCandidateCallback { 11811 public: 11812 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 11813 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 11814 : HasTypenameKeyword(HasTypenameKeyword), 11815 IsInstantiation(IsInstantiation), OldNNS(NNS), 11816 RequireMemberOf(RequireMemberOf) {} 11817 11818 bool ValidateCandidate(const TypoCorrection &Candidate) override { 11819 NamedDecl *ND = Candidate.getCorrectionDecl(); 11820 11821 // Keywords are not valid here. 11822 if (!ND || isa<NamespaceDecl>(ND)) 11823 return false; 11824 11825 // Completely unqualified names are invalid for a 'using' declaration. 11826 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 11827 return false; 11828 11829 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would 11830 // reject. 11831 11832 if (RequireMemberOf) { 11833 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 11834 if (FoundRecord && FoundRecord->isInjectedClassName()) { 11835 // No-one ever wants a using-declaration to name an injected-class-name 11836 // of a base class, unless they're declaring an inheriting constructor. 11837 ASTContext &Ctx = ND->getASTContext(); 11838 if (!Ctx.getLangOpts().CPlusPlus11) 11839 return false; 11840 QualType FoundType = Ctx.getRecordType(FoundRecord); 11841 11842 // Check that the injected-class-name is named as a member of its own 11843 // type; we don't want to suggest 'using Derived::Base;', since that 11844 // means something else. 11845 NestedNameSpecifier *Specifier = 11846 Candidate.WillReplaceSpecifier() 11847 ? Candidate.getCorrectionSpecifier() 11848 : OldNNS; 11849 if (!Specifier->getAsType() || 11850 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 11851 return false; 11852 11853 // Check that this inheriting constructor declaration actually names a 11854 // direct base class of the current class. 11855 bool AnyDependentBases = false; 11856 if (!findDirectBaseWithType(RequireMemberOf, 11857 Ctx.getRecordType(FoundRecord), 11858 AnyDependentBases) && 11859 !AnyDependentBases) 11860 return false; 11861 } else { 11862 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 11863 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 11864 return false; 11865 11866 // FIXME: Check that the base class member is accessible? 11867 } 11868 } else { 11869 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 11870 if (FoundRecord && FoundRecord->isInjectedClassName()) 11871 return false; 11872 } 11873 11874 if (isa<TypeDecl>(ND)) 11875 return HasTypenameKeyword || !IsInstantiation; 11876 11877 return !HasTypenameKeyword; 11878 } 11879 11880 std::unique_ptr<CorrectionCandidateCallback> clone() override { 11881 return std::make_unique<UsingValidatorCCC>(*this); 11882 } 11883 11884 private: 11885 bool HasTypenameKeyword; 11886 bool IsInstantiation; 11887 NestedNameSpecifier *OldNNS; 11888 CXXRecordDecl *RequireMemberOf; 11889 }; 11890 } // end anonymous namespace 11891 11892 /// Builds a using declaration. 11893 /// 11894 /// \param IsInstantiation - Whether this call arises from an 11895 /// instantiation of an unresolved using declaration. We treat 11896 /// the lookup differently for these declarations. 11897 NamedDecl *Sema::BuildUsingDeclaration( 11898 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, 11899 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, 11900 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, 11901 const ParsedAttributesView &AttrList, bool IsInstantiation) { 11902 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 11903 SourceLocation IdentLoc = NameInfo.getLoc(); 11904 assert(IdentLoc.isValid() && "Invalid TargetName location."); 11905 11906 // FIXME: We ignore attributes for now. 11907 11908 // For an inheriting constructor declaration, the name of the using 11909 // declaration is the name of a constructor in this class, not in the 11910 // base class. 11911 DeclarationNameInfo UsingName = NameInfo; 11912 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName) 11913 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext)) 11914 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 11915 Context.getCanonicalType(Context.getRecordType(RD)))); 11916 11917 // Do the redeclaration lookup in the current scope. 11918 LookupResult Previous(*this, UsingName, LookupUsingDeclName, 11919 ForVisibleRedeclaration); 11920 Previous.setHideTags(false); 11921 if (S) { 11922 LookupName(Previous, S); 11923 11924 // It is really dumb that we have to do this. 11925 LookupResult::Filter F = Previous.makeFilter(); 11926 while (F.hasNext()) { 11927 NamedDecl *D = F.next(); 11928 if (!isDeclInScope(D, CurContext, S)) 11929 F.erase(); 11930 // If we found a local extern declaration that's not ordinarily visible, 11931 // and this declaration is being added to a non-block scope, ignore it. 11932 // We're only checking for scope conflicts here, not also for violations 11933 // of the linkage rules. 11934 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 11935 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 11936 F.erase(); 11937 } 11938 F.done(); 11939 } else { 11940 assert(IsInstantiation && "no scope in non-instantiation"); 11941 if (CurContext->isRecord()) 11942 LookupQualifiedName(Previous, CurContext); 11943 else { 11944 // No redeclaration check is needed here; in non-member contexts we 11945 // diagnosed all possible conflicts with other using-declarations when 11946 // building the template: 11947 // 11948 // For a dependent non-type using declaration, the only valid case is 11949 // if we instantiate to a single enumerator. We check for conflicts 11950 // between shadow declarations we introduce, and we check in the template 11951 // definition for conflicts between a non-type using declaration and any 11952 // other declaration, which together covers all cases. 11953 // 11954 // A dependent typename using declaration will never successfully 11955 // instantiate, since it will always name a class member, so we reject 11956 // that in the template definition. 11957 } 11958 } 11959 11960 // Check for invalid redeclarations. 11961 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 11962 SS, IdentLoc, Previous)) 11963 return nullptr; 11964 11965 // Check for bad qualifiers. 11966 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo, 11967 IdentLoc)) 11968 return nullptr; 11969 11970 DeclContext *LookupContext = computeDeclContext(SS); 11971 NamedDecl *D; 11972 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 11973 if (!LookupContext || EllipsisLoc.isValid()) { 11974 if (HasTypenameKeyword) { 11975 // FIXME: not all declaration name kinds are legal here 11976 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 11977 UsingLoc, TypenameLoc, 11978 QualifierLoc, 11979 IdentLoc, NameInfo.getName(), 11980 EllipsisLoc); 11981 } else { 11982 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 11983 QualifierLoc, NameInfo, EllipsisLoc); 11984 } 11985 D->setAccess(AS); 11986 CurContext->addDecl(D); 11987 return D; 11988 } 11989 11990 auto Build = [&](bool Invalid) { 11991 UsingDecl *UD = 11992 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 11993 UsingName, HasTypenameKeyword); 11994 UD->setAccess(AS); 11995 CurContext->addDecl(UD); 11996 UD->setInvalidDecl(Invalid); 11997 return UD; 11998 }; 11999 auto BuildInvalid = [&]{ return Build(true); }; 12000 auto BuildValid = [&]{ return Build(false); }; 12001 12002 if (RequireCompleteDeclContext(SS, LookupContext)) 12003 return BuildInvalid(); 12004 12005 // Look up the target name. 12006 LookupResult R(*this, NameInfo, LookupOrdinaryName); 12007 12008 // Unlike most lookups, we don't always want to hide tag 12009 // declarations: tag names are visible through the using declaration 12010 // even if hidden by ordinary names, *except* in a dependent context 12011 // where it's important for the sanity of two-phase lookup. 12012 if (!IsInstantiation) 12013 R.setHideTags(false); 12014 12015 // For the purposes of this lookup, we have a base object type 12016 // equal to that of the current context. 12017 if (CurContext->isRecord()) { 12018 R.setBaseObjectType( 12019 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 12020 } 12021 12022 LookupQualifiedName(R, LookupContext); 12023 12024 // Try to correct typos if possible. If constructor name lookup finds no 12025 // results, that means the named class has no explicit constructors, and we 12026 // suppressed declaring implicit ones (probably because it's dependent or 12027 // invalid). 12028 if (R.empty() && 12029 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { 12030 // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes 12031 // it will believe that glibc provides a ::gets in cases where it does not, 12032 // and will try to pull it into namespace std with a using-declaration. 12033 // Just ignore the using-declaration in that case. 12034 auto *II = NameInfo.getName().getAsIdentifierInfo(); 12035 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") && 12036 CurContext->isStdNamespace() && 12037 isa<TranslationUnitDecl>(LookupContext) && 12038 getSourceManager().isInSystemHeader(UsingLoc)) 12039 return nullptr; 12040 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 12041 dyn_cast<CXXRecordDecl>(CurContext)); 12042 if (TypoCorrection Corrected = 12043 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 12044 CTK_ErrorRecovery)) { 12045 // We reject candidates where DroppedSpecifier == true, hence the 12046 // literal '0' below. 12047 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 12048 << NameInfo.getName() << LookupContext << 0 12049 << SS.getRange()); 12050 12051 // If we picked a correction with no attached Decl we can't do anything 12052 // useful with it, bail out. 12053 NamedDecl *ND = Corrected.getCorrectionDecl(); 12054 if (!ND) 12055 return BuildInvalid(); 12056 12057 // If we corrected to an inheriting constructor, handle it as one. 12058 auto *RD = dyn_cast<CXXRecordDecl>(ND); 12059 if (RD && RD->isInjectedClassName()) { 12060 // The parent of the injected class name is the class itself. 12061 RD = cast<CXXRecordDecl>(RD->getParent()); 12062 12063 // Fix up the information we'll use to build the using declaration. 12064 if (Corrected.WillReplaceSpecifier()) { 12065 NestedNameSpecifierLocBuilder Builder; 12066 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 12067 QualifierLoc.getSourceRange()); 12068 QualifierLoc = Builder.getWithLocInContext(Context); 12069 } 12070 12071 // In this case, the name we introduce is the name of a derived class 12072 // constructor. 12073 auto *CurClass = cast<CXXRecordDecl>(CurContext); 12074 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 12075 Context.getCanonicalType(Context.getRecordType(CurClass)))); 12076 UsingName.setNamedTypeInfo(nullptr); 12077 for (auto *Ctor : LookupConstructors(RD)) 12078 R.addDecl(Ctor); 12079 R.resolveKind(); 12080 } else { 12081 // FIXME: Pick up all the declarations if we found an overloaded 12082 // function. 12083 UsingName.setName(ND->getDeclName()); 12084 R.addDecl(ND); 12085 } 12086 } else { 12087 Diag(IdentLoc, diag::err_no_member) 12088 << NameInfo.getName() << LookupContext << SS.getRange(); 12089 return BuildInvalid(); 12090 } 12091 } 12092 12093 if (R.isAmbiguous()) 12094 return BuildInvalid(); 12095 12096 if (HasTypenameKeyword) { 12097 // If we asked for a typename and got a non-type decl, error out. 12098 if (!R.getAsSingle<TypeDecl>()) { 12099 Diag(IdentLoc, diag::err_using_typename_non_type); 12100 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 12101 Diag((*I)->getUnderlyingDecl()->getLocation(), 12102 diag::note_using_decl_target); 12103 return BuildInvalid(); 12104 } 12105 } else { 12106 // If we asked for a non-typename and we got a type, error out, 12107 // but only if this is an instantiation of an unresolved using 12108 // decl. Otherwise just silently find the type name. 12109 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 12110 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 12111 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 12112 return BuildInvalid(); 12113 } 12114 } 12115 12116 // C++14 [namespace.udecl]p6: 12117 // A using-declaration shall not name a namespace. 12118 if (R.getAsSingle<NamespaceDecl>()) { 12119 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 12120 << SS.getRange(); 12121 return BuildInvalid(); 12122 } 12123 12124 // C++14 [namespace.udecl]p7: 12125 // A using-declaration shall not name a scoped enumerator. 12126 if (auto *ED = R.getAsSingle<EnumConstantDecl>()) { 12127 if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) { 12128 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum) 12129 << SS.getRange(); 12130 return BuildInvalid(); 12131 } 12132 } 12133 12134 UsingDecl *UD = BuildValid(); 12135 12136 // Some additional rules apply to inheriting constructors. 12137 if (UsingName.getName().getNameKind() == 12138 DeclarationName::CXXConstructorName) { 12139 // Suppress access diagnostics; the access check is instead performed at the 12140 // point of use for an inheriting constructor. 12141 R.suppressDiagnostics(); 12142 if (CheckInheritingConstructorUsingDecl(UD)) 12143 return UD; 12144 } 12145 12146 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 12147 UsingShadowDecl *PrevDecl = nullptr; 12148 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 12149 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 12150 } 12151 12152 return UD; 12153 } 12154 12155 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom, 12156 ArrayRef<NamedDecl *> Expansions) { 12157 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || 12158 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || 12159 isa<UsingPackDecl>(InstantiatedFrom)); 12160 12161 auto *UPD = 12162 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions); 12163 UPD->setAccess(InstantiatedFrom->getAccess()); 12164 CurContext->addDecl(UPD); 12165 return UPD; 12166 } 12167 12168 /// Additional checks for a using declaration referring to a constructor name. 12169 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 12170 assert(!UD->hasTypename() && "expecting a constructor name"); 12171 12172 const Type *SourceType = UD->getQualifier()->getAsType(); 12173 assert(SourceType && 12174 "Using decl naming constructor doesn't have type in scope spec."); 12175 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 12176 12177 // Check whether the named type is a direct base class. 12178 bool AnyDependentBases = false; 12179 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 12180 AnyDependentBases); 12181 if (!Base && !AnyDependentBases) { 12182 Diag(UD->getUsingLoc(), 12183 diag::err_using_decl_constructor_not_in_direct_base) 12184 << UD->getNameInfo().getSourceRange() 12185 << QualType(SourceType, 0) << TargetClass; 12186 UD->setInvalidDecl(); 12187 return true; 12188 } 12189 12190 if (Base) 12191 Base->setInheritConstructors(); 12192 12193 return false; 12194 } 12195 12196 /// Checks that the given using declaration is not an invalid 12197 /// redeclaration. Note that this is checking only for the using decl 12198 /// itself, not for any ill-formedness among the UsingShadowDecls. 12199 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 12200 bool HasTypenameKeyword, 12201 const CXXScopeSpec &SS, 12202 SourceLocation NameLoc, 12203 const LookupResult &Prev) { 12204 NestedNameSpecifier *Qual = SS.getScopeRep(); 12205 12206 // C++03 [namespace.udecl]p8: 12207 // C++0x [namespace.udecl]p10: 12208 // A using-declaration is a declaration and can therefore be used 12209 // repeatedly where (and only where) multiple declarations are 12210 // allowed. 12211 // 12212 // That's in non-member contexts. 12213 if (!CurContext->getRedeclContext()->isRecord()) { 12214 // A dependent qualifier outside a class can only ever resolve to an 12215 // enumeration type. Therefore it conflicts with any other non-type 12216 // declaration in the same scope. 12217 // FIXME: How should we check for dependent type-type conflicts at block 12218 // scope? 12219 if (Qual->isDependent() && !HasTypenameKeyword) { 12220 for (auto *D : Prev) { 12221 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) { 12222 bool OldCouldBeEnumerator = 12223 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D); 12224 Diag(NameLoc, 12225 OldCouldBeEnumerator ? diag::err_redefinition 12226 : diag::err_redefinition_different_kind) 12227 << Prev.getLookupName(); 12228 Diag(D->getLocation(), diag::note_previous_definition); 12229 return true; 12230 } 12231 } 12232 } 12233 return false; 12234 } 12235 12236 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 12237 NamedDecl *D = *I; 12238 12239 bool DTypename; 12240 NestedNameSpecifier *DQual; 12241 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 12242 DTypename = UD->hasTypename(); 12243 DQual = UD->getQualifier(); 12244 } else if (UnresolvedUsingValueDecl *UD 12245 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 12246 DTypename = false; 12247 DQual = UD->getQualifier(); 12248 } else if (UnresolvedUsingTypenameDecl *UD 12249 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 12250 DTypename = true; 12251 DQual = UD->getQualifier(); 12252 } else continue; 12253 12254 // using decls differ if one says 'typename' and the other doesn't. 12255 // FIXME: non-dependent using decls? 12256 if (HasTypenameKeyword != DTypename) continue; 12257 12258 // using decls differ if they name different scopes (but note that 12259 // template instantiation can cause this check to trigger when it 12260 // didn't before instantiation). 12261 if (Context.getCanonicalNestedNameSpecifier(Qual) != 12262 Context.getCanonicalNestedNameSpecifier(DQual)) 12263 continue; 12264 12265 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 12266 Diag(D->getLocation(), diag::note_using_decl) << 1; 12267 return true; 12268 } 12269 12270 return false; 12271 } 12272 12273 12274 /// Checks that the given nested-name qualifier used in a using decl 12275 /// in the current context is appropriately related to the current 12276 /// scope. If an error is found, diagnoses it and returns true. 12277 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 12278 bool HasTypename, 12279 const CXXScopeSpec &SS, 12280 const DeclarationNameInfo &NameInfo, 12281 SourceLocation NameLoc) { 12282 DeclContext *NamedContext = computeDeclContext(SS); 12283 12284 if (!CurContext->isRecord()) { 12285 // C++03 [namespace.udecl]p3: 12286 // C++0x [namespace.udecl]p8: 12287 // A using-declaration for a class member shall be a member-declaration. 12288 12289 // If we weren't able to compute a valid scope, it might validly be a 12290 // dependent class scope or a dependent enumeration unscoped scope. If 12291 // we have a 'typename' keyword, the scope must resolve to a class type. 12292 if ((HasTypename && !NamedContext) || 12293 (NamedContext && NamedContext->getRedeclContext()->isRecord())) { 12294 auto *RD = NamedContext 12295 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext()) 12296 : nullptr; 12297 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) 12298 RD = nullptr; 12299 12300 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 12301 << SS.getRange(); 12302 12303 // If we have a complete, non-dependent source type, try to suggest a 12304 // way to get the same effect. 12305 if (!RD) 12306 return true; 12307 12308 // Find what this using-declaration was referring to. 12309 LookupResult R(*this, NameInfo, LookupOrdinaryName); 12310 R.setHideTags(false); 12311 R.suppressDiagnostics(); 12312 LookupQualifiedName(R, RD); 12313 12314 if (R.getAsSingle<TypeDecl>()) { 12315 if (getLangOpts().CPlusPlus11) { 12316 // Convert 'using X::Y;' to 'using Y = X::Y;'. 12317 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 12318 << 0 // alias declaration 12319 << FixItHint::CreateInsertion(SS.getBeginLoc(), 12320 NameInfo.getName().getAsString() + 12321 " = "); 12322 } else { 12323 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 12324 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc()); 12325 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 12326 << 1 // typedef declaration 12327 << FixItHint::CreateReplacement(UsingLoc, "typedef") 12328 << FixItHint::CreateInsertion( 12329 InsertLoc, " " + NameInfo.getName().getAsString()); 12330 } 12331 } else if (R.getAsSingle<VarDecl>()) { 12332 // Don't provide a fixit outside C++11 mode; we don't want to suggest 12333 // repeating the type of the static data member here. 12334 FixItHint FixIt; 12335 if (getLangOpts().CPlusPlus11) { 12336 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 12337 FixIt = FixItHint::CreateReplacement( 12338 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 12339 } 12340 12341 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 12342 << 2 // reference declaration 12343 << FixIt; 12344 } else if (R.getAsSingle<EnumConstantDecl>()) { 12345 // Don't provide a fixit outside C++11 mode; we don't want to suggest 12346 // repeating the type of the enumeration here, and we can't do so if 12347 // the type is anonymous. 12348 FixItHint FixIt; 12349 if (getLangOpts().CPlusPlus11) { 12350 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 12351 FixIt = FixItHint::CreateReplacement( 12352 UsingLoc, 12353 "constexpr auto " + NameInfo.getName().getAsString() + " = "); 12354 } 12355 12356 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 12357 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable 12358 << FixIt; 12359 } 12360 return true; 12361 } 12362 12363 // Otherwise, this might be valid. 12364 return false; 12365 } 12366 12367 // The current scope is a record. 12368 12369 // If the named context is dependent, we can't decide much. 12370 if (!NamedContext) { 12371 // FIXME: in C++0x, we can diagnose if we can prove that the 12372 // nested-name-specifier does not refer to a base class, which is 12373 // still possible in some cases. 12374 12375 // Otherwise we have to conservatively report that things might be 12376 // okay. 12377 return false; 12378 } 12379 12380 if (!NamedContext->isRecord()) { 12381 // Ideally this would point at the last name in the specifier, 12382 // but we don't have that level of source info. 12383 Diag(SS.getRange().getBegin(), 12384 diag::err_using_decl_nested_name_specifier_is_not_class) 12385 << SS.getScopeRep() << SS.getRange(); 12386 return true; 12387 } 12388 12389 if (!NamedContext->isDependentContext() && 12390 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 12391 return true; 12392 12393 if (getLangOpts().CPlusPlus11) { 12394 // C++11 [namespace.udecl]p3: 12395 // In a using-declaration used as a member-declaration, the 12396 // nested-name-specifier shall name a base class of the class 12397 // being defined. 12398 12399 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 12400 cast<CXXRecordDecl>(NamedContext))) { 12401 if (CurContext == NamedContext) { 12402 Diag(NameLoc, 12403 diag::err_using_decl_nested_name_specifier_is_current_class) 12404 << SS.getRange(); 12405 return true; 12406 } 12407 12408 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) { 12409 Diag(SS.getRange().getBegin(), 12410 diag::err_using_decl_nested_name_specifier_is_not_base_class) 12411 << SS.getScopeRep() 12412 << cast<CXXRecordDecl>(CurContext) 12413 << SS.getRange(); 12414 } 12415 return true; 12416 } 12417 12418 return false; 12419 } 12420 12421 // C++03 [namespace.udecl]p4: 12422 // A using-declaration used as a member-declaration shall refer 12423 // to a member of a base class of the class being defined [etc.]. 12424 12425 // Salient point: SS doesn't have to name a base class as long as 12426 // lookup only finds members from base classes. Therefore we can 12427 // diagnose here only if we can prove that that can't happen, 12428 // i.e. if the class hierarchies provably don't intersect. 12429 12430 // TODO: it would be nice if "definitely valid" results were cached 12431 // in the UsingDecl and UsingShadowDecl so that these checks didn't 12432 // need to be repeated. 12433 12434 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases; 12435 auto Collect = [&Bases](const CXXRecordDecl *Base) { 12436 Bases.insert(Base); 12437 return true; 12438 }; 12439 12440 // Collect all bases. Return false if we find a dependent base. 12441 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect)) 12442 return false; 12443 12444 // Returns true if the base is dependent or is one of the accumulated base 12445 // classes. 12446 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) { 12447 return !Bases.count(Base); 12448 }; 12449 12450 // Return false if the class has a dependent base or if it or one 12451 // of its bases is present in the base set of the current context. 12452 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) || 12453 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase)) 12454 return false; 12455 12456 Diag(SS.getRange().getBegin(), 12457 diag::err_using_decl_nested_name_specifier_is_not_base_class) 12458 << SS.getScopeRep() 12459 << cast<CXXRecordDecl>(CurContext) 12460 << SS.getRange(); 12461 12462 return true; 12463 } 12464 12465 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS, 12466 MultiTemplateParamsArg TemplateParamLists, 12467 SourceLocation UsingLoc, UnqualifiedId &Name, 12468 const ParsedAttributesView &AttrList, 12469 TypeResult Type, Decl *DeclFromDeclSpec) { 12470 // Skip up to the relevant declaration scope. 12471 while (S->isTemplateParamScope()) 12472 S = S->getParent(); 12473 assert((S->getFlags() & Scope::DeclScope) && 12474 "got alias-declaration outside of declaration scope"); 12475 12476 if (Type.isInvalid()) 12477 return nullptr; 12478 12479 bool Invalid = false; 12480 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 12481 TypeSourceInfo *TInfo = nullptr; 12482 GetTypeFromParser(Type.get(), &TInfo); 12483 12484 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 12485 return nullptr; 12486 12487 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 12488 UPPC_DeclarationType)) { 12489 Invalid = true; 12490 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 12491 TInfo->getTypeLoc().getBeginLoc()); 12492 } 12493 12494 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 12495 TemplateParamLists.size() 12496 ? forRedeclarationInCurContext() 12497 : ForVisibleRedeclaration); 12498 LookupName(Previous, S); 12499 12500 // Warn about shadowing the name of a template parameter. 12501 if (Previous.isSingleResult() && 12502 Previous.getFoundDecl()->isTemplateParameter()) { 12503 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 12504 Previous.clear(); 12505 } 12506 12507 assert(Name.Kind == UnqualifiedIdKind::IK_Identifier && 12508 "name in alias declaration must be an identifier"); 12509 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 12510 Name.StartLocation, 12511 Name.Identifier, TInfo); 12512 12513 NewTD->setAccess(AS); 12514 12515 if (Invalid) 12516 NewTD->setInvalidDecl(); 12517 12518 ProcessDeclAttributeList(S, NewTD, AttrList); 12519 AddPragmaAttributes(S, NewTD); 12520 12521 CheckTypedefForVariablyModifiedType(S, NewTD); 12522 Invalid |= NewTD->isInvalidDecl(); 12523 12524 bool Redeclaration = false; 12525 12526 NamedDecl *NewND; 12527 if (TemplateParamLists.size()) { 12528 TypeAliasTemplateDecl *OldDecl = nullptr; 12529 TemplateParameterList *OldTemplateParams = nullptr; 12530 12531 if (TemplateParamLists.size() != 1) { 12532 Diag(UsingLoc, diag::err_alias_template_extra_headers) 12533 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 12534 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 12535 } 12536 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 12537 12538 // Check that we can declare a template here. 12539 if (CheckTemplateDeclScope(S, TemplateParams)) 12540 return nullptr; 12541 12542 // Only consider previous declarations in the same scope. 12543 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 12544 /*ExplicitInstantiationOrSpecialization*/false); 12545 if (!Previous.empty()) { 12546 Redeclaration = true; 12547 12548 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 12549 if (!OldDecl && !Invalid) { 12550 Diag(UsingLoc, diag::err_redefinition_different_kind) 12551 << Name.Identifier; 12552 12553 NamedDecl *OldD = Previous.getRepresentativeDecl(); 12554 if (OldD->getLocation().isValid()) 12555 Diag(OldD->getLocation(), diag::note_previous_definition); 12556 12557 Invalid = true; 12558 } 12559 12560 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 12561 if (TemplateParameterListsAreEqual(TemplateParams, 12562 OldDecl->getTemplateParameters(), 12563 /*Complain=*/true, 12564 TPL_TemplateMatch)) 12565 OldTemplateParams = 12566 OldDecl->getMostRecentDecl()->getTemplateParameters(); 12567 else 12568 Invalid = true; 12569 12570 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 12571 if (!Invalid && 12572 !Context.hasSameType(OldTD->getUnderlyingType(), 12573 NewTD->getUnderlyingType())) { 12574 // FIXME: The C++0x standard does not clearly say this is ill-formed, 12575 // but we can't reasonably accept it. 12576 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 12577 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 12578 if (OldTD->getLocation().isValid()) 12579 Diag(OldTD->getLocation(), diag::note_previous_definition); 12580 Invalid = true; 12581 } 12582 } 12583 } 12584 12585 // Merge any previous default template arguments into our parameters, 12586 // and check the parameter list. 12587 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 12588 TPC_TypeAliasTemplate)) 12589 return nullptr; 12590 12591 TypeAliasTemplateDecl *NewDecl = 12592 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 12593 Name.Identifier, TemplateParams, 12594 NewTD); 12595 NewTD->setDescribedAliasTemplate(NewDecl); 12596 12597 NewDecl->setAccess(AS); 12598 12599 if (Invalid) 12600 NewDecl->setInvalidDecl(); 12601 else if (OldDecl) { 12602 NewDecl->setPreviousDecl(OldDecl); 12603 CheckRedeclarationModuleOwnership(NewDecl, OldDecl); 12604 } 12605 12606 NewND = NewDecl; 12607 } else { 12608 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { 12609 setTagNameForLinkagePurposes(TD, NewTD); 12610 handleTagNumbering(TD, S); 12611 } 12612 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 12613 NewND = NewTD; 12614 } 12615 12616 PushOnScopeChains(NewND, S); 12617 ActOnDocumentableDecl(NewND); 12618 return NewND; 12619 } 12620 12621 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 12622 SourceLocation AliasLoc, 12623 IdentifierInfo *Alias, CXXScopeSpec &SS, 12624 SourceLocation IdentLoc, 12625 IdentifierInfo *Ident) { 12626 12627 // Lookup the namespace name. 12628 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 12629 LookupParsedName(R, S, &SS); 12630 12631 if (R.isAmbiguous()) 12632 return nullptr; 12633 12634 if (R.empty()) { 12635 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 12636 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 12637 return nullptr; 12638 } 12639 } 12640 assert(!R.isAmbiguous() && !R.empty()); 12641 NamedDecl *ND = R.getRepresentativeDecl(); 12642 12643 // Check if we have a previous declaration with the same name. 12644 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName, 12645 ForVisibleRedeclaration); 12646 LookupName(PrevR, S); 12647 12648 // Check we're not shadowing a template parameter. 12649 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) { 12650 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl()); 12651 PrevR.clear(); 12652 } 12653 12654 // Filter out any other lookup result from an enclosing scope. 12655 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false, 12656 /*AllowInlineNamespace*/false); 12657 12658 // Find the previous declaration and check that we can redeclare it. 12659 NamespaceAliasDecl *Prev = nullptr; 12660 if (PrevR.isSingleResult()) { 12661 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl(); 12662 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 12663 // We already have an alias with the same name that points to the same 12664 // namespace; check that it matches. 12665 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) { 12666 Prev = AD; 12667 } else if (isVisible(PrevDecl)) { 12668 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 12669 << Alias; 12670 Diag(AD->getLocation(), diag::note_previous_namespace_alias) 12671 << AD->getNamespace(); 12672 return nullptr; 12673 } 12674 } else if (isVisible(PrevDecl)) { 12675 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl()) 12676 ? diag::err_redefinition 12677 : diag::err_redefinition_different_kind; 12678 Diag(AliasLoc, DiagID) << Alias; 12679 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 12680 return nullptr; 12681 } 12682 } 12683 12684 // The use of a nested name specifier may trigger deprecation warnings. 12685 DiagnoseUseOfDecl(ND, IdentLoc); 12686 12687 NamespaceAliasDecl *AliasDecl = 12688 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 12689 Alias, SS.getWithLocInContext(Context), 12690 IdentLoc, ND); 12691 if (Prev) 12692 AliasDecl->setPreviousDecl(Prev); 12693 12694 PushOnScopeChains(AliasDecl, S); 12695 return AliasDecl; 12696 } 12697 12698 namespace { 12699 struct SpecialMemberExceptionSpecInfo 12700 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> { 12701 SourceLocation Loc; 12702 Sema::ImplicitExceptionSpecification ExceptSpec; 12703 12704 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD, 12705 Sema::CXXSpecialMember CSM, 12706 Sema::InheritedConstructorInfo *ICI, 12707 SourceLocation Loc) 12708 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {} 12709 12710 bool visitBase(CXXBaseSpecifier *Base); 12711 bool visitField(FieldDecl *FD); 12712 12713 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 12714 unsigned Quals); 12715 12716 void visitSubobjectCall(Subobject Subobj, 12717 Sema::SpecialMemberOverloadResult SMOR); 12718 }; 12719 } 12720 12721 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) { 12722 auto *RT = Base->getType()->getAs<RecordType>(); 12723 if (!RT) 12724 return false; 12725 12726 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl()); 12727 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 12728 if (auto *BaseCtor = SMOR.getMethod()) { 12729 visitSubobjectCall(Base, BaseCtor); 12730 return false; 12731 } 12732 12733 visitClassSubobject(BaseClass, Base, 0); 12734 return false; 12735 } 12736 12737 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) { 12738 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) { 12739 Expr *E = FD->getInClassInitializer(); 12740 if (!E) 12741 // FIXME: It's a little wasteful to build and throw away a 12742 // CXXDefaultInitExpr here. 12743 // FIXME: We should have a single context note pointing at Loc, and 12744 // this location should be MD->getLocation() instead, since that's 12745 // the location where we actually use the default init expression. 12746 E = S.BuildCXXDefaultInitExpr(Loc, FD).get(); 12747 if (E) 12748 ExceptSpec.CalledExpr(E); 12749 } else if (auto *RT = S.Context.getBaseElementType(FD->getType()) 12750 ->getAs<RecordType>()) { 12751 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD, 12752 FD->getType().getCVRQualifiers()); 12753 } 12754 return false; 12755 } 12756 12757 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class, 12758 Subobject Subobj, 12759 unsigned Quals) { 12760 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 12761 bool IsMutable = Field && Field->isMutable(); 12762 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable)); 12763 } 12764 12765 void SpecialMemberExceptionSpecInfo::visitSubobjectCall( 12766 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) { 12767 // Note, if lookup fails, it doesn't matter what exception specification we 12768 // choose because the special member will be deleted. 12769 if (CXXMethodDecl *MD = SMOR.getMethod()) 12770 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD); 12771 } 12772 12773 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) { 12774 llvm::APSInt Result; 12775 ExprResult Converted = CheckConvertedConstantExpression( 12776 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool); 12777 ExplicitSpec.setExpr(Converted.get()); 12778 if (Converted.isUsable() && !Converted.get()->isValueDependent()) { 12779 ExplicitSpec.setKind(Result.getBoolValue() 12780 ? ExplicitSpecKind::ResolvedTrue 12781 : ExplicitSpecKind::ResolvedFalse); 12782 return true; 12783 } 12784 ExplicitSpec.setKind(ExplicitSpecKind::Unresolved); 12785 return false; 12786 } 12787 12788 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) { 12789 ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved); 12790 if (!ExplicitExpr->isTypeDependent()) 12791 tryResolveExplicitSpecifier(ES); 12792 return ES; 12793 } 12794 12795 static Sema::ImplicitExceptionSpecification 12796 ComputeDefaultedSpecialMemberExceptionSpec( 12797 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 12798 Sema::InheritedConstructorInfo *ICI) { 12799 ComputingExceptionSpec CES(S, MD, Loc); 12800 12801 CXXRecordDecl *ClassDecl = MD->getParent(); 12802 12803 // C++ [except.spec]p14: 12804 // An implicitly declared special member function (Clause 12) shall have an 12805 // exception-specification. [...] 12806 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation()); 12807 if (ClassDecl->isInvalidDecl()) 12808 return Info.ExceptSpec; 12809 12810 // FIXME: If this diagnostic fires, we're probably missing a check for 12811 // attempting to resolve an exception specification before it's known 12812 // at a higher level. 12813 if (S.RequireCompleteType(MD->getLocation(), 12814 S.Context.getRecordType(ClassDecl), 12815 diag::err_exception_spec_incomplete_type)) 12816 return Info.ExceptSpec; 12817 12818 // C++1z [except.spec]p7: 12819 // [Look for exceptions thrown by] a constructor selected [...] to 12820 // initialize a potentially constructed subobject, 12821 // C++1z [except.spec]p8: 12822 // The exception specification for an implicitly-declared destructor, or a 12823 // destructor without a noexcept-specifier, is potentially-throwing if and 12824 // only if any of the destructors for any of its potentially constructed 12825 // subojects is potentially throwing. 12826 // FIXME: We respect the first rule but ignore the "potentially constructed" 12827 // in the second rule to resolve a core issue (no number yet) that would have 12828 // us reject: 12829 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; }; 12830 // struct B : A {}; 12831 // struct C : B { void f(); }; 12832 // ... due to giving B::~B() a non-throwing exception specification. 12833 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases 12834 : Info.VisitAllBases); 12835 12836 return Info.ExceptSpec; 12837 } 12838 12839 namespace { 12840 /// RAII object to register a special member as being currently declared. 12841 struct DeclaringSpecialMember { 12842 Sema &S; 12843 Sema::SpecialMemberDecl D; 12844 Sema::ContextRAII SavedContext; 12845 bool WasAlreadyBeingDeclared; 12846 12847 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 12848 : S(S), D(RD, CSM), SavedContext(S, RD) { 12849 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 12850 if (WasAlreadyBeingDeclared) 12851 // This almost never happens, but if it does, ensure that our cache 12852 // doesn't contain a stale result. 12853 S.SpecialMemberCache.clear(); 12854 else { 12855 // Register a note to be produced if we encounter an error while 12856 // declaring the special member. 12857 Sema::CodeSynthesisContext Ctx; 12858 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember; 12859 // FIXME: We don't have a location to use here. Using the class's 12860 // location maintains the fiction that we declare all special members 12861 // with the class, but (1) it's not clear that lying about that helps our 12862 // users understand what's going on, and (2) there may be outer contexts 12863 // on the stack (some of which are relevant) and printing them exposes 12864 // our lies. 12865 Ctx.PointOfInstantiation = RD->getLocation(); 12866 Ctx.Entity = RD; 12867 Ctx.SpecialMember = CSM; 12868 S.pushCodeSynthesisContext(Ctx); 12869 } 12870 } 12871 ~DeclaringSpecialMember() { 12872 if (!WasAlreadyBeingDeclared) { 12873 S.SpecialMembersBeingDeclared.erase(D); 12874 S.popCodeSynthesisContext(); 12875 } 12876 } 12877 12878 /// Are we already trying to declare this special member? 12879 bool isAlreadyBeingDeclared() const { 12880 return WasAlreadyBeingDeclared; 12881 } 12882 }; 12883 } 12884 12885 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) { 12886 // Look up any existing declarations, but don't trigger declaration of all 12887 // implicit special members with this name. 12888 DeclarationName Name = FD->getDeclName(); 12889 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName, 12890 ForExternalRedeclaration); 12891 for (auto *D : FD->getParent()->lookup(Name)) 12892 if (auto *Acceptable = R.getAcceptableDecl(D)) 12893 R.addDecl(Acceptable); 12894 R.resolveKind(); 12895 R.suppressDiagnostics(); 12896 12897 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false); 12898 } 12899 12900 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem, 12901 QualType ResultTy, 12902 ArrayRef<QualType> Args) { 12903 // Build an exception specification pointing back at this constructor. 12904 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem); 12905 12906 LangAS AS = getDefaultCXXMethodAddrSpace(); 12907 if (AS != LangAS::Default) { 12908 EPI.TypeQuals.addAddressSpace(AS); 12909 } 12910 12911 auto QT = Context.getFunctionType(ResultTy, Args, EPI); 12912 SpecialMem->setType(QT); 12913 } 12914 12915 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 12916 CXXRecordDecl *ClassDecl) { 12917 // C++ [class.ctor]p5: 12918 // A default constructor for a class X is a constructor of class X 12919 // that can be called without an argument. If there is no 12920 // user-declared constructor for class X, a default constructor is 12921 // implicitly declared. An implicitly-declared default constructor 12922 // is an inline public member of its class. 12923 assert(ClassDecl->needsImplicitDefaultConstructor() && 12924 "Should not build implicit default constructor!"); 12925 12926 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 12927 if (DSM.isAlreadyBeingDeclared()) 12928 return nullptr; 12929 12930 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12931 CXXDefaultConstructor, 12932 false); 12933 12934 // Create the actual constructor declaration. 12935 CanQualType ClassType 12936 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 12937 SourceLocation ClassLoc = ClassDecl->getLocation(); 12938 DeclarationName Name 12939 = Context.DeclarationNames.getCXXConstructorName(ClassType); 12940 DeclarationNameInfo NameInfo(Name, ClassLoc); 12941 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 12942 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(), 12943 /*TInfo=*/nullptr, ExplicitSpecifier(), 12944 /*isInline=*/true, /*isImplicitlyDeclared=*/true, 12945 Constexpr ? CSK_constexpr : CSK_unspecified); 12946 DefaultCon->setAccess(AS_public); 12947 DefaultCon->setDefaulted(); 12948 12949 if (getLangOpts().CUDA) { 12950 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 12951 DefaultCon, 12952 /* ConstRHS */ false, 12953 /* Diagnose */ false); 12954 } 12955 12956 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None); 12957 12958 // We don't need to use SpecialMemberIsTrivial here; triviality for default 12959 // constructors is easy to compute. 12960 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 12961 12962 // Note that we have declared this constructor. 12963 ++getASTContext().NumImplicitDefaultConstructorsDeclared; 12964 12965 Scope *S = getScopeForContext(ClassDecl); 12966 CheckImplicitSpecialMemberDeclaration(S, DefaultCon); 12967 12968 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 12969 SetDeclDeleted(DefaultCon, ClassLoc); 12970 12971 if (S) 12972 PushOnScopeChains(DefaultCon, S, false); 12973 ClassDecl->addDecl(DefaultCon); 12974 12975 return DefaultCon; 12976 } 12977 12978 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 12979 CXXConstructorDecl *Constructor) { 12980 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 12981 !Constructor->doesThisDeclarationHaveABody() && 12982 !Constructor->isDeleted()) && 12983 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 12984 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 12985 return; 12986 12987 CXXRecordDecl *ClassDecl = Constructor->getParent(); 12988 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 12989 12990 SynthesizedFunctionScope Scope(*this, Constructor); 12991 12992 // The exception specification is needed because we are defining the 12993 // function. 12994 ResolveExceptionSpec(CurrentLocation, 12995 Constructor->getType()->castAs<FunctionProtoType>()); 12996 MarkVTableUsed(CurrentLocation, ClassDecl); 12997 12998 // Add a context note for diagnostics produced after this point. 12999 Scope.addContextNote(CurrentLocation); 13000 13001 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) { 13002 Constructor->setInvalidDecl(); 13003 return; 13004 } 13005 13006 SourceLocation Loc = Constructor->getEndLoc().isValid() 13007 ? Constructor->getEndLoc() 13008 : Constructor->getLocation(); 13009 Constructor->setBody(new (Context) CompoundStmt(Loc)); 13010 Constructor->markUsed(Context); 13011 13012 if (ASTMutationListener *L = getASTMutationListener()) { 13013 L->CompletedImplicitDefinition(Constructor); 13014 } 13015 13016 DiagnoseUninitializedFields(*this, Constructor); 13017 } 13018 13019 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 13020 // Perform any delayed checks on exception specifications. 13021 CheckDelayedMemberExceptionSpecs(); 13022 } 13023 13024 /// Find or create the fake constructor we synthesize to model constructing an 13025 /// object of a derived class via a constructor of a base class. 13026 CXXConstructorDecl * 13027 Sema::findInheritingConstructor(SourceLocation Loc, 13028 CXXConstructorDecl *BaseCtor, 13029 ConstructorUsingShadowDecl *Shadow) { 13030 CXXRecordDecl *Derived = Shadow->getParent(); 13031 SourceLocation UsingLoc = Shadow->getLocation(); 13032 13033 // FIXME: Add a new kind of DeclarationName for an inherited constructor. 13034 // For now we use the name of the base class constructor as a member of the 13035 // derived class to indicate a (fake) inherited constructor name. 13036 DeclarationName Name = BaseCtor->getDeclName(); 13037 13038 // Check to see if we already have a fake constructor for this inherited 13039 // constructor call. 13040 for (NamedDecl *Ctor : Derived->lookup(Name)) 13041 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor) 13042 ->getInheritedConstructor() 13043 .getConstructor(), 13044 BaseCtor)) 13045 return cast<CXXConstructorDecl>(Ctor); 13046 13047 DeclarationNameInfo NameInfo(Name, UsingLoc); 13048 TypeSourceInfo *TInfo = 13049 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc); 13050 FunctionProtoTypeLoc ProtoLoc = 13051 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 13052 13053 // Check the inherited constructor is valid and find the list of base classes 13054 // from which it was inherited. 13055 InheritedConstructorInfo ICI(*this, Loc, Shadow); 13056 13057 bool Constexpr = 13058 BaseCtor->isConstexpr() && 13059 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor, 13060 false, BaseCtor, &ICI); 13061 13062 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 13063 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo, 13064 BaseCtor->getExplicitSpecifier(), /*isInline=*/true, 13065 /*isImplicitlyDeclared=*/true, 13066 Constexpr ? BaseCtor->getConstexprKind() : CSK_unspecified, 13067 InheritedConstructor(Shadow, BaseCtor), 13068 BaseCtor->getTrailingRequiresClause()); 13069 if (Shadow->isInvalidDecl()) 13070 DerivedCtor->setInvalidDecl(); 13071 13072 // Build an unevaluated exception specification for this fake constructor. 13073 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>(); 13074 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 13075 EPI.ExceptionSpec.Type = EST_Unevaluated; 13076 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 13077 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 13078 FPT->getParamTypes(), EPI)); 13079 13080 // Build the parameter declarations. 13081 SmallVector<ParmVarDecl *, 16> ParamDecls; 13082 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 13083 TypeSourceInfo *TInfo = 13084 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 13085 ParmVarDecl *PD = ParmVarDecl::Create( 13086 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 13087 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr); 13088 PD->setScopeInfo(0, I); 13089 PD->setImplicit(); 13090 // Ensure attributes are propagated onto parameters (this matters for 13091 // format, pass_object_size, ...). 13092 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I)); 13093 ParamDecls.push_back(PD); 13094 ProtoLoc.setParam(I, PD); 13095 } 13096 13097 // Set up the new constructor. 13098 assert(!BaseCtor->isDeleted() && "should not use deleted constructor"); 13099 DerivedCtor->setAccess(BaseCtor->getAccess()); 13100 DerivedCtor->setParams(ParamDecls); 13101 Derived->addDecl(DerivedCtor); 13102 13103 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI)) 13104 SetDeclDeleted(DerivedCtor, UsingLoc); 13105 13106 return DerivedCtor; 13107 } 13108 13109 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) { 13110 InheritedConstructorInfo ICI(*this, Ctor->getLocation(), 13111 Ctor->getInheritedConstructor().getShadowDecl()); 13112 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI, 13113 /*Diagnose*/true); 13114 } 13115 13116 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 13117 CXXConstructorDecl *Constructor) { 13118 CXXRecordDecl *ClassDecl = Constructor->getParent(); 13119 assert(Constructor->getInheritedConstructor() && 13120 !Constructor->doesThisDeclarationHaveABody() && 13121 !Constructor->isDeleted()); 13122 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 13123 return; 13124 13125 // Initializations are performed "as if by a defaulted default constructor", 13126 // so enter the appropriate scope. 13127 SynthesizedFunctionScope Scope(*this, Constructor); 13128 13129 // The exception specification is needed because we are defining the 13130 // function. 13131 ResolveExceptionSpec(CurrentLocation, 13132 Constructor->getType()->castAs<FunctionProtoType>()); 13133 MarkVTableUsed(CurrentLocation, ClassDecl); 13134 13135 // Add a context note for diagnostics produced after this point. 13136 Scope.addContextNote(CurrentLocation); 13137 13138 ConstructorUsingShadowDecl *Shadow = 13139 Constructor->getInheritedConstructor().getShadowDecl(); 13140 CXXConstructorDecl *InheritedCtor = 13141 Constructor->getInheritedConstructor().getConstructor(); 13142 13143 // [class.inhctor.init]p1: 13144 // initialization proceeds as if a defaulted default constructor is used to 13145 // initialize the D object and each base class subobject from which the 13146 // constructor was inherited 13147 13148 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow); 13149 CXXRecordDecl *RD = Shadow->getParent(); 13150 SourceLocation InitLoc = Shadow->getLocation(); 13151 13152 // Build explicit initializers for all base classes from which the 13153 // constructor was inherited. 13154 SmallVector<CXXCtorInitializer*, 8> Inits; 13155 for (bool VBase : {false, true}) { 13156 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) { 13157 if (B.isVirtual() != VBase) 13158 continue; 13159 13160 auto *BaseRD = B.getType()->getAsCXXRecordDecl(); 13161 if (!BaseRD) 13162 continue; 13163 13164 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor); 13165 if (!BaseCtor.first) 13166 continue; 13167 13168 MarkFunctionReferenced(CurrentLocation, BaseCtor.first); 13169 ExprResult Init = new (Context) CXXInheritedCtorInitExpr( 13170 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second); 13171 13172 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc); 13173 Inits.push_back(new (Context) CXXCtorInitializer( 13174 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc, 13175 SourceLocation())); 13176 } 13177 } 13178 13179 // We now proceed as if for a defaulted default constructor, with the relevant 13180 // initializers replaced. 13181 13182 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) { 13183 Constructor->setInvalidDecl(); 13184 return; 13185 } 13186 13187 Constructor->setBody(new (Context) CompoundStmt(InitLoc)); 13188 Constructor->markUsed(Context); 13189 13190 if (ASTMutationListener *L = getASTMutationListener()) { 13191 L->CompletedImplicitDefinition(Constructor); 13192 } 13193 13194 DiagnoseUninitializedFields(*this, Constructor); 13195 } 13196 13197 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 13198 // C++ [class.dtor]p2: 13199 // If a class has no user-declared destructor, a destructor is 13200 // declared implicitly. An implicitly-declared destructor is an 13201 // inline public member of its class. 13202 assert(ClassDecl->needsImplicitDestructor()); 13203 13204 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 13205 if (DSM.isAlreadyBeingDeclared()) 13206 return nullptr; 13207 13208 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 13209 CXXDestructor, 13210 false); 13211 13212 // Create the actual destructor declaration. 13213 CanQualType ClassType 13214 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 13215 SourceLocation ClassLoc = ClassDecl->getLocation(); 13216 DeclarationName Name 13217 = Context.DeclarationNames.getCXXDestructorName(ClassType); 13218 DeclarationNameInfo NameInfo(Name, ClassLoc); 13219 CXXDestructorDecl *Destructor = 13220 CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 13221 QualType(), nullptr, /*isInline=*/true, 13222 /*isImplicitlyDeclared=*/true, 13223 Constexpr ? CSK_constexpr : CSK_unspecified); 13224 Destructor->setAccess(AS_public); 13225 Destructor->setDefaulted(); 13226 13227 if (getLangOpts().CUDA) { 13228 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 13229 Destructor, 13230 /* ConstRHS */ false, 13231 /* Diagnose */ false); 13232 } 13233 13234 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None); 13235 13236 // We don't need to use SpecialMemberIsTrivial here; triviality for 13237 // destructors is easy to compute. 13238 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 13239 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() || 13240 ClassDecl->hasTrivialDestructorForCall()); 13241 13242 // Note that we have declared this destructor. 13243 ++getASTContext().NumImplicitDestructorsDeclared; 13244 13245 Scope *S = getScopeForContext(ClassDecl); 13246 CheckImplicitSpecialMemberDeclaration(S, Destructor); 13247 13248 // We can't check whether an implicit destructor is deleted before we complete 13249 // the definition of the class, because its validity depends on the alignment 13250 // of the class. We'll check this from ActOnFields once the class is complete. 13251 if (ClassDecl->isCompleteDefinition() && 13252 ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 13253 SetDeclDeleted(Destructor, ClassLoc); 13254 13255 // Introduce this destructor into its scope. 13256 if (S) 13257 PushOnScopeChains(Destructor, S, false); 13258 ClassDecl->addDecl(Destructor); 13259 13260 return Destructor; 13261 } 13262 13263 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 13264 CXXDestructorDecl *Destructor) { 13265 assert((Destructor->isDefaulted() && 13266 !Destructor->doesThisDeclarationHaveABody() && 13267 !Destructor->isDeleted()) && 13268 "DefineImplicitDestructor - call it for implicit default dtor"); 13269 if (Destructor->willHaveBody() || Destructor->isInvalidDecl()) 13270 return; 13271 13272 CXXRecordDecl *ClassDecl = Destructor->getParent(); 13273 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 13274 13275 SynthesizedFunctionScope Scope(*this, Destructor); 13276 13277 // The exception specification is needed because we are defining the 13278 // function. 13279 ResolveExceptionSpec(CurrentLocation, 13280 Destructor->getType()->castAs<FunctionProtoType>()); 13281 MarkVTableUsed(CurrentLocation, ClassDecl); 13282 13283 // Add a context note for diagnostics produced after this point. 13284 Scope.addContextNote(CurrentLocation); 13285 13286 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 13287 Destructor->getParent()); 13288 13289 if (CheckDestructor(Destructor)) { 13290 Destructor->setInvalidDecl(); 13291 return; 13292 } 13293 13294 SourceLocation Loc = Destructor->getEndLoc().isValid() 13295 ? Destructor->getEndLoc() 13296 : Destructor->getLocation(); 13297 Destructor->setBody(new (Context) CompoundStmt(Loc)); 13298 Destructor->markUsed(Context); 13299 13300 if (ASTMutationListener *L = getASTMutationListener()) { 13301 L->CompletedImplicitDefinition(Destructor); 13302 } 13303 } 13304 13305 void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation, 13306 CXXDestructorDecl *Destructor) { 13307 if (Destructor->isInvalidDecl()) 13308 return; 13309 13310 CXXRecordDecl *ClassDecl = Destructor->getParent(); 13311 assert(Context.getTargetInfo().getCXXABI().isMicrosoft() && 13312 "implicit complete dtors unneeded outside MS ABI"); 13313 assert(ClassDecl->getNumVBases() > 0 && 13314 "complete dtor only exists for classes with vbases"); 13315 13316 SynthesizedFunctionScope Scope(*this, Destructor); 13317 13318 // Add a context note for diagnostics produced after this point. 13319 Scope.addContextNote(CurrentLocation); 13320 13321 MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl); 13322 } 13323 13324 /// Perform any semantic analysis which needs to be delayed until all 13325 /// pending class member declarations have been parsed. 13326 void Sema::ActOnFinishCXXMemberDecls() { 13327 // If the context is an invalid C++ class, just suppress these checks. 13328 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 13329 if (Record->isInvalidDecl()) { 13330 DelayedOverridingExceptionSpecChecks.clear(); 13331 DelayedEquivalentExceptionSpecChecks.clear(); 13332 return; 13333 } 13334 checkForMultipleExportedDefaultConstructors(*this, Record); 13335 } 13336 } 13337 13338 void Sema::ActOnFinishCXXNonNestedClass() { 13339 referenceDLLExportedClassMethods(); 13340 13341 if (!DelayedDllExportMemberFunctions.empty()) { 13342 SmallVector<CXXMethodDecl*, 4> WorkList; 13343 std::swap(DelayedDllExportMemberFunctions, WorkList); 13344 for (CXXMethodDecl *M : WorkList) { 13345 DefineDefaultedFunction(*this, M, M->getLocation()); 13346 13347 // Pass the method to the consumer to get emitted. This is not necessary 13348 // for explicit instantiation definitions, as they will get emitted 13349 // anyway. 13350 if (M->getParent()->getTemplateSpecializationKind() != 13351 TSK_ExplicitInstantiationDefinition) 13352 ActOnFinishInlineFunctionDef(M); 13353 } 13354 } 13355 } 13356 13357 void Sema::referenceDLLExportedClassMethods() { 13358 if (!DelayedDllExportClasses.empty()) { 13359 // Calling ReferenceDllExportedMembers might cause the current function to 13360 // be called again, so use a local copy of DelayedDllExportClasses. 13361 SmallVector<CXXRecordDecl *, 4> WorkList; 13362 std::swap(DelayedDllExportClasses, WorkList); 13363 for (CXXRecordDecl *Class : WorkList) 13364 ReferenceDllExportedMembers(*this, Class); 13365 } 13366 } 13367 13368 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) { 13369 assert(getLangOpts().CPlusPlus11 && 13370 "adjusting dtor exception specs was introduced in c++11"); 13371 13372 if (Destructor->isDependentContext()) 13373 return; 13374 13375 // C++11 [class.dtor]p3: 13376 // A declaration of a destructor that does not have an exception- 13377 // specification is implicitly considered to have the same exception- 13378 // specification as an implicit declaration. 13379 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>(); 13380 if (DtorType->hasExceptionSpec()) 13381 return; 13382 13383 // Replace the destructor's type, building off the existing one. Fortunately, 13384 // the only thing of interest in the destructor type is its extended info. 13385 // The return and arguments are fixed. 13386 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 13387 EPI.ExceptionSpec.Type = EST_Unevaluated; 13388 EPI.ExceptionSpec.SourceDecl = Destructor; 13389 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 13390 13391 // FIXME: If the destructor has a body that could throw, and the newly created 13392 // spec doesn't allow exceptions, we should emit a warning, because this 13393 // change in behavior can break conforming C++03 programs at runtime. 13394 // However, we don't have a body or an exception specification yet, so it 13395 // needs to be done somewhere else. 13396 } 13397 13398 namespace { 13399 /// An abstract base class for all helper classes used in building the 13400 // copy/move operators. These classes serve as factory functions and help us 13401 // avoid using the same Expr* in the AST twice. 13402 class ExprBuilder { 13403 ExprBuilder(const ExprBuilder&) = delete; 13404 ExprBuilder &operator=(const ExprBuilder&) = delete; 13405 13406 protected: 13407 static Expr *assertNotNull(Expr *E) { 13408 assert(E && "Expression construction must not fail."); 13409 return E; 13410 } 13411 13412 public: 13413 ExprBuilder() {} 13414 virtual ~ExprBuilder() {} 13415 13416 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 13417 }; 13418 13419 class RefBuilder: public ExprBuilder { 13420 VarDecl *Var; 13421 QualType VarType; 13422 13423 public: 13424 Expr *build(Sema &S, SourceLocation Loc) const override { 13425 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc)); 13426 } 13427 13428 RefBuilder(VarDecl *Var, QualType VarType) 13429 : Var(Var), VarType(VarType) {} 13430 }; 13431 13432 class ThisBuilder: public ExprBuilder { 13433 public: 13434 Expr *build(Sema &S, SourceLocation Loc) const override { 13435 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 13436 } 13437 }; 13438 13439 class CastBuilder: public ExprBuilder { 13440 const ExprBuilder &Builder; 13441 QualType Type; 13442 ExprValueKind Kind; 13443 const CXXCastPath &Path; 13444 13445 public: 13446 Expr *build(Sema &S, SourceLocation Loc) const override { 13447 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 13448 CK_UncheckedDerivedToBase, Kind, 13449 &Path).get()); 13450 } 13451 13452 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 13453 const CXXCastPath &Path) 13454 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 13455 }; 13456 13457 class DerefBuilder: public ExprBuilder { 13458 const ExprBuilder &Builder; 13459 13460 public: 13461 Expr *build(Sema &S, SourceLocation Loc) const override { 13462 return assertNotNull( 13463 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 13464 } 13465 13466 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13467 }; 13468 13469 class MemberBuilder: public ExprBuilder { 13470 const ExprBuilder &Builder; 13471 QualType Type; 13472 CXXScopeSpec SS; 13473 bool IsArrow; 13474 LookupResult &MemberLookup; 13475 13476 public: 13477 Expr *build(Sema &S, SourceLocation Loc) const override { 13478 return assertNotNull(S.BuildMemberReferenceExpr( 13479 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 13480 nullptr, MemberLookup, nullptr, nullptr).get()); 13481 } 13482 13483 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 13484 LookupResult &MemberLookup) 13485 : Builder(Builder), Type(Type), IsArrow(IsArrow), 13486 MemberLookup(MemberLookup) {} 13487 }; 13488 13489 class MoveCastBuilder: public ExprBuilder { 13490 const ExprBuilder &Builder; 13491 13492 public: 13493 Expr *build(Sema &S, SourceLocation Loc) const override { 13494 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 13495 } 13496 13497 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13498 }; 13499 13500 class LvalueConvBuilder: public ExprBuilder { 13501 const ExprBuilder &Builder; 13502 13503 public: 13504 Expr *build(Sema &S, SourceLocation Loc) const override { 13505 return assertNotNull( 13506 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 13507 } 13508 13509 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13510 }; 13511 13512 class SubscriptBuilder: public ExprBuilder { 13513 const ExprBuilder &Base; 13514 const ExprBuilder &Index; 13515 13516 public: 13517 Expr *build(Sema &S, SourceLocation Loc) const override { 13518 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 13519 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 13520 } 13521 13522 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 13523 : Base(Base), Index(Index) {} 13524 }; 13525 13526 } // end anonymous namespace 13527 13528 /// When generating a defaulted copy or move assignment operator, if a field 13529 /// should be copied with __builtin_memcpy rather than via explicit assignments, 13530 /// do so. This optimization only applies for arrays of scalars, and for arrays 13531 /// of class type where the selected copy/move-assignment operator is trivial. 13532 static StmtResult 13533 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 13534 const ExprBuilder &ToB, const ExprBuilder &FromB) { 13535 // Compute the size of the memory buffer to be copied. 13536 QualType SizeType = S.Context.getSizeType(); 13537 llvm::APInt Size(S.Context.getTypeSize(SizeType), 13538 S.Context.getTypeSizeInChars(T).getQuantity()); 13539 13540 // Take the address of the field references for "from" and "to". We 13541 // directly construct UnaryOperators here because semantic analysis 13542 // does not permit us to take the address of an xvalue. 13543 Expr *From = FromB.build(S, Loc); 13544 From = UnaryOperator::Create( 13545 S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()), 13546 VK_RValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides()); 13547 Expr *To = ToB.build(S, Loc); 13548 To = UnaryOperator::Create( 13549 S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()), 13550 VK_RValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides()); 13551 13552 const Type *E = T->getBaseElementTypeUnsafe(); 13553 bool NeedsCollectableMemCpy = 13554 E->isRecordType() && 13555 E->castAs<RecordType>()->getDecl()->hasObjectMember(); 13556 13557 // Create a reference to the __builtin_objc_memmove_collectable function 13558 StringRef MemCpyName = NeedsCollectableMemCpy ? 13559 "__builtin_objc_memmove_collectable" : 13560 "__builtin_memcpy"; 13561 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 13562 Sema::LookupOrdinaryName); 13563 S.LookupName(R, S.TUScope, true); 13564 13565 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 13566 if (!MemCpy) 13567 // Something went horribly wrong earlier, and we will have complained 13568 // about it. 13569 return StmtError(); 13570 13571 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 13572 VK_RValue, Loc, nullptr); 13573 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 13574 13575 Expr *CallArgs[] = { 13576 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 13577 }; 13578 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 13579 Loc, CallArgs, Loc); 13580 13581 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 13582 return Call.getAs<Stmt>(); 13583 } 13584 13585 /// Builds a statement that copies/moves the given entity from \p From to 13586 /// \c To. 13587 /// 13588 /// This routine is used to copy/move the members of a class with an 13589 /// implicitly-declared copy/move assignment operator. When the entities being 13590 /// copied are arrays, this routine builds for loops to copy them. 13591 /// 13592 /// \param S The Sema object used for type-checking. 13593 /// 13594 /// \param Loc The location where the implicit copy/move is being generated. 13595 /// 13596 /// \param T The type of the expressions being copied/moved. Both expressions 13597 /// must have this type. 13598 /// 13599 /// \param To The expression we are copying/moving to. 13600 /// 13601 /// \param From The expression we are copying/moving from. 13602 /// 13603 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 13604 /// Otherwise, it's a non-static member subobject. 13605 /// 13606 /// \param Copying Whether we're copying or moving. 13607 /// 13608 /// \param Depth Internal parameter recording the depth of the recursion. 13609 /// 13610 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 13611 /// if a memcpy should be used instead. 13612 static StmtResult 13613 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 13614 const ExprBuilder &To, const ExprBuilder &From, 13615 bool CopyingBaseSubobject, bool Copying, 13616 unsigned Depth = 0) { 13617 // C++11 [class.copy]p28: 13618 // Each subobject is assigned in the manner appropriate to its type: 13619 // 13620 // - if the subobject is of class type, as if by a call to operator= with 13621 // the subobject as the object expression and the corresponding 13622 // subobject of x as a single function argument (as if by explicit 13623 // qualification; that is, ignoring any possible virtual overriding 13624 // functions in more derived classes); 13625 // 13626 // C++03 [class.copy]p13: 13627 // - if the subobject is of class type, the copy assignment operator for 13628 // the class is used (as if by explicit qualification; that is, 13629 // ignoring any possible virtual overriding functions in more derived 13630 // classes); 13631 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 13632 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 13633 13634 // Look for operator=. 13635 DeclarationName Name 13636 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 13637 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 13638 S.LookupQualifiedName(OpLookup, ClassDecl, false); 13639 13640 // Prior to C++11, filter out any result that isn't a copy/move-assignment 13641 // operator. 13642 if (!S.getLangOpts().CPlusPlus11) { 13643 LookupResult::Filter F = OpLookup.makeFilter(); 13644 while (F.hasNext()) { 13645 NamedDecl *D = F.next(); 13646 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 13647 if (Method->isCopyAssignmentOperator() || 13648 (!Copying && Method->isMoveAssignmentOperator())) 13649 continue; 13650 13651 F.erase(); 13652 } 13653 F.done(); 13654 } 13655 13656 // Suppress the protected check (C++ [class.protected]) for each of the 13657 // assignment operators we found. This strange dance is required when 13658 // we're assigning via a base classes's copy-assignment operator. To 13659 // ensure that we're getting the right base class subobject (without 13660 // ambiguities), we need to cast "this" to that subobject type; to 13661 // ensure that we don't go through the virtual call mechanism, we need 13662 // to qualify the operator= name with the base class (see below). However, 13663 // this means that if the base class has a protected copy assignment 13664 // operator, the protected member access check will fail. So, we 13665 // rewrite "protected" access to "public" access in this case, since we 13666 // know by construction that we're calling from a derived class. 13667 if (CopyingBaseSubobject) { 13668 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 13669 L != LEnd; ++L) { 13670 if (L.getAccess() == AS_protected) 13671 L.setAccess(AS_public); 13672 } 13673 } 13674 13675 // Create the nested-name-specifier that will be used to qualify the 13676 // reference to operator=; this is required to suppress the virtual 13677 // call mechanism. 13678 CXXScopeSpec SS; 13679 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 13680 SS.MakeTrivial(S.Context, 13681 NestedNameSpecifier::Create(S.Context, nullptr, false, 13682 CanonicalT), 13683 Loc); 13684 13685 // Create the reference to operator=. 13686 ExprResult OpEqualRef 13687 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false, 13688 SS, /*TemplateKWLoc=*/SourceLocation(), 13689 /*FirstQualifierInScope=*/nullptr, 13690 OpLookup, 13691 /*TemplateArgs=*/nullptr, /*S*/nullptr, 13692 /*SuppressQualifierCheck=*/true); 13693 if (OpEqualRef.isInvalid()) 13694 return StmtError(); 13695 13696 // Build the call to the assignment operator. 13697 13698 Expr *FromInst = From.build(S, Loc); 13699 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 13700 OpEqualRef.getAs<Expr>(), 13701 Loc, FromInst, Loc); 13702 if (Call.isInvalid()) 13703 return StmtError(); 13704 13705 // If we built a call to a trivial 'operator=' while copying an array, 13706 // bail out. We'll replace the whole shebang with a memcpy. 13707 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 13708 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 13709 return StmtResult((Stmt*)nullptr); 13710 13711 // Convert to an expression-statement, and clean up any produced 13712 // temporaries. 13713 return S.ActOnExprStmt(Call); 13714 } 13715 13716 // - if the subobject is of scalar type, the built-in assignment 13717 // operator is used. 13718 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 13719 if (!ArrayTy) { 13720 ExprResult Assignment = S.CreateBuiltinBinOp( 13721 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 13722 if (Assignment.isInvalid()) 13723 return StmtError(); 13724 return S.ActOnExprStmt(Assignment); 13725 } 13726 13727 // - if the subobject is an array, each element is assigned, in the 13728 // manner appropriate to the element type; 13729 13730 // Construct a loop over the array bounds, e.g., 13731 // 13732 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 13733 // 13734 // that will copy each of the array elements. 13735 QualType SizeType = S.Context.getSizeType(); 13736 13737 // Create the iteration variable. 13738 IdentifierInfo *IterationVarName = nullptr; 13739 { 13740 SmallString<8> Str; 13741 llvm::raw_svector_ostream OS(Str); 13742 OS << "__i" << Depth; 13743 IterationVarName = &S.Context.Idents.get(OS.str()); 13744 } 13745 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 13746 IterationVarName, SizeType, 13747 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 13748 SC_None); 13749 13750 // Initialize the iteration variable to zero. 13751 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 13752 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 13753 13754 // Creates a reference to the iteration variable. 13755 RefBuilder IterationVarRef(IterationVar, SizeType); 13756 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 13757 13758 // Create the DeclStmt that holds the iteration variable. 13759 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 13760 13761 // Subscript the "from" and "to" expressions with the iteration variable. 13762 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 13763 MoveCastBuilder FromIndexMove(FromIndexCopy); 13764 const ExprBuilder *FromIndex; 13765 if (Copying) 13766 FromIndex = &FromIndexCopy; 13767 else 13768 FromIndex = &FromIndexMove; 13769 13770 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 13771 13772 // Build the copy/move for an individual element of the array. 13773 StmtResult Copy = 13774 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 13775 ToIndex, *FromIndex, CopyingBaseSubobject, 13776 Copying, Depth + 1); 13777 // Bail out if copying fails or if we determined that we should use memcpy. 13778 if (Copy.isInvalid() || !Copy.get()) 13779 return Copy; 13780 13781 // Create the comparison against the array bound. 13782 llvm::APInt Upper 13783 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 13784 Expr *Comparison = BinaryOperator::Create( 13785 S.Context, IterationVarRefRVal.build(S, Loc), 13786 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE, 13787 S.Context.BoolTy, VK_RValue, OK_Ordinary, Loc, S.CurFPFeatureOverrides()); 13788 13789 // Create the pre-increment of the iteration variable. We can determine 13790 // whether the increment will overflow based on the value of the array 13791 // bound. 13792 Expr *Increment = UnaryOperator::Create( 13793 S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue, 13794 OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides()); 13795 13796 // Construct the loop that copies all elements of this array. 13797 return S.ActOnForStmt( 13798 Loc, Loc, InitStmt, 13799 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean), 13800 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get()); 13801 } 13802 13803 static StmtResult 13804 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 13805 const ExprBuilder &To, const ExprBuilder &From, 13806 bool CopyingBaseSubobject, bool Copying) { 13807 // Maybe we should use a memcpy? 13808 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 13809 T.isTriviallyCopyableType(S.Context)) 13810 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 13811 13812 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 13813 CopyingBaseSubobject, 13814 Copying, 0)); 13815 13816 // If we ended up picking a trivial assignment operator for an array of a 13817 // non-trivially-copyable class type, just emit a memcpy. 13818 if (!Result.isInvalid() && !Result.get()) 13819 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 13820 13821 return Result; 13822 } 13823 13824 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 13825 // Note: The following rules are largely analoguous to the copy 13826 // constructor rules. Note that virtual bases are not taken into account 13827 // for determining the argument type of the operator. Note also that 13828 // operators taking an object instead of a reference are allowed. 13829 assert(ClassDecl->needsImplicitCopyAssignment()); 13830 13831 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 13832 if (DSM.isAlreadyBeingDeclared()) 13833 return nullptr; 13834 13835 QualType ArgType = Context.getTypeDeclType(ClassDecl); 13836 LangAS AS = getDefaultCXXMethodAddrSpace(); 13837 if (AS != LangAS::Default) 13838 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 13839 QualType RetType = Context.getLValueReferenceType(ArgType); 13840 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 13841 if (Const) 13842 ArgType = ArgType.withConst(); 13843 13844 ArgType = Context.getLValueReferenceType(ArgType); 13845 13846 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 13847 CXXCopyAssignment, 13848 Const); 13849 13850 // An implicitly-declared copy assignment operator is an inline public 13851 // member of its class. 13852 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 13853 SourceLocation ClassLoc = ClassDecl->getLocation(); 13854 DeclarationNameInfo NameInfo(Name, ClassLoc); 13855 CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create( 13856 Context, ClassDecl, ClassLoc, NameInfo, QualType(), 13857 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 13858 /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified, 13859 SourceLocation()); 13860 CopyAssignment->setAccess(AS_public); 13861 CopyAssignment->setDefaulted(); 13862 CopyAssignment->setImplicit(); 13863 13864 if (getLangOpts().CUDA) { 13865 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 13866 CopyAssignment, 13867 /* ConstRHS */ Const, 13868 /* Diagnose */ false); 13869 } 13870 13871 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType); 13872 13873 // Add the parameter to the operator. 13874 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 13875 ClassLoc, ClassLoc, 13876 /*Id=*/nullptr, ArgType, 13877 /*TInfo=*/nullptr, SC_None, 13878 nullptr); 13879 CopyAssignment->setParams(FromParam); 13880 13881 CopyAssignment->setTrivial( 13882 ClassDecl->needsOverloadResolutionForCopyAssignment() 13883 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 13884 : ClassDecl->hasTrivialCopyAssignment()); 13885 13886 // Note that we have added this copy-assignment operator. 13887 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared; 13888 13889 Scope *S = getScopeForContext(ClassDecl); 13890 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment); 13891 13892 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) { 13893 ClassDecl->setImplicitCopyAssignmentIsDeleted(); 13894 SetDeclDeleted(CopyAssignment, ClassLoc); 13895 } 13896 13897 if (S) 13898 PushOnScopeChains(CopyAssignment, S, false); 13899 ClassDecl->addDecl(CopyAssignment); 13900 13901 return CopyAssignment; 13902 } 13903 13904 /// Diagnose an implicit copy operation for a class which is odr-used, but 13905 /// which is deprecated because the class has a user-declared copy constructor, 13906 /// copy assignment operator, or destructor. 13907 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) { 13908 assert(CopyOp->isImplicit()); 13909 13910 CXXRecordDecl *RD = CopyOp->getParent(); 13911 CXXMethodDecl *UserDeclaredOperation = nullptr; 13912 13913 // In Microsoft mode, assignment operations don't affect constructors and 13914 // vice versa. 13915 if (RD->hasUserDeclaredDestructor()) { 13916 UserDeclaredOperation = RD->getDestructor(); 13917 } else if (!isa<CXXConstructorDecl>(CopyOp) && 13918 RD->hasUserDeclaredCopyConstructor() && 13919 !S.getLangOpts().MSVCCompat) { 13920 // Find any user-declared copy constructor. 13921 for (auto *I : RD->ctors()) { 13922 if (I->isCopyConstructor()) { 13923 UserDeclaredOperation = I; 13924 break; 13925 } 13926 } 13927 assert(UserDeclaredOperation); 13928 } else if (isa<CXXConstructorDecl>(CopyOp) && 13929 RD->hasUserDeclaredCopyAssignment() && 13930 !S.getLangOpts().MSVCCompat) { 13931 // Find any user-declared move assignment operator. 13932 for (auto *I : RD->methods()) { 13933 if (I->isCopyAssignmentOperator()) { 13934 UserDeclaredOperation = I; 13935 break; 13936 } 13937 } 13938 assert(UserDeclaredOperation); 13939 } 13940 13941 if (UserDeclaredOperation && UserDeclaredOperation->isUserProvided()) { 13942 S.Diag(UserDeclaredOperation->getLocation(), 13943 isa<CXXDestructorDecl>(UserDeclaredOperation) 13944 ? diag::warn_deprecated_copy_dtor_operation 13945 : diag::warn_deprecated_copy_operation) 13946 << RD << /*copy assignment*/ !isa<CXXConstructorDecl>(CopyOp); 13947 } 13948 } 13949 13950 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 13951 CXXMethodDecl *CopyAssignOperator) { 13952 assert((CopyAssignOperator->isDefaulted() && 13953 CopyAssignOperator->isOverloadedOperator() && 13954 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 13955 !CopyAssignOperator->doesThisDeclarationHaveABody() && 13956 !CopyAssignOperator->isDeleted()) && 13957 "DefineImplicitCopyAssignment called for wrong function"); 13958 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl()) 13959 return; 13960 13961 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 13962 if (ClassDecl->isInvalidDecl()) { 13963 CopyAssignOperator->setInvalidDecl(); 13964 return; 13965 } 13966 13967 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 13968 13969 // The exception specification is needed because we are defining the 13970 // function. 13971 ResolveExceptionSpec(CurrentLocation, 13972 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 13973 13974 // Add a context note for diagnostics produced after this point. 13975 Scope.addContextNote(CurrentLocation); 13976 13977 // C++11 [class.copy]p18: 13978 // The [definition of an implicitly declared copy assignment operator] is 13979 // deprecated if the class has a user-declared copy constructor or a 13980 // user-declared destructor. 13981 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 13982 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator); 13983 13984 // C++0x [class.copy]p30: 13985 // The implicitly-defined or explicitly-defaulted copy assignment operator 13986 // for a non-union class X performs memberwise copy assignment of its 13987 // subobjects. The direct base classes of X are assigned first, in the 13988 // order of their declaration in the base-specifier-list, and then the 13989 // immediate non-static data members of X are assigned, in the order in 13990 // which they were declared in the class definition. 13991 13992 // The statements that form the synthesized function body. 13993 SmallVector<Stmt*, 8> Statements; 13994 13995 // The parameter for the "other" object, which we are copying from. 13996 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 13997 Qualifiers OtherQuals = Other->getType().getQualifiers(); 13998 QualType OtherRefType = Other->getType(); 13999 if (const LValueReferenceType *OtherRef 14000 = OtherRefType->getAs<LValueReferenceType>()) { 14001 OtherRefType = OtherRef->getPointeeType(); 14002 OtherQuals = OtherRefType.getQualifiers(); 14003 } 14004 14005 // Our location for everything implicitly-generated. 14006 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid() 14007 ? CopyAssignOperator->getEndLoc() 14008 : CopyAssignOperator->getLocation(); 14009 14010 // Builds a DeclRefExpr for the "other" object. 14011 RefBuilder OtherRef(Other, OtherRefType); 14012 14013 // Builds the "this" pointer. 14014 ThisBuilder This; 14015 14016 // Assign base classes. 14017 bool Invalid = false; 14018 for (auto &Base : ClassDecl->bases()) { 14019 // Form the assignment: 14020 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 14021 QualType BaseType = Base.getType().getUnqualifiedType(); 14022 if (!BaseType->isRecordType()) { 14023 Invalid = true; 14024 continue; 14025 } 14026 14027 CXXCastPath BasePath; 14028 BasePath.push_back(&Base); 14029 14030 // Construct the "from" expression, which is an implicit cast to the 14031 // appropriately-qualified base type. 14032 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 14033 VK_LValue, BasePath); 14034 14035 // Dereference "this". 14036 DerefBuilder DerefThis(This); 14037 CastBuilder To(DerefThis, 14038 Context.getQualifiedType( 14039 BaseType, CopyAssignOperator->getMethodQualifiers()), 14040 VK_LValue, BasePath); 14041 14042 // Build the copy. 14043 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 14044 To, From, 14045 /*CopyingBaseSubobject=*/true, 14046 /*Copying=*/true); 14047 if (Copy.isInvalid()) { 14048 CopyAssignOperator->setInvalidDecl(); 14049 return; 14050 } 14051 14052 // Success! Record the copy. 14053 Statements.push_back(Copy.getAs<Expr>()); 14054 } 14055 14056 // Assign non-static members. 14057 for (auto *Field : ClassDecl->fields()) { 14058 // FIXME: We should form some kind of AST representation for the implied 14059 // memcpy in a union copy operation. 14060 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 14061 continue; 14062 14063 if (Field->isInvalidDecl()) { 14064 Invalid = true; 14065 continue; 14066 } 14067 14068 // Check for members of reference type; we can't copy those. 14069 if (Field->getType()->isReferenceType()) { 14070 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14071 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 14072 Diag(Field->getLocation(), diag::note_declared_at); 14073 Invalid = true; 14074 continue; 14075 } 14076 14077 // Check for members of const-qualified, non-class type. 14078 QualType BaseType = Context.getBaseElementType(Field->getType()); 14079 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 14080 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14081 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 14082 Diag(Field->getLocation(), diag::note_declared_at); 14083 Invalid = true; 14084 continue; 14085 } 14086 14087 // Suppress assigning zero-width bitfields. 14088 if (Field->isZeroLengthBitField(Context)) 14089 continue; 14090 14091 QualType FieldType = Field->getType().getNonReferenceType(); 14092 if (FieldType->isIncompleteArrayType()) { 14093 assert(ClassDecl->hasFlexibleArrayMember() && 14094 "Incomplete array type is not valid"); 14095 continue; 14096 } 14097 14098 // Build references to the field in the object we're copying from and to. 14099 CXXScopeSpec SS; // Intentionally empty 14100 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 14101 LookupMemberName); 14102 MemberLookup.addDecl(Field); 14103 MemberLookup.resolveKind(); 14104 14105 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 14106 14107 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 14108 14109 // Build the copy of this field. 14110 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 14111 To, From, 14112 /*CopyingBaseSubobject=*/false, 14113 /*Copying=*/true); 14114 if (Copy.isInvalid()) { 14115 CopyAssignOperator->setInvalidDecl(); 14116 return; 14117 } 14118 14119 // Success! Record the copy. 14120 Statements.push_back(Copy.getAs<Stmt>()); 14121 } 14122 14123 if (!Invalid) { 14124 // Add a "return *this;" 14125 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 14126 14127 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 14128 if (Return.isInvalid()) 14129 Invalid = true; 14130 else 14131 Statements.push_back(Return.getAs<Stmt>()); 14132 } 14133 14134 if (Invalid) { 14135 CopyAssignOperator->setInvalidDecl(); 14136 return; 14137 } 14138 14139 StmtResult Body; 14140 { 14141 CompoundScopeRAII CompoundScope(*this); 14142 Body = ActOnCompoundStmt(Loc, Loc, Statements, 14143 /*isStmtExpr=*/false); 14144 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 14145 } 14146 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 14147 CopyAssignOperator->markUsed(Context); 14148 14149 if (ASTMutationListener *L = getASTMutationListener()) { 14150 L->CompletedImplicitDefinition(CopyAssignOperator); 14151 } 14152 } 14153 14154 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 14155 assert(ClassDecl->needsImplicitMoveAssignment()); 14156 14157 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 14158 if (DSM.isAlreadyBeingDeclared()) 14159 return nullptr; 14160 14161 // Note: The following rules are largely analoguous to the move 14162 // constructor rules. 14163 14164 QualType ArgType = Context.getTypeDeclType(ClassDecl); 14165 LangAS AS = getDefaultCXXMethodAddrSpace(); 14166 if (AS != LangAS::Default) 14167 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 14168 QualType RetType = Context.getLValueReferenceType(ArgType); 14169 ArgType = Context.getRValueReferenceType(ArgType); 14170 14171 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14172 CXXMoveAssignment, 14173 false); 14174 14175 // An implicitly-declared move assignment operator is an inline public 14176 // member of its class. 14177 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 14178 SourceLocation ClassLoc = ClassDecl->getLocation(); 14179 DeclarationNameInfo NameInfo(Name, ClassLoc); 14180 CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create( 14181 Context, ClassDecl, ClassLoc, NameInfo, QualType(), 14182 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 14183 /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified, 14184 SourceLocation()); 14185 MoveAssignment->setAccess(AS_public); 14186 MoveAssignment->setDefaulted(); 14187 MoveAssignment->setImplicit(); 14188 14189 if (getLangOpts().CUDA) { 14190 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 14191 MoveAssignment, 14192 /* ConstRHS */ false, 14193 /* Diagnose */ false); 14194 } 14195 14196 // Build an exception specification pointing back at this member. 14197 FunctionProtoType::ExtProtoInfo EPI = 14198 getImplicitMethodEPI(*this, MoveAssignment); 14199 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 14200 14201 // Add the parameter to the operator. 14202 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 14203 ClassLoc, ClassLoc, 14204 /*Id=*/nullptr, ArgType, 14205 /*TInfo=*/nullptr, SC_None, 14206 nullptr); 14207 MoveAssignment->setParams(FromParam); 14208 14209 MoveAssignment->setTrivial( 14210 ClassDecl->needsOverloadResolutionForMoveAssignment() 14211 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 14212 : ClassDecl->hasTrivialMoveAssignment()); 14213 14214 // Note that we have added this copy-assignment operator. 14215 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared; 14216 14217 Scope *S = getScopeForContext(ClassDecl); 14218 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment); 14219 14220 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 14221 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 14222 SetDeclDeleted(MoveAssignment, ClassLoc); 14223 } 14224 14225 if (S) 14226 PushOnScopeChains(MoveAssignment, S, false); 14227 ClassDecl->addDecl(MoveAssignment); 14228 14229 return MoveAssignment; 14230 } 14231 14232 /// Check if we're implicitly defining a move assignment operator for a class 14233 /// with virtual bases. Such a move assignment might move-assign the virtual 14234 /// base multiple times. 14235 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 14236 SourceLocation CurrentLocation) { 14237 assert(!Class->isDependentContext() && "should not define dependent move"); 14238 14239 // Only a virtual base could get implicitly move-assigned multiple times. 14240 // Only a non-trivial move assignment can observe this. We only want to 14241 // diagnose if we implicitly define an assignment operator that assigns 14242 // two base classes, both of which move-assign the same virtual base. 14243 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 14244 Class->getNumBases() < 2) 14245 return; 14246 14247 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 14248 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 14249 VBaseMap VBases; 14250 14251 for (auto &BI : Class->bases()) { 14252 Worklist.push_back(&BI); 14253 while (!Worklist.empty()) { 14254 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 14255 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 14256 14257 // If the base has no non-trivial move assignment operators, 14258 // we don't care about moves from it. 14259 if (!Base->hasNonTrivialMoveAssignment()) 14260 continue; 14261 14262 // If there's nothing virtual here, skip it. 14263 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 14264 continue; 14265 14266 // If we're not actually going to call a move assignment for this base, 14267 // or the selected move assignment is trivial, skip it. 14268 Sema::SpecialMemberOverloadResult SMOR = 14269 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 14270 /*ConstArg*/false, /*VolatileArg*/false, 14271 /*RValueThis*/true, /*ConstThis*/false, 14272 /*VolatileThis*/false); 14273 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() || 14274 !SMOR.getMethod()->isMoveAssignmentOperator()) 14275 continue; 14276 14277 if (BaseSpec->isVirtual()) { 14278 // We're going to move-assign this virtual base, and its move 14279 // assignment operator is not trivial. If this can happen for 14280 // multiple distinct direct bases of Class, diagnose it. (If it 14281 // only happens in one base, we'll diagnose it when synthesizing 14282 // that base class's move assignment operator.) 14283 CXXBaseSpecifier *&Existing = 14284 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 14285 .first->second; 14286 if (Existing && Existing != &BI) { 14287 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 14288 << Class << Base; 14289 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here) 14290 << (Base->getCanonicalDecl() == 14291 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 14292 << Base << Existing->getType() << Existing->getSourceRange(); 14293 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here) 14294 << (Base->getCanonicalDecl() == 14295 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 14296 << Base << BI.getType() << BaseSpec->getSourceRange(); 14297 14298 // Only diagnose each vbase once. 14299 Existing = nullptr; 14300 } 14301 } else { 14302 // Only walk over bases that have defaulted move assignment operators. 14303 // We assume that any user-provided move assignment operator handles 14304 // the multiple-moves-of-vbase case itself somehow. 14305 if (!SMOR.getMethod()->isDefaulted()) 14306 continue; 14307 14308 // We're going to move the base classes of Base. Add them to the list. 14309 for (auto &BI : Base->bases()) 14310 Worklist.push_back(&BI); 14311 } 14312 } 14313 } 14314 } 14315 14316 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 14317 CXXMethodDecl *MoveAssignOperator) { 14318 assert((MoveAssignOperator->isDefaulted() && 14319 MoveAssignOperator->isOverloadedOperator() && 14320 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 14321 !MoveAssignOperator->doesThisDeclarationHaveABody() && 14322 !MoveAssignOperator->isDeleted()) && 14323 "DefineImplicitMoveAssignment called for wrong function"); 14324 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl()) 14325 return; 14326 14327 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 14328 if (ClassDecl->isInvalidDecl()) { 14329 MoveAssignOperator->setInvalidDecl(); 14330 return; 14331 } 14332 14333 // C++0x [class.copy]p28: 14334 // The implicitly-defined or move assignment operator for a non-union class 14335 // X performs memberwise move assignment of its subobjects. The direct base 14336 // classes of X are assigned first, in the order of their declaration in the 14337 // base-specifier-list, and then the immediate non-static data members of X 14338 // are assigned, in the order in which they were declared in the class 14339 // definition. 14340 14341 // Issue a warning if our implicit move assignment operator will move 14342 // from a virtual base more than once. 14343 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 14344 14345 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 14346 14347 // The exception specification is needed because we are defining the 14348 // function. 14349 ResolveExceptionSpec(CurrentLocation, 14350 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 14351 14352 // Add a context note for diagnostics produced after this point. 14353 Scope.addContextNote(CurrentLocation); 14354 14355 // The statements that form the synthesized function body. 14356 SmallVector<Stmt*, 8> Statements; 14357 14358 // The parameter for the "other" object, which we are move from. 14359 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 14360 QualType OtherRefType = 14361 Other->getType()->castAs<RValueReferenceType>()->getPointeeType(); 14362 14363 // Our location for everything implicitly-generated. 14364 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid() 14365 ? MoveAssignOperator->getEndLoc() 14366 : MoveAssignOperator->getLocation(); 14367 14368 // Builds a reference to the "other" object. 14369 RefBuilder OtherRef(Other, OtherRefType); 14370 // Cast to rvalue. 14371 MoveCastBuilder MoveOther(OtherRef); 14372 14373 // Builds the "this" pointer. 14374 ThisBuilder This; 14375 14376 // Assign base classes. 14377 bool Invalid = false; 14378 for (auto &Base : ClassDecl->bases()) { 14379 // C++11 [class.copy]p28: 14380 // It is unspecified whether subobjects representing virtual base classes 14381 // are assigned more than once by the implicitly-defined copy assignment 14382 // operator. 14383 // FIXME: Do not assign to a vbase that will be assigned by some other base 14384 // class. For a move-assignment, this can result in the vbase being moved 14385 // multiple times. 14386 14387 // Form the assignment: 14388 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 14389 QualType BaseType = Base.getType().getUnqualifiedType(); 14390 if (!BaseType->isRecordType()) { 14391 Invalid = true; 14392 continue; 14393 } 14394 14395 CXXCastPath BasePath; 14396 BasePath.push_back(&Base); 14397 14398 // Construct the "from" expression, which is an implicit cast to the 14399 // appropriately-qualified base type. 14400 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 14401 14402 // Dereference "this". 14403 DerefBuilder DerefThis(This); 14404 14405 // Implicitly cast "this" to the appropriately-qualified base type. 14406 CastBuilder To(DerefThis, 14407 Context.getQualifiedType( 14408 BaseType, MoveAssignOperator->getMethodQualifiers()), 14409 VK_LValue, BasePath); 14410 14411 // Build the move. 14412 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 14413 To, From, 14414 /*CopyingBaseSubobject=*/true, 14415 /*Copying=*/false); 14416 if (Move.isInvalid()) { 14417 MoveAssignOperator->setInvalidDecl(); 14418 return; 14419 } 14420 14421 // Success! Record the move. 14422 Statements.push_back(Move.getAs<Expr>()); 14423 } 14424 14425 // Assign non-static members. 14426 for (auto *Field : ClassDecl->fields()) { 14427 // FIXME: We should form some kind of AST representation for the implied 14428 // memcpy in a union copy operation. 14429 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 14430 continue; 14431 14432 if (Field->isInvalidDecl()) { 14433 Invalid = true; 14434 continue; 14435 } 14436 14437 // Check for members of reference type; we can't move those. 14438 if (Field->getType()->isReferenceType()) { 14439 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14440 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 14441 Diag(Field->getLocation(), diag::note_declared_at); 14442 Invalid = true; 14443 continue; 14444 } 14445 14446 // Check for members of const-qualified, non-class type. 14447 QualType BaseType = Context.getBaseElementType(Field->getType()); 14448 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 14449 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14450 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 14451 Diag(Field->getLocation(), diag::note_declared_at); 14452 Invalid = true; 14453 continue; 14454 } 14455 14456 // Suppress assigning zero-width bitfields. 14457 if (Field->isZeroLengthBitField(Context)) 14458 continue; 14459 14460 QualType FieldType = Field->getType().getNonReferenceType(); 14461 if (FieldType->isIncompleteArrayType()) { 14462 assert(ClassDecl->hasFlexibleArrayMember() && 14463 "Incomplete array type is not valid"); 14464 continue; 14465 } 14466 14467 // Build references to the field in the object we're copying from and to. 14468 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 14469 LookupMemberName); 14470 MemberLookup.addDecl(Field); 14471 MemberLookup.resolveKind(); 14472 MemberBuilder From(MoveOther, OtherRefType, 14473 /*IsArrow=*/false, MemberLookup); 14474 MemberBuilder To(This, getCurrentThisType(), 14475 /*IsArrow=*/true, MemberLookup); 14476 14477 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 14478 "Member reference with rvalue base must be rvalue except for reference " 14479 "members, which aren't allowed for move assignment."); 14480 14481 // Build the move of this field. 14482 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 14483 To, From, 14484 /*CopyingBaseSubobject=*/false, 14485 /*Copying=*/false); 14486 if (Move.isInvalid()) { 14487 MoveAssignOperator->setInvalidDecl(); 14488 return; 14489 } 14490 14491 // Success! Record the copy. 14492 Statements.push_back(Move.getAs<Stmt>()); 14493 } 14494 14495 if (!Invalid) { 14496 // Add a "return *this;" 14497 ExprResult ThisObj = 14498 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 14499 14500 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 14501 if (Return.isInvalid()) 14502 Invalid = true; 14503 else 14504 Statements.push_back(Return.getAs<Stmt>()); 14505 } 14506 14507 if (Invalid) { 14508 MoveAssignOperator->setInvalidDecl(); 14509 return; 14510 } 14511 14512 StmtResult Body; 14513 { 14514 CompoundScopeRAII CompoundScope(*this); 14515 Body = ActOnCompoundStmt(Loc, Loc, Statements, 14516 /*isStmtExpr=*/false); 14517 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 14518 } 14519 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 14520 MoveAssignOperator->markUsed(Context); 14521 14522 if (ASTMutationListener *L = getASTMutationListener()) { 14523 L->CompletedImplicitDefinition(MoveAssignOperator); 14524 } 14525 } 14526 14527 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 14528 CXXRecordDecl *ClassDecl) { 14529 // C++ [class.copy]p4: 14530 // If the class definition does not explicitly declare a copy 14531 // constructor, one is declared implicitly. 14532 assert(ClassDecl->needsImplicitCopyConstructor()); 14533 14534 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 14535 if (DSM.isAlreadyBeingDeclared()) 14536 return nullptr; 14537 14538 QualType ClassType = Context.getTypeDeclType(ClassDecl); 14539 QualType ArgType = ClassType; 14540 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 14541 if (Const) 14542 ArgType = ArgType.withConst(); 14543 14544 LangAS AS = getDefaultCXXMethodAddrSpace(); 14545 if (AS != LangAS::Default) 14546 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 14547 14548 ArgType = Context.getLValueReferenceType(ArgType); 14549 14550 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14551 CXXCopyConstructor, 14552 Const); 14553 14554 DeclarationName Name 14555 = Context.DeclarationNames.getCXXConstructorName( 14556 Context.getCanonicalType(ClassType)); 14557 SourceLocation ClassLoc = ClassDecl->getLocation(); 14558 DeclarationNameInfo NameInfo(Name, ClassLoc); 14559 14560 // An implicitly-declared copy constructor is an inline public 14561 // member of its class. 14562 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 14563 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 14564 ExplicitSpecifier(), 14565 /*isInline=*/true, 14566 /*isImplicitlyDeclared=*/true, 14567 Constexpr ? CSK_constexpr : CSK_unspecified); 14568 CopyConstructor->setAccess(AS_public); 14569 CopyConstructor->setDefaulted(); 14570 14571 if (getLangOpts().CUDA) { 14572 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 14573 CopyConstructor, 14574 /* ConstRHS */ Const, 14575 /* Diagnose */ false); 14576 } 14577 14578 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType); 14579 14580 // Add the parameter to the constructor. 14581 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 14582 ClassLoc, ClassLoc, 14583 /*IdentifierInfo=*/nullptr, 14584 ArgType, /*TInfo=*/nullptr, 14585 SC_None, nullptr); 14586 CopyConstructor->setParams(FromParam); 14587 14588 CopyConstructor->setTrivial( 14589 ClassDecl->needsOverloadResolutionForCopyConstructor() 14590 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 14591 : ClassDecl->hasTrivialCopyConstructor()); 14592 14593 CopyConstructor->setTrivialForCall( 14594 ClassDecl->hasAttr<TrivialABIAttr>() || 14595 (ClassDecl->needsOverloadResolutionForCopyConstructor() 14596 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor, 14597 TAH_ConsiderTrivialABI) 14598 : ClassDecl->hasTrivialCopyConstructorForCall())); 14599 14600 // Note that we have declared this constructor. 14601 ++getASTContext().NumImplicitCopyConstructorsDeclared; 14602 14603 Scope *S = getScopeForContext(ClassDecl); 14604 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor); 14605 14606 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) { 14607 ClassDecl->setImplicitCopyConstructorIsDeleted(); 14608 SetDeclDeleted(CopyConstructor, ClassLoc); 14609 } 14610 14611 if (S) 14612 PushOnScopeChains(CopyConstructor, S, false); 14613 ClassDecl->addDecl(CopyConstructor); 14614 14615 return CopyConstructor; 14616 } 14617 14618 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 14619 CXXConstructorDecl *CopyConstructor) { 14620 assert((CopyConstructor->isDefaulted() && 14621 CopyConstructor->isCopyConstructor() && 14622 !CopyConstructor->doesThisDeclarationHaveABody() && 14623 !CopyConstructor->isDeleted()) && 14624 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 14625 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl()) 14626 return; 14627 14628 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 14629 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 14630 14631 SynthesizedFunctionScope Scope(*this, CopyConstructor); 14632 14633 // The exception specification is needed because we are defining the 14634 // function. 14635 ResolveExceptionSpec(CurrentLocation, 14636 CopyConstructor->getType()->castAs<FunctionProtoType>()); 14637 MarkVTableUsed(CurrentLocation, ClassDecl); 14638 14639 // Add a context note for diagnostics produced after this point. 14640 Scope.addContextNote(CurrentLocation); 14641 14642 // C++11 [class.copy]p7: 14643 // The [definition of an implicitly declared copy constructor] is 14644 // deprecated if the class has a user-declared copy assignment operator 14645 // or a user-declared destructor. 14646 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 14647 diagnoseDeprecatedCopyOperation(*this, CopyConstructor); 14648 14649 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) { 14650 CopyConstructor->setInvalidDecl(); 14651 } else { 14652 SourceLocation Loc = CopyConstructor->getEndLoc().isValid() 14653 ? CopyConstructor->getEndLoc() 14654 : CopyConstructor->getLocation(); 14655 Sema::CompoundScopeRAII CompoundScope(*this); 14656 CopyConstructor->setBody( 14657 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 14658 CopyConstructor->markUsed(Context); 14659 } 14660 14661 if (ASTMutationListener *L = getASTMutationListener()) { 14662 L->CompletedImplicitDefinition(CopyConstructor); 14663 } 14664 } 14665 14666 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 14667 CXXRecordDecl *ClassDecl) { 14668 assert(ClassDecl->needsImplicitMoveConstructor()); 14669 14670 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 14671 if (DSM.isAlreadyBeingDeclared()) 14672 return nullptr; 14673 14674 QualType ClassType = Context.getTypeDeclType(ClassDecl); 14675 14676 QualType ArgType = ClassType; 14677 LangAS AS = getDefaultCXXMethodAddrSpace(); 14678 if (AS != LangAS::Default) 14679 ArgType = Context.getAddrSpaceQualType(ClassType, AS); 14680 ArgType = Context.getRValueReferenceType(ArgType); 14681 14682 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14683 CXXMoveConstructor, 14684 false); 14685 14686 DeclarationName Name 14687 = Context.DeclarationNames.getCXXConstructorName( 14688 Context.getCanonicalType(ClassType)); 14689 SourceLocation ClassLoc = ClassDecl->getLocation(); 14690 DeclarationNameInfo NameInfo(Name, ClassLoc); 14691 14692 // C++11 [class.copy]p11: 14693 // An implicitly-declared copy/move constructor is an inline public 14694 // member of its class. 14695 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 14696 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 14697 ExplicitSpecifier(), 14698 /*isInline=*/true, 14699 /*isImplicitlyDeclared=*/true, 14700 Constexpr ? CSK_constexpr : CSK_unspecified); 14701 MoveConstructor->setAccess(AS_public); 14702 MoveConstructor->setDefaulted(); 14703 14704 if (getLangOpts().CUDA) { 14705 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 14706 MoveConstructor, 14707 /* ConstRHS */ false, 14708 /* Diagnose */ false); 14709 } 14710 14711 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType); 14712 14713 // Add the parameter to the constructor. 14714 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 14715 ClassLoc, ClassLoc, 14716 /*IdentifierInfo=*/nullptr, 14717 ArgType, /*TInfo=*/nullptr, 14718 SC_None, nullptr); 14719 MoveConstructor->setParams(FromParam); 14720 14721 MoveConstructor->setTrivial( 14722 ClassDecl->needsOverloadResolutionForMoveConstructor() 14723 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 14724 : ClassDecl->hasTrivialMoveConstructor()); 14725 14726 MoveConstructor->setTrivialForCall( 14727 ClassDecl->hasAttr<TrivialABIAttr>() || 14728 (ClassDecl->needsOverloadResolutionForMoveConstructor() 14729 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor, 14730 TAH_ConsiderTrivialABI) 14731 : ClassDecl->hasTrivialMoveConstructorForCall())); 14732 14733 // Note that we have declared this constructor. 14734 ++getASTContext().NumImplicitMoveConstructorsDeclared; 14735 14736 Scope *S = getScopeForContext(ClassDecl); 14737 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor); 14738 14739 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 14740 ClassDecl->setImplicitMoveConstructorIsDeleted(); 14741 SetDeclDeleted(MoveConstructor, ClassLoc); 14742 } 14743 14744 if (S) 14745 PushOnScopeChains(MoveConstructor, S, false); 14746 ClassDecl->addDecl(MoveConstructor); 14747 14748 return MoveConstructor; 14749 } 14750 14751 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 14752 CXXConstructorDecl *MoveConstructor) { 14753 assert((MoveConstructor->isDefaulted() && 14754 MoveConstructor->isMoveConstructor() && 14755 !MoveConstructor->doesThisDeclarationHaveABody() && 14756 !MoveConstructor->isDeleted()) && 14757 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 14758 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl()) 14759 return; 14760 14761 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 14762 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 14763 14764 SynthesizedFunctionScope Scope(*this, MoveConstructor); 14765 14766 // The exception specification is needed because we are defining the 14767 // function. 14768 ResolveExceptionSpec(CurrentLocation, 14769 MoveConstructor->getType()->castAs<FunctionProtoType>()); 14770 MarkVTableUsed(CurrentLocation, ClassDecl); 14771 14772 // Add a context note for diagnostics produced after this point. 14773 Scope.addContextNote(CurrentLocation); 14774 14775 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) { 14776 MoveConstructor->setInvalidDecl(); 14777 } else { 14778 SourceLocation Loc = MoveConstructor->getEndLoc().isValid() 14779 ? MoveConstructor->getEndLoc() 14780 : MoveConstructor->getLocation(); 14781 Sema::CompoundScopeRAII CompoundScope(*this); 14782 MoveConstructor->setBody(ActOnCompoundStmt( 14783 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 14784 MoveConstructor->markUsed(Context); 14785 } 14786 14787 if (ASTMutationListener *L = getASTMutationListener()) { 14788 L->CompletedImplicitDefinition(MoveConstructor); 14789 } 14790 } 14791 14792 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 14793 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 14794 } 14795 14796 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 14797 SourceLocation CurrentLocation, 14798 CXXConversionDecl *Conv) { 14799 SynthesizedFunctionScope Scope(*this, Conv); 14800 assert(!Conv->getReturnType()->isUndeducedType()); 14801 14802 CXXRecordDecl *Lambda = Conv->getParent(); 14803 FunctionDecl *CallOp = Lambda->getLambdaCallOperator(); 14804 FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(); 14805 14806 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) { 14807 CallOp = InstantiateFunctionDeclaration( 14808 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 14809 if (!CallOp) 14810 return; 14811 14812 Invoker = InstantiateFunctionDeclaration( 14813 Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 14814 if (!Invoker) 14815 return; 14816 } 14817 14818 if (CallOp->isInvalidDecl()) 14819 return; 14820 14821 // Mark the call operator referenced (and add to pending instantiations 14822 // if necessary). 14823 // For both the conversion and static-invoker template specializations 14824 // we construct their body's in this function, so no need to add them 14825 // to the PendingInstantiations. 14826 MarkFunctionReferenced(CurrentLocation, CallOp); 14827 14828 // Fill in the __invoke function with a dummy implementation. IR generation 14829 // will fill in the actual details. Update its type in case it contained 14830 // an 'auto'. 14831 Invoker->markUsed(Context); 14832 Invoker->setReferenced(); 14833 Invoker->setType(Conv->getReturnType()->getPointeeType()); 14834 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 14835 14836 // Construct the body of the conversion function { return __invoke; }. 14837 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 14838 VK_LValue, Conv->getLocation()); 14839 assert(FunctionRef && "Can't refer to __invoke function?"); 14840 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 14841 Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(), 14842 Conv->getLocation())); 14843 Conv->markUsed(Context); 14844 Conv->setReferenced(); 14845 14846 if (ASTMutationListener *L = getASTMutationListener()) { 14847 L->CompletedImplicitDefinition(Conv); 14848 L->CompletedImplicitDefinition(Invoker); 14849 } 14850 } 14851 14852 14853 14854 void Sema::DefineImplicitLambdaToBlockPointerConversion( 14855 SourceLocation CurrentLocation, 14856 CXXConversionDecl *Conv) 14857 { 14858 assert(!Conv->getParent()->isGenericLambda()); 14859 14860 SynthesizedFunctionScope Scope(*this, Conv); 14861 14862 // Copy-initialize the lambda object as needed to capture it. 14863 Expr *This = ActOnCXXThis(CurrentLocation).get(); 14864 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 14865 14866 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 14867 Conv->getLocation(), 14868 Conv, DerefThis); 14869 14870 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 14871 // behavior. Note that only the general conversion function does this 14872 // (since it's unusable otherwise); in the case where we inline the 14873 // block literal, it has block literal lifetime semantics. 14874 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 14875 BuildBlock = ImplicitCastExpr::Create( 14876 Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject, 14877 BuildBlock.get(), nullptr, VK_RValue, FPOptionsOverride()); 14878 14879 if (BuildBlock.isInvalid()) { 14880 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 14881 Conv->setInvalidDecl(); 14882 return; 14883 } 14884 14885 // Create the return statement that returns the block from the conversion 14886 // function. 14887 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 14888 if (Return.isInvalid()) { 14889 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 14890 Conv->setInvalidDecl(); 14891 return; 14892 } 14893 14894 // Set the body of the conversion function. 14895 Stmt *ReturnS = Return.get(); 14896 Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(), 14897 Conv->getLocation())); 14898 Conv->markUsed(Context); 14899 14900 // We're done; notify the mutation listener, if any. 14901 if (ASTMutationListener *L = getASTMutationListener()) { 14902 L->CompletedImplicitDefinition(Conv); 14903 } 14904 } 14905 14906 /// Determine whether the given list arguments contains exactly one 14907 /// "real" (non-default) argument. 14908 static bool hasOneRealArgument(MultiExprArg Args) { 14909 switch (Args.size()) { 14910 case 0: 14911 return false; 14912 14913 default: 14914 if (!Args[1]->isDefaultArgument()) 14915 return false; 14916 14917 LLVM_FALLTHROUGH; 14918 case 1: 14919 return !Args[0]->isDefaultArgument(); 14920 } 14921 14922 return false; 14923 } 14924 14925 ExprResult 14926 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 14927 NamedDecl *FoundDecl, 14928 CXXConstructorDecl *Constructor, 14929 MultiExprArg ExprArgs, 14930 bool HadMultipleCandidates, 14931 bool IsListInitialization, 14932 bool IsStdInitListInitialization, 14933 bool RequiresZeroInit, 14934 unsigned ConstructKind, 14935 SourceRange ParenRange) { 14936 bool Elidable = false; 14937 14938 // C++0x [class.copy]p34: 14939 // When certain criteria are met, an implementation is allowed to 14940 // omit the copy/move construction of a class object, even if the 14941 // copy/move constructor and/or destructor for the object have 14942 // side effects. [...] 14943 // - when a temporary class object that has not been bound to a 14944 // reference (12.2) would be copied/moved to a class object 14945 // with the same cv-unqualified type, the copy/move operation 14946 // can be omitted by constructing the temporary object 14947 // directly into the target of the omitted copy/move 14948 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor && 14949 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 14950 Expr *SubExpr = ExprArgs[0]; 14951 Elidable = SubExpr->isTemporaryObject( 14952 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 14953 } 14954 14955 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, 14956 FoundDecl, Constructor, 14957 Elidable, ExprArgs, HadMultipleCandidates, 14958 IsListInitialization, 14959 IsStdInitListInitialization, RequiresZeroInit, 14960 ConstructKind, ParenRange); 14961 } 14962 14963 ExprResult 14964 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 14965 NamedDecl *FoundDecl, 14966 CXXConstructorDecl *Constructor, 14967 bool Elidable, 14968 MultiExprArg ExprArgs, 14969 bool HadMultipleCandidates, 14970 bool IsListInitialization, 14971 bool IsStdInitListInitialization, 14972 bool RequiresZeroInit, 14973 unsigned ConstructKind, 14974 SourceRange ParenRange) { 14975 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) { 14976 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow); 14977 if (DiagnoseUseOfDecl(Constructor, ConstructLoc)) 14978 return ExprError(); 14979 } 14980 14981 return BuildCXXConstructExpr( 14982 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs, 14983 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 14984 RequiresZeroInit, ConstructKind, ParenRange); 14985 } 14986 14987 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 14988 /// including handling of its default argument expressions. 14989 ExprResult 14990 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 14991 CXXConstructorDecl *Constructor, 14992 bool Elidable, 14993 MultiExprArg ExprArgs, 14994 bool HadMultipleCandidates, 14995 bool IsListInitialization, 14996 bool IsStdInitListInitialization, 14997 bool RequiresZeroInit, 14998 unsigned ConstructKind, 14999 SourceRange ParenRange) { 15000 assert(declaresSameEntity( 15001 Constructor->getParent(), 15002 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && 15003 "given constructor for wrong type"); 15004 MarkFunctionReferenced(ConstructLoc, Constructor); 15005 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor)) 15006 return ExprError(); 15007 if (getLangOpts().SYCLIsDevice && 15008 !checkSYCLDeviceFunction(ConstructLoc, Constructor)) 15009 return ExprError(); 15010 15011 return CheckForImmediateInvocation( 15012 CXXConstructExpr::Create( 15013 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs, 15014 HadMultipleCandidates, IsListInitialization, 15015 IsStdInitListInitialization, RequiresZeroInit, 15016 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 15017 ParenRange), 15018 Constructor); 15019 } 15020 15021 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 15022 assert(Field->hasInClassInitializer()); 15023 15024 // If we already have the in-class initializer nothing needs to be done. 15025 if (Field->getInClassInitializer()) 15026 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext); 15027 15028 // If we might have already tried and failed to instantiate, don't try again. 15029 if (Field->isInvalidDecl()) 15030 return ExprError(); 15031 15032 // Maybe we haven't instantiated the in-class initializer. Go check the 15033 // pattern FieldDecl to see if it has one. 15034 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 15035 15036 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 15037 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 15038 DeclContext::lookup_result Lookup = 15039 ClassPattern->lookup(Field->getDeclName()); 15040 15041 // Lookup can return at most two results: the pattern for the field, or the 15042 // injected class name of the parent record. No other member can have the 15043 // same name as the field. 15044 // In modules mode, lookup can return multiple results (coming from 15045 // different modules). 15046 assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) && 15047 "more than two lookup results for field name"); 15048 FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]); 15049 if (!Pattern) { 15050 assert(isa<CXXRecordDecl>(Lookup[0]) && 15051 "cannot have other non-field member with same name"); 15052 for (auto L : Lookup) 15053 if (isa<FieldDecl>(L)) { 15054 Pattern = cast<FieldDecl>(L); 15055 break; 15056 } 15057 assert(Pattern && "We must have set the Pattern!"); 15058 } 15059 15060 if (!Pattern->hasInClassInitializer() || 15061 InstantiateInClassInitializer(Loc, Field, Pattern, 15062 getTemplateInstantiationArgs(Field))) { 15063 // Don't diagnose this again. 15064 Field->setInvalidDecl(); 15065 return ExprError(); 15066 } 15067 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext); 15068 } 15069 15070 // DR1351: 15071 // If the brace-or-equal-initializer of a non-static data member 15072 // invokes a defaulted default constructor of its class or of an 15073 // enclosing class in a potentially evaluated subexpression, the 15074 // program is ill-formed. 15075 // 15076 // This resolution is unworkable: the exception specification of the 15077 // default constructor can be needed in an unevaluated context, in 15078 // particular, in the operand of a noexcept-expression, and we can be 15079 // unable to compute an exception specification for an enclosed class. 15080 // 15081 // Any attempt to resolve the exception specification of a defaulted default 15082 // constructor before the initializer is lexically complete will ultimately 15083 // come here at which point we can diagnose it. 15084 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 15085 Diag(Loc, diag::err_default_member_initializer_not_yet_parsed) 15086 << OutermostClass << Field; 15087 Diag(Field->getEndLoc(), 15088 diag::note_default_member_initializer_not_yet_parsed); 15089 // Recover by marking the field invalid, unless we're in a SFINAE context. 15090 if (!isSFINAEContext()) 15091 Field->setInvalidDecl(); 15092 return ExprError(); 15093 } 15094 15095 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 15096 if (VD->isInvalidDecl()) return; 15097 // If initializing the variable failed, don't also diagnose problems with 15098 // the desctructor, they're likely related. 15099 if (VD->getInit() && VD->getInit()->containsErrors()) 15100 return; 15101 15102 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 15103 if (ClassDecl->isInvalidDecl()) return; 15104 if (ClassDecl->hasIrrelevantDestructor()) return; 15105 if (ClassDecl->isDependentContext()) return; 15106 15107 if (VD->isNoDestroy(getASTContext())) 15108 return; 15109 15110 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 15111 15112 // If this is an array, we'll require the destructor during initialization, so 15113 // we can skip over this. We still want to emit exit-time destructor warnings 15114 // though. 15115 if (!VD->getType()->isArrayType()) { 15116 MarkFunctionReferenced(VD->getLocation(), Destructor); 15117 CheckDestructorAccess(VD->getLocation(), Destructor, 15118 PDiag(diag::err_access_dtor_var) 15119 << VD->getDeclName() << VD->getType()); 15120 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 15121 } 15122 15123 if (Destructor->isTrivial()) return; 15124 15125 // If the destructor is constexpr, check whether the variable has constant 15126 // destruction now. 15127 if (Destructor->isConstexpr()) { 15128 bool HasConstantInit = false; 15129 if (VD->getInit() && !VD->getInit()->isValueDependent()) 15130 HasConstantInit = VD->evaluateValue(); 15131 SmallVector<PartialDiagnosticAt, 8> Notes; 15132 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() && 15133 HasConstantInit) { 15134 Diag(VD->getLocation(), 15135 diag::err_constexpr_var_requires_const_destruction) << VD; 15136 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 15137 Diag(Notes[I].first, Notes[I].second); 15138 } 15139 } 15140 15141 if (!VD->hasGlobalStorage()) return; 15142 15143 // Emit warning for non-trivial dtor in global scope (a real global, 15144 // class-static, function-static). 15145 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 15146 15147 // TODO: this should be re-enabled for static locals by !CXAAtExit 15148 if (!VD->isStaticLocal()) 15149 Diag(VD->getLocation(), diag::warn_global_destructor); 15150 } 15151 15152 /// Given a constructor and the set of arguments provided for the 15153 /// constructor, convert the arguments and add any required default arguments 15154 /// to form a proper call to this constructor. 15155 /// 15156 /// \returns true if an error occurred, false otherwise. 15157 bool 15158 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 15159 MultiExprArg ArgsPtr, 15160 SourceLocation Loc, 15161 SmallVectorImpl<Expr*> &ConvertedArgs, 15162 bool AllowExplicit, 15163 bool IsListInitialization) { 15164 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 15165 unsigned NumArgs = ArgsPtr.size(); 15166 Expr **Args = ArgsPtr.data(); 15167 15168 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>(); 15169 unsigned NumParams = Proto->getNumParams(); 15170 15171 // If too few arguments are available, we'll fill in the rest with defaults. 15172 if (NumArgs < NumParams) 15173 ConvertedArgs.reserve(NumParams); 15174 else 15175 ConvertedArgs.reserve(NumArgs); 15176 15177 VariadicCallType CallType = 15178 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 15179 SmallVector<Expr *, 8> AllArgs; 15180 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 15181 Proto, 0, 15182 llvm::makeArrayRef(Args, NumArgs), 15183 AllArgs, 15184 CallType, AllowExplicit, 15185 IsListInitialization); 15186 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 15187 15188 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 15189 15190 CheckConstructorCall(Constructor, 15191 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 15192 Proto, Loc); 15193 15194 return Invalid; 15195 } 15196 15197 static inline bool 15198 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 15199 const FunctionDecl *FnDecl) { 15200 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 15201 if (isa<NamespaceDecl>(DC)) { 15202 return SemaRef.Diag(FnDecl->getLocation(), 15203 diag::err_operator_new_delete_declared_in_namespace) 15204 << FnDecl->getDeclName(); 15205 } 15206 15207 if (isa<TranslationUnitDecl>(DC) && 15208 FnDecl->getStorageClass() == SC_Static) { 15209 return SemaRef.Diag(FnDecl->getLocation(), 15210 diag::err_operator_new_delete_declared_static) 15211 << FnDecl->getDeclName(); 15212 } 15213 15214 return false; 15215 } 15216 15217 static QualType 15218 RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) { 15219 QualType QTy = PtrTy->getPointeeType(); 15220 QTy = SemaRef.Context.removeAddrSpaceQualType(QTy); 15221 return SemaRef.Context.getPointerType(QTy); 15222 } 15223 15224 static inline bool 15225 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 15226 CanQualType ExpectedResultType, 15227 CanQualType ExpectedFirstParamType, 15228 unsigned DependentParamTypeDiag, 15229 unsigned InvalidParamTypeDiag) { 15230 QualType ResultType = 15231 FnDecl->getType()->castAs<FunctionType>()->getReturnType(); 15232 15233 // The operator is valid on any address space for OpenCL. 15234 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 15235 if (auto *PtrTy = ResultType->getAs<PointerType>()) { 15236 ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 15237 } 15238 } 15239 15240 // Check that the result type is what we expect. 15241 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) { 15242 // Reject even if the type is dependent; an operator delete function is 15243 // required to have a non-dependent result type. 15244 return SemaRef.Diag( 15245 FnDecl->getLocation(), 15246 ResultType->isDependentType() 15247 ? diag::err_operator_new_delete_dependent_result_type 15248 : diag::err_operator_new_delete_invalid_result_type) 15249 << FnDecl->getDeclName() << ExpectedResultType; 15250 } 15251 15252 // A function template must have at least 2 parameters. 15253 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 15254 return SemaRef.Diag(FnDecl->getLocation(), 15255 diag::err_operator_new_delete_template_too_few_parameters) 15256 << FnDecl->getDeclName(); 15257 15258 // The function decl must have at least 1 parameter. 15259 if (FnDecl->getNumParams() == 0) 15260 return SemaRef.Diag(FnDecl->getLocation(), 15261 diag::err_operator_new_delete_too_few_parameters) 15262 << FnDecl->getDeclName(); 15263 15264 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 15265 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 15266 // The operator is valid on any address space for OpenCL. 15267 if (auto *PtrTy = 15268 FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) { 15269 FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 15270 } 15271 } 15272 15273 // Check that the first parameter type is what we expect. 15274 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 15275 ExpectedFirstParamType) { 15276 // The first parameter type is not allowed to be dependent. As a tentative 15277 // DR resolution, we allow a dependent parameter type if it is the right 15278 // type anyway, to allow destroying operator delete in class templates. 15279 return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType() 15280 ? DependentParamTypeDiag 15281 : InvalidParamTypeDiag) 15282 << FnDecl->getDeclName() << ExpectedFirstParamType; 15283 } 15284 15285 return false; 15286 } 15287 15288 static bool 15289 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 15290 // C++ [basic.stc.dynamic.allocation]p1: 15291 // A program is ill-formed if an allocation function is declared in a 15292 // namespace scope other than global scope or declared static in global 15293 // scope. 15294 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 15295 return true; 15296 15297 CanQualType SizeTy = 15298 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 15299 15300 // C++ [basic.stc.dynamic.allocation]p1: 15301 // The return type shall be void*. The first parameter shall have type 15302 // std::size_t. 15303 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 15304 SizeTy, 15305 diag::err_operator_new_dependent_param_type, 15306 diag::err_operator_new_param_type)) 15307 return true; 15308 15309 // C++ [basic.stc.dynamic.allocation]p1: 15310 // The first parameter shall not have an associated default argument. 15311 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 15312 return SemaRef.Diag(FnDecl->getLocation(), 15313 diag::err_operator_new_default_arg) 15314 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 15315 15316 return false; 15317 } 15318 15319 static bool 15320 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 15321 // C++ [basic.stc.dynamic.deallocation]p1: 15322 // A program is ill-formed if deallocation functions are declared in a 15323 // namespace scope other than global scope or declared static in global 15324 // scope. 15325 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 15326 return true; 15327 15328 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl); 15329 15330 // C++ P0722: 15331 // Within a class C, the first parameter of a destroying operator delete 15332 // shall be of type C *. The first parameter of any other deallocation 15333 // function shall be of type void *. 15334 CanQualType ExpectedFirstParamType = 15335 MD && MD->isDestroyingOperatorDelete() 15336 ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType( 15337 SemaRef.Context.getRecordType(MD->getParent()))) 15338 : SemaRef.Context.VoidPtrTy; 15339 15340 // C++ [basic.stc.dynamic.deallocation]p2: 15341 // Each deallocation function shall return void 15342 if (CheckOperatorNewDeleteTypes( 15343 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType, 15344 diag::err_operator_delete_dependent_param_type, 15345 diag::err_operator_delete_param_type)) 15346 return true; 15347 15348 // C++ P0722: 15349 // A destroying operator delete shall be a usual deallocation function. 15350 if (MD && !MD->getParent()->isDependentContext() && 15351 MD->isDestroyingOperatorDelete() && 15352 !SemaRef.isUsualDeallocationFunction(MD)) { 15353 SemaRef.Diag(MD->getLocation(), 15354 diag::err_destroying_operator_delete_not_usual); 15355 return true; 15356 } 15357 15358 return false; 15359 } 15360 15361 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 15362 /// of this overloaded operator is well-formed. If so, returns false; 15363 /// otherwise, emits appropriate diagnostics and returns true. 15364 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 15365 assert(FnDecl && FnDecl->isOverloadedOperator() && 15366 "Expected an overloaded operator declaration"); 15367 15368 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 15369 15370 // C++ [over.oper]p5: 15371 // The allocation and deallocation functions, operator new, 15372 // operator new[], operator delete and operator delete[], are 15373 // described completely in 3.7.3. The attributes and restrictions 15374 // found in the rest of this subclause do not apply to them unless 15375 // explicitly stated in 3.7.3. 15376 if (Op == OO_Delete || Op == OO_Array_Delete) 15377 return CheckOperatorDeleteDeclaration(*this, FnDecl); 15378 15379 if (Op == OO_New || Op == OO_Array_New) 15380 return CheckOperatorNewDeclaration(*this, FnDecl); 15381 15382 // C++ [over.oper]p6: 15383 // An operator function shall either be a non-static member 15384 // function or be a non-member function and have at least one 15385 // parameter whose type is a class, a reference to a class, an 15386 // enumeration, or a reference to an enumeration. 15387 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 15388 if (MethodDecl->isStatic()) 15389 return Diag(FnDecl->getLocation(), 15390 diag::err_operator_overload_static) << FnDecl->getDeclName(); 15391 } else { 15392 bool ClassOrEnumParam = false; 15393 for (auto Param : FnDecl->parameters()) { 15394 QualType ParamType = Param->getType().getNonReferenceType(); 15395 if (ParamType->isDependentType() || ParamType->isRecordType() || 15396 ParamType->isEnumeralType()) { 15397 ClassOrEnumParam = true; 15398 break; 15399 } 15400 } 15401 15402 if (!ClassOrEnumParam) 15403 return Diag(FnDecl->getLocation(), 15404 diag::err_operator_overload_needs_class_or_enum) 15405 << FnDecl->getDeclName(); 15406 } 15407 15408 // C++ [over.oper]p8: 15409 // An operator function cannot have default arguments (8.3.6), 15410 // except where explicitly stated below. 15411 // 15412 // Only the function-call operator allows default arguments 15413 // (C++ [over.call]p1). 15414 if (Op != OO_Call) { 15415 for (auto Param : FnDecl->parameters()) { 15416 if (Param->hasDefaultArg()) 15417 return Diag(Param->getLocation(), 15418 diag::err_operator_overload_default_arg) 15419 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 15420 } 15421 } 15422 15423 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 15424 { false, false, false } 15425 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 15426 , { Unary, Binary, MemberOnly } 15427 #include "clang/Basic/OperatorKinds.def" 15428 }; 15429 15430 bool CanBeUnaryOperator = OperatorUses[Op][0]; 15431 bool CanBeBinaryOperator = OperatorUses[Op][1]; 15432 bool MustBeMemberOperator = OperatorUses[Op][2]; 15433 15434 // C++ [over.oper]p8: 15435 // [...] Operator functions cannot have more or fewer parameters 15436 // than the number required for the corresponding operator, as 15437 // described in the rest of this subclause. 15438 unsigned NumParams = FnDecl->getNumParams() 15439 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 15440 if (Op != OO_Call && 15441 ((NumParams == 1 && !CanBeUnaryOperator) || 15442 (NumParams == 2 && !CanBeBinaryOperator) || 15443 (NumParams < 1) || (NumParams > 2))) { 15444 // We have the wrong number of parameters. 15445 unsigned ErrorKind; 15446 if (CanBeUnaryOperator && CanBeBinaryOperator) { 15447 ErrorKind = 2; // 2 -> unary or binary. 15448 } else if (CanBeUnaryOperator) { 15449 ErrorKind = 0; // 0 -> unary 15450 } else { 15451 assert(CanBeBinaryOperator && 15452 "All non-call overloaded operators are unary or binary!"); 15453 ErrorKind = 1; // 1 -> binary 15454 } 15455 15456 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 15457 << FnDecl->getDeclName() << NumParams << ErrorKind; 15458 } 15459 15460 // Overloaded operators other than operator() cannot be variadic. 15461 if (Op != OO_Call && 15462 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) { 15463 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 15464 << FnDecl->getDeclName(); 15465 } 15466 15467 // Some operators must be non-static member functions. 15468 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 15469 return Diag(FnDecl->getLocation(), 15470 diag::err_operator_overload_must_be_member) 15471 << FnDecl->getDeclName(); 15472 } 15473 15474 // C++ [over.inc]p1: 15475 // The user-defined function called operator++ implements the 15476 // prefix and postfix ++ operator. If this function is a member 15477 // function with no parameters, or a non-member function with one 15478 // parameter of class or enumeration type, it defines the prefix 15479 // increment operator ++ for objects of that type. If the function 15480 // is a member function with one parameter (which shall be of type 15481 // int) or a non-member function with two parameters (the second 15482 // of which shall be of type int), it defines the postfix 15483 // increment operator ++ for objects of that type. 15484 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 15485 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 15486 QualType ParamType = LastParam->getType(); 15487 15488 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 15489 !ParamType->isDependentType()) 15490 return Diag(LastParam->getLocation(), 15491 diag::err_operator_overload_post_incdec_must_be_int) 15492 << LastParam->getType() << (Op == OO_MinusMinus); 15493 } 15494 15495 return false; 15496 } 15497 15498 static bool 15499 checkLiteralOperatorTemplateParameterList(Sema &SemaRef, 15500 FunctionTemplateDecl *TpDecl) { 15501 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters(); 15502 15503 // Must have one or two template parameters. 15504 if (TemplateParams->size() == 1) { 15505 NonTypeTemplateParmDecl *PmDecl = 15506 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0)); 15507 15508 // The template parameter must be a char parameter pack. 15509 if (PmDecl && PmDecl->isTemplateParameterPack() && 15510 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy)) 15511 return false; 15512 15513 } else if (TemplateParams->size() == 2) { 15514 TemplateTypeParmDecl *PmType = 15515 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0)); 15516 NonTypeTemplateParmDecl *PmArgs = 15517 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1)); 15518 15519 // The second template parameter must be a parameter pack with the 15520 // first template parameter as its type. 15521 if (PmType && PmArgs && !PmType->isTemplateParameterPack() && 15522 PmArgs->isTemplateParameterPack()) { 15523 const TemplateTypeParmType *TArgs = 15524 PmArgs->getType()->getAs<TemplateTypeParmType>(); 15525 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 15526 TArgs->getIndex() == PmType->getIndex()) { 15527 if (!SemaRef.inTemplateInstantiation()) 15528 SemaRef.Diag(TpDecl->getLocation(), 15529 diag::ext_string_literal_operator_template); 15530 return false; 15531 } 15532 } 15533 } 15534 15535 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(), 15536 diag::err_literal_operator_template) 15537 << TpDecl->getTemplateParameters()->getSourceRange(); 15538 return true; 15539 } 15540 15541 /// CheckLiteralOperatorDeclaration - Check whether the declaration 15542 /// of this literal operator function is well-formed. If so, returns 15543 /// false; otherwise, emits appropriate diagnostics and returns true. 15544 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 15545 if (isa<CXXMethodDecl>(FnDecl)) { 15546 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 15547 << FnDecl->getDeclName(); 15548 return true; 15549 } 15550 15551 if (FnDecl->isExternC()) { 15552 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 15553 if (const LinkageSpecDecl *LSD = 15554 FnDecl->getDeclContext()->getExternCContext()) 15555 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here); 15556 return true; 15557 } 15558 15559 // This might be the definition of a literal operator template. 15560 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 15561 15562 // This might be a specialization of a literal operator template. 15563 if (!TpDecl) 15564 TpDecl = FnDecl->getPrimaryTemplate(); 15565 15566 // template <char...> type operator "" name() and 15567 // template <class T, T...> type operator "" name() are the only valid 15568 // template signatures, and the only valid signatures with no parameters. 15569 if (TpDecl) { 15570 if (FnDecl->param_size() != 0) { 15571 Diag(FnDecl->getLocation(), 15572 diag::err_literal_operator_template_with_params); 15573 return true; 15574 } 15575 15576 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl)) 15577 return true; 15578 15579 } else if (FnDecl->param_size() == 1) { 15580 const ParmVarDecl *Param = FnDecl->getParamDecl(0); 15581 15582 QualType ParamType = Param->getType().getUnqualifiedType(); 15583 15584 // Only unsigned long long int, long double, any character type, and const 15585 // char * are allowed as the only parameters. 15586 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) || 15587 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) || 15588 Context.hasSameType(ParamType, Context.CharTy) || 15589 Context.hasSameType(ParamType, Context.WideCharTy) || 15590 Context.hasSameType(ParamType, Context.Char8Ty) || 15591 Context.hasSameType(ParamType, Context.Char16Ty) || 15592 Context.hasSameType(ParamType, Context.Char32Ty)) { 15593 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) { 15594 QualType InnerType = Ptr->getPointeeType(); 15595 15596 // Pointer parameter must be a const char *. 15597 if (!(Context.hasSameType(InnerType.getUnqualifiedType(), 15598 Context.CharTy) && 15599 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) { 15600 Diag(Param->getSourceRange().getBegin(), 15601 diag::err_literal_operator_param) 15602 << ParamType << "'const char *'" << Param->getSourceRange(); 15603 return true; 15604 } 15605 15606 } else if (ParamType->isRealFloatingType()) { 15607 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 15608 << ParamType << Context.LongDoubleTy << Param->getSourceRange(); 15609 return true; 15610 15611 } else if (ParamType->isIntegerType()) { 15612 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 15613 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange(); 15614 return true; 15615 15616 } else { 15617 Diag(Param->getSourceRange().getBegin(), 15618 diag::err_literal_operator_invalid_param) 15619 << ParamType << Param->getSourceRange(); 15620 return true; 15621 } 15622 15623 } else if (FnDecl->param_size() == 2) { 15624 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 15625 15626 // First, verify that the first parameter is correct. 15627 15628 QualType FirstParamType = (*Param)->getType().getUnqualifiedType(); 15629 15630 // Two parameter function must have a pointer to const as a 15631 // first parameter; let's strip those qualifiers. 15632 const PointerType *PT = FirstParamType->getAs<PointerType>(); 15633 15634 if (!PT) { 15635 Diag((*Param)->getSourceRange().getBegin(), 15636 diag::err_literal_operator_param) 15637 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 15638 return true; 15639 } 15640 15641 QualType PointeeType = PT->getPointeeType(); 15642 // First parameter must be const 15643 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) { 15644 Diag((*Param)->getSourceRange().getBegin(), 15645 diag::err_literal_operator_param) 15646 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 15647 return true; 15648 } 15649 15650 QualType InnerType = PointeeType.getUnqualifiedType(); 15651 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and 15652 // const char32_t* are allowed as the first parameter to a two-parameter 15653 // function 15654 if (!(Context.hasSameType(InnerType, Context.CharTy) || 15655 Context.hasSameType(InnerType, Context.WideCharTy) || 15656 Context.hasSameType(InnerType, Context.Char8Ty) || 15657 Context.hasSameType(InnerType, Context.Char16Ty) || 15658 Context.hasSameType(InnerType, Context.Char32Ty))) { 15659 Diag((*Param)->getSourceRange().getBegin(), 15660 diag::err_literal_operator_param) 15661 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 15662 return true; 15663 } 15664 15665 // Move on to the second and final parameter. 15666 ++Param; 15667 15668 // The second parameter must be a std::size_t. 15669 QualType SecondParamType = (*Param)->getType().getUnqualifiedType(); 15670 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) { 15671 Diag((*Param)->getSourceRange().getBegin(), 15672 diag::err_literal_operator_param) 15673 << SecondParamType << Context.getSizeType() 15674 << (*Param)->getSourceRange(); 15675 return true; 15676 } 15677 } else { 15678 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count); 15679 return true; 15680 } 15681 15682 // Parameters are good. 15683 15684 // A parameter-declaration-clause containing a default argument is not 15685 // equivalent to any of the permitted forms. 15686 for (auto Param : FnDecl->parameters()) { 15687 if (Param->hasDefaultArg()) { 15688 Diag(Param->getDefaultArgRange().getBegin(), 15689 diag::err_literal_operator_default_argument) 15690 << Param->getDefaultArgRange(); 15691 break; 15692 } 15693 } 15694 15695 StringRef LiteralName 15696 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 15697 if (LiteralName[0] != '_' && 15698 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) { 15699 // C++11 [usrlit.suffix]p1: 15700 // Literal suffix identifiers that do not start with an underscore 15701 // are reserved for future standardization. 15702 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 15703 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 15704 } 15705 15706 return false; 15707 } 15708 15709 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 15710 /// linkage specification, including the language and (if present) 15711 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 15712 /// language string literal. LBraceLoc, if valid, provides the location of 15713 /// the '{' brace. Otherwise, this linkage specification does not 15714 /// have any braces. 15715 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 15716 Expr *LangStr, 15717 SourceLocation LBraceLoc) { 15718 StringLiteral *Lit = cast<StringLiteral>(LangStr); 15719 if (!Lit->isAscii()) { 15720 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 15721 << LangStr->getSourceRange(); 15722 return nullptr; 15723 } 15724 15725 StringRef Lang = Lit->getString(); 15726 LinkageSpecDecl::LanguageIDs Language; 15727 if (Lang == "C") 15728 Language = LinkageSpecDecl::lang_c; 15729 else if (Lang == "C++") 15730 Language = LinkageSpecDecl::lang_cxx; 15731 else { 15732 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 15733 << LangStr->getSourceRange(); 15734 return nullptr; 15735 } 15736 15737 // FIXME: Add all the various semantics of linkage specifications 15738 15739 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 15740 LangStr->getExprLoc(), Language, 15741 LBraceLoc.isValid()); 15742 CurContext->addDecl(D); 15743 PushDeclContext(S, D); 15744 return D; 15745 } 15746 15747 /// ActOnFinishLinkageSpecification - Complete the definition of 15748 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 15749 /// valid, it's the position of the closing '}' brace in a linkage 15750 /// specification that uses braces. 15751 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 15752 Decl *LinkageSpec, 15753 SourceLocation RBraceLoc) { 15754 if (RBraceLoc.isValid()) { 15755 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 15756 LSDecl->setRBraceLoc(RBraceLoc); 15757 } 15758 PopDeclContext(); 15759 return LinkageSpec; 15760 } 15761 15762 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 15763 const ParsedAttributesView &AttrList, 15764 SourceLocation SemiLoc) { 15765 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 15766 // Attribute declarations appertain to empty declaration so we handle 15767 // them here. 15768 ProcessDeclAttributeList(S, ED, AttrList); 15769 15770 CurContext->addDecl(ED); 15771 return ED; 15772 } 15773 15774 /// Perform semantic analysis for the variable declaration that 15775 /// occurs within a C++ catch clause, returning the newly-created 15776 /// variable. 15777 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 15778 TypeSourceInfo *TInfo, 15779 SourceLocation StartLoc, 15780 SourceLocation Loc, 15781 IdentifierInfo *Name) { 15782 bool Invalid = false; 15783 QualType ExDeclType = TInfo->getType(); 15784 15785 // Arrays and functions decay. 15786 if (ExDeclType->isArrayType()) 15787 ExDeclType = Context.getArrayDecayedType(ExDeclType); 15788 else if (ExDeclType->isFunctionType()) 15789 ExDeclType = Context.getPointerType(ExDeclType); 15790 15791 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 15792 // The exception-declaration shall not denote a pointer or reference to an 15793 // incomplete type, other than [cv] void*. 15794 // N2844 forbids rvalue references. 15795 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 15796 Diag(Loc, diag::err_catch_rvalue_ref); 15797 Invalid = true; 15798 } 15799 15800 if (ExDeclType->isVariablyModifiedType()) { 15801 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType; 15802 Invalid = true; 15803 } 15804 15805 QualType BaseType = ExDeclType; 15806 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 15807 unsigned DK = diag::err_catch_incomplete; 15808 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 15809 BaseType = Ptr->getPointeeType(); 15810 Mode = 1; 15811 DK = diag::err_catch_incomplete_ptr; 15812 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 15813 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 15814 BaseType = Ref->getPointeeType(); 15815 Mode = 2; 15816 DK = diag::err_catch_incomplete_ref; 15817 } 15818 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 15819 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 15820 Invalid = true; 15821 15822 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) { 15823 Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType; 15824 Invalid = true; 15825 } 15826 15827 if (!Invalid && !ExDeclType->isDependentType() && 15828 RequireNonAbstractType(Loc, ExDeclType, 15829 diag::err_abstract_type_in_decl, 15830 AbstractVariableType)) 15831 Invalid = true; 15832 15833 // Only the non-fragile NeXT runtime currently supports C++ catches 15834 // of ObjC types, and no runtime supports catching ObjC types by value. 15835 if (!Invalid && getLangOpts().ObjC) { 15836 QualType T = ExDeclType; 15837 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 15838 T = RT->getPointeeType(); 15839 15840 if (T->isObjCObjectType()) { 15841 Diag(Loc, diag::err_objc_object_catch); 15842 Invalid = true; 15843 } else if (T->isObjCObjectPointerType()) { 15844 // FIXME: should this be a test for macosx-fragile specifically? 15845 if (getLangOpts().ObjCRuntime.isFragile()) 15846 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 15847 } 15848 } 15849 15850 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 15851 ExDeclType, TInfo, SC_None); 15852 ExDecl->setExceptionVariable(true); 15853 15854 // In ARC, infer 'retaining' for variables of retainable type. 15855 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 15856 Invalid = true; 15857 15858 if (!Invalid && !ExDeclType->isDependentType()) { 15859 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 15860 // Insulate this from anything else we might currently be parsing. 15861 EnterExpressionEvaluationContext scope( 15862 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 15863 15864 // C++ [except.handle]p16: 15865 // The object declared in an exception-declaration or, if the 15866 // exception-declaration does not specify a name, a temporary (12.2) is 15867 // copy-initialized (8.5) from the exception object. [...] 15868 // The object is destroyed when the handler exits, after the destruction 15869 // of any automatic objects initialized within the handler. 15870 // 15871 // We just pretend to initialize the object with itself, then make sure 15872 // it can be destroyed later. 15873 QualType initType = Context.getExceptionObjectType(ExDeclType); 15874 15875 InitializedEntity entity = 15876 InitializedEntity::InitializeVariable(ExDecl); 15877 InitializationKind initKind = 15878 InitializationKind::CreateCopy(Loc, SourceLocation()); 15879 15880 Expr *opaqueValue = 15881 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 15882 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 15883 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 15884 if (result.isInvalid()) 15885 Invalid = true; 15886 else { 15887 // If the constructor used was non-trivial, set this as the 15888 // "initializer". 15889 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 15890 if (!construct->getConstructor()->isTrivial()) { 15891 Expr *init = MaybeCreateExprWithCleanups(construct); 15892 ExDecl->setInit(init); 15893 } 15894 15895 // And make sure it's destructable. 15896 FinalizeVarWithDestructor(ExDecl, recordType); 15897 } 15898 } 15899 } 15900 15901 if (Invalid) 15902 ExDecl->setInvalidDecl(); 15903 15904 return ExDecl; 15905 } 15906 15907 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 15908 /// handler. 15909 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 15910 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 15911 bool Invalid = D.isInvalidType(); 15912 15913 // Check for unexpanded parameter packs. 15914 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 15915 UPPC_ExceptionType)) { 15916 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 15917 D.getIdentifierLoc()); 15918 Invalid = true; 15919 } 15920 15921 IdentifierInfo *II = D.getIdentifier(); 15922 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 15923 LookupOrdinaryName, 15924 ForVisibleRedeclaration)) { 15925 // The scope should be freshly made just for us. There is just no way 15926 // it contains any previous declaration, except for function parameters in 15927 // a function-try-block's catch statement. 15928 assert(!S->isDeclScope(PrevDecl)); 15929 if (isDeclInScope(PrevDecl, CurContext, S)) { 15930 Diag(D.getIdentifierLoc(), diag::err_redefinition) 15931 << D.getIdentifier(); 15932 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 15933 Invalid = true; 15934 } else if (PrevDecl->isTemplateParameter()) 15935 // Maybe we will complain about the shadowed template parameter. 15936 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 15937 } 15938 15939 if (D.getCXXScopeSpec().isSet() && !Invalid) { 15940 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 15941 << D.getCXXScopeSpec().getRange(); 15942 Invalid = true; 15943 } 15944 15945 VarDecl *ExDecl = BuildExceptionDeclaration( 15946 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier()); 15947 if (Invalid) 15948 ExDecl->setInvalidDecl(); 15949 15950 // Add the exception declaration into this scope. 15951 if (II) 15952 PushOnScopeChains(ExDecl, S); 15953 else 15954 CurContext->addDecl(ExDecl); 15955 15956 ProcessDeclAttributes(S, ExDecl, D); 15957 return ExDecl; 15958 } 15959 15960 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 15961 Expr *AssertExpr, 15962 Expr *AssertMessageExpr, 15963 SourceLocation RParenLoc) { 15964 StringLiteral *AssertMessage = 15965 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 15966 15967 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 15968 return nullptr; 15969 15970 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 15971 AssertMessage, RParenLoc, false); 15972 } 15973 15974 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 15975 Expr *AssertExpr, 15976 StringLiteral *AssertMessage, 15977 SourceLocation RParenLoc, 15978 bool Failed) { 15979 assert(AssertExpr != nullptr && "Expected non-null condition"); 15980 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 15981 !Failed) { 15982 // In a static_assert-declaration, the constant-expression shall be a 15983 // constant expression that can be contextually converted to bool. 15984 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 15985 if (Converted.isInvalid()) 15986 Failed = true; 15987 15988 ExprResult FullAssertExpr = 15989 ActOnFinishFullExpr(Converted.get(), StaticAssertLoc, 15990 /*DiscardedValue*/ false, 15991 /*IsConstexpr*/ true); 15992 if (FullAssertExpr.isInvalid()) 15993 Failed = true; 15994 else 15995 AssertExpr = FullAssertExpr.get(); 15996 15997 llvm::APSInt Cond; 15998 if (!Failed && VerifyIntegerConstantExpression( 15999 AssertExpr, &Cond, 16000 diag::err_static_assert_expression_is_not_constant) 16001 .isInvalid()) 16002 Failed = true; 16003 16004 if (!Failed && !Cond) { 16005 SmallString<256> MsgBuffer; 16006 llvm::raw_svector_ostream Msg(MsgBuffer); 16007 if (AssertMessage) 16008 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 16009 16010 Expr *InnerCond = nullptr; 16011 std::string InnerCondDescription; 16012 std::tie(InnerCond, InnerCondDescription) = 16013 findFailedBooleanCondition(Converted.get()); 16014 if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) { 16015 // Drill down into concept specialization expressions to see why they 16016 // weren't satisfied. 16017 Diag(StaticAssertLoc, diag::err_static_assert_failed) 16018 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 16019 ConstraintSatisfaction Satisfaction; 16020 if (!CheckConstraintSatisfaction(InnerCond, Satisfaction)) 16021 DiagnoseUnsatisfiedConstraint(Satisfaction); 16022 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond) 16023 && !isa<IntegerLiteral>(InnerCond)) { 16024 Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed) 16025 << InnerCondDescription << !AssertMessage 16026 << Msg.str() << InnerCond->getSourceRange(); 16027 } else { 16028 Diag(StaticAssertLoc, diag::err_static_assert_failed) 16029 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 16030 } 16031 Failed = true; 16032 } 16033 } else { 16034 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc, 16035 /*DiscardedValue*/false, 16036 /*IsConstexpr*/true); 16037 if (FullAssertExpr.isInvalid()) 16038 Failed = true; 16039 else 16040 AssertExpr = FullAssertExpr.get(); 16041 } 16042 16043 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 16044 AssertExpr, AssertMessage, RParenLoc, 16045 Failed); 16046 16047 CurContext->addDecl(Decl); 16048 return Decl; 16049 } 16050 16051 /// Perform semantic analysis of the given friend type declaration. 16052 /// 16053 /// \returns A friend declaration that. 16054 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 16055 SourceLocation FriendLoc, 16056 TypeSourceInfo *TSInfo) { 16057 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 16058 16059 QualType T = TSInfo->getType(); 16060 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 16061 16062 // C++03 [class.friend]p2: 16063 // An elaborated-type-specifier shall be used in a friend declaration 16064 // for a class.* 16065 // 16066 // * The class-key of the elaborated-type-specifier is required. 16067 if (!CodeSynthesisContexts.empty()) { 16068 // Do not complain about the form of friend template types during any kind 16069 // of code synthesis. For template instantiation, we will have complained 16070 // when the template was defined. 16071 } else { 16072 if (!T->isElaboratedTypeSpecifier()) { 16073 // If we evaluated the type to a record type, suggest putting 16074 // a tag in front. 16075 if (const RecordType *RT = T->getAs<RecordType>()) { 16076 RecordDecl *RD = RT->getDecl(); 16077 16078 SmallString<16> InsertionText(" "); 16079 InsertionText += RD->getKindName(); 16080 16081 Diag(TypeRange.getBegin(), 16082 getLangOpts().CPlusPlus11 ? 16083 diag::warn_cxx98_compat_unelaborated_friend_type : 16084 diag::ext_unelaborated_friend_type) 16085 << (unsigned) RD->getTagKind() 16086 << T 16087 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc), 16088 InsertionText); 16089 } else { 16090 Diag(FriendLoc, 16091 getLangOpts().CPlusPlus11 ? 16092 diag::warn_cxx98_compat_nonclass_type_friend : 16093 diag::ext_nonclass_type_friend) 16094 << T 16095 << TypeRange; 16096 } 16097 } else if (T->getAs<EnumType>()) { 16098 Diag(FriendLoc, 16099 getLangOpts().CPlusPlus11 ? 16100 diag::warn_cxx98_compat_enum_friend : 16101 diag::ext_enum_friend) 16102 << T 16103 << TypeRange; 16104 } 16105 16106 // C++11 [class.friend]p3: 16107 // A friend declaration that does not declare a function shall have one 16108 // of the following forms: 16109 // friend elaborated-type-specifier ; 16110 // friend simple-type-specifier ; 16111 // friend typename-specifier ; 16112 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 16113 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 16114 } 16115 16116 // If the type specifier in a friend declaration designates a (possibly 16117 // cv-qualified) class type, that class is declared as a friend; otherwise, 16118 // the friend declaration is ignored. 16119 return FriendDecl::Create(Context, CurContext, 16120 TSInfo->getTypeLoc().getBeginLoc(), TSInfo, 16121 FriendLoc); 16122 } 16123 16124 /// Handle a friend tag declaration where the scope specifier was 16125 /// templated. 16126 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 16127 unsigned TagSpec, SourceLocation TagLoc, 16128 CXXScopeSpec &SS, IdentifierInfo *Name, 16129 SourceLocation NameLoc, 16130 const ParsedAttributesView &Attr, 16131 MultiTemplateParamsArg TempParamLists) { 16132 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 16133 16134 bool IsMemberSpecialization = false; 16135 bool Invalid = false; 16136 16137 if (TemplateParameterList *TemplateParams = 16138 MatchTemplateParametersToScopeSpecifier( 16139 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 16140 IsMemberSpecialization, Invalid)) { 16141 if (TemplateParams->size() > 0) { 16142 // This is a declaration of a class template. 16143 if (Invalid) 16144 return nullptr; 16145 16146 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 16147 NameLoc, Attr, TemplateParams, AS_public, 16148 /*ModulePrivateLoc=*/SourceLocation(), 16149 FriendLoc, TempParamLists.size() - 1, 16150 TempParamLists.data()).get(); 16151 } else { 16152 // The "template<>" header is extraneous. 16153 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 16154 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 16155 IsMemberSpecialization = true; 16156 } 16157 } 16158 16159 if (Invalid) return nullptr; 16160 16161 bool isAllExplicitSpecializations = true; 16162 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 16163 if (TempParamLists[I]->size()) { 16164 isAllExplicitSpecializations = false; 16165 break; 16166 } 16167 } 16168 16169 // FIXME: don't ignore attributes. 16170 16171 // If it's explicit specializations all the way down, just forget 16172 // about the template header and build an appropriate non-templated 16173 // friend. TODO: for source fidelity, remember the headers. 16174 if (isAllExplicitSpecializations) { 16175 if (SS.isEmpty()) { 16176 bool Owned = false; 16177 bool IsDependent = false; 16178 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 16179 Attr, AS_public, 16180 /*ModulePrivateLoc=*/SourceLocation(), 16181 MultiTemplateParamsArg(), Owned, IsDependent, 16182 /*ScopedEnumKWLoc=*/SourceLocation(), 16183 /*ScopedEnumUsesClassTag=*/false, 16184 /*UnderlyingType=*/TypeResult(), 16185 /*IsTypeSpecifier=*/false, 16186 /*IsTemplateParamOrArg=*/false); 16187 } 16188 16189 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 16190 ElaboratedTypeKeyword Keyword 16191 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 16192 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 16193 *Name, NameLoc); 16194 if (T.isNull()) 16195 return nullptr; 16196 16197 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 16198 if (isa<DependentNameType>(T)) { 16199 DependentNameTypeLoc TL = 16200 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 16201 TL.setElaboratedKeywordLoc(TagLoc); 16202 TL.setQualifierLoc(QualifierLoc); 16203 TL.setNameLoc(NameLoc); 16204 } else { 16205 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 16206 TL.setElaboratedKeywordLoc(TagLoc); 16207 TL.setQualifierLoc(QualifierLoc); 16208 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 16209 } 16210 16211 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 16212 TSI, FriendLoc, TempParamLists); 16213 Friend->setAccess(AS_public); 16214 CurContext->addDecl(Friend); 16215 return Friend; 16216 } 16217 16218 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 16219 16220 16221 16222 // Handle the case of a templated-scope friend class. e.g. 16223 // template <class T> class A<T>::B; 16224 // FIXME: we don't support these right now. 16225 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 16226 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 16227 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 16228 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 16229 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 16230 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 16231 TL.setElaboratedKeywordLoc(TagLoc); 16232 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 16233 TL.setNameLoc(NameLoc); 16234 16235 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 16236 TSI, FriendLoc, TempParamLists); 16237 Friend->setAccess(AS_public); 16238 Friend->setUnsupportedFriend(true); 16239 CurContext->addDecl(Friend); 16240 return Friend; 16241 } 16242 16243 /// Handle a friend type declaration. This works in tandem with 16244 /// ActOnTag. 16245 /// 16246 /// Notes on friend class templates: 16247 /// 16248 /// We generally treat friend class declarations as if they were 16249 /// declaring a class. So, for example, the elaborated type specifier 16250 /// in a friend declaration is required to obey the restrictions of a 16251 /// class-head (i.e. no typedefs in the scope chain), template 16252 /// parameters are required to match up with simple template-ids, &c. 16253 /// However, unlike when declaring a template specialization, it's 16254 /// okay to refer to a template specialization without an empty 16255 /// template parameter declaration, e.g. 16256 /// friend class A<T>::B<unsigned>; 16257 /// We permit this as a special case; if there are any template 16258 /// parameters present at all, require proper matching, i.e. 16259 /// template <> template \<class T> friend class A<int>::B; 16260 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 16261 MultiTemplateParamsArg TempParams) { 16262 SourceLocation Loc = DS.getBeginLoc(); 16263 16264 assert(DS.isFriendSpecified()); 16265 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 16266 16267 // C++ [class.friend]p3: 16268 // A friend declaration that does not declare a function shall have one of 16269 // the following forms: 16270 // friend elaborated-type-specifier ; 16271 // friend simple-type-specifier ; 16272 // friend typename-specifier ; 16273 // 16274 // Any declaration with a type qualifier does not have that form. (It's 16275 // legal to specify a qualified type as a friend, you just can't write the 16276 // keywords.) 16277 if (DS.getTypeQualifiers()) { 16278 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 16279 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const"; 16280 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 16281 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile"; 16282 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 16283 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict"; 16284 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 16285 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic"; 16286 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 16287 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned"; 16288 } 16289 16290 // Try to convert the decl specifier to a type. This works for 16291 // friend templates because ActOnTag never produces a ClassTemplateDecl 16292 // for a TUK_Friend. 16293 Declarator TheDeclarator(DS, DeclaratorContext::MemberContext); 16294 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 16295 QualType T = TSI->getType(); 16296 if (TheDeclarator.isInvalidType()) 16297 return nullptr; 16298 16299 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 16300 return nullptr; 16301 16302 // This is definitely an error in C++98. It's probably meant to 16303 // be forbidden in C++0x, too, but the specification is just 16304 // poorly written. 16305 // 16306 // The problem is with declarations like the following: 16307 // template <T> friend A<T>::foo; 16308 // where deciding whether a class C is a friend or not now hinges 16309 // on whether there exists an instantiation of A that causes 16310 // 'foo' to equal C. There are restrictions on class-heads 16311 // (which we declare (by fiat) elaborated friend declarations to 16312 // be) that makes this tractable. 16313 // 16314 // FIXME: handle "template <> friend class A<T>;", which 16315 // is possibly well-formed? Who even knows? 16316 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 16317 Diag(Loc, diag::err_tagless_friend_type_template) 16318 << DS.getSourceRange(); 16319 return nullptr; 16320 } 16321 16322 // C++98 [class.friend]p1: A friend of a class is a function 16323 // or class that is not a member of the class . . . 16324 // This is fixed in DR77, which just barely didn't make the C++03 16325 // deadline. It's also a very silly restriction that seriously 16326 // affects inner classes and which nobody else seems to implement; 16327 // thus we never diagnose it, not even in -pedantic. 16328 // 16329 // But note that we could warn about it: it's always useless to 16330 // friend one of your own members (it's not, however, worthless to 16331 // friend a member of an arbitrary specialization of your template). 16332 16333 Decl *D; 16334 if (!TempParams.empty()) 16335 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 16336 TempParams, 16337 TSI, 16338 DS.getFriendSpecLoc()); 16339 else 16340 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 16341 16342 if (!D) 16343 return nullptr; 16344 16345 D->setAccess(AS_public); 16346 CurContext->addDecl(D); 16347 16348 return D; 16349 } 16350 16351 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 16352 MultiTemplateParamsArg TemplateParams) { 16353 const DeclSpec &DS = D.getDeclSpec(); 16354 16355 assert(DS.isFriendSpecified()); 16356 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 16357 16358 SourceLocation Loc = D.getIdentifierLoc(); 16359 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16360 16361 // C++ [class.friend]p1 16362 // A friend of a class is a function or class.... 16363 // Note that this sees through typedefs, which is intended. 16364 // It *doesn't* see through dependent types, which is correct 16365 // according to [temp.arg.type]p3: 16366 // If a declaration acquires a function type through a 16367 // type dependent on a template-parameter and this causes 16368 // a declaration that does not use the syntactic form of a 16369 // function declarator to have a function type, the program 16370 // is ill-formed. 16371 if (!TInfo->getType()->isFunctionType()) { 16372 Diag(Loc, diag::err_unexpected_friend); 16373 16374 // It might be worthwhile to try to recover by creating an 16375 // appropriate declaration. 16376 return nullptr; 16377 } 16378 16379 // C++ [namespace.memdef]p3 16380 // - If a friend declaration in a non-local class first declares a 16381 // class or function, the friend class or function is a member 16382 // of the innermost enclosing namespace. 16383 // - The name of the friend is not found by simple name lookup 16384 // until a matching declaration is provided in that namespace 16385 // scope (either before or after the class declaration granting 16386 // friendship). 16387 // - If a friend function is called, its name may be found by the 16388 // name lookup that considers functions from namespaces and 16389 // classes associated with the types of the function arguments. 16390 // - When looking for a prior declaration of a class or a function 16391 // declared as a friend, scopes outside the innermost enclosing 16392 // namespace scope are not considered. 16393 16394 CXXScopeSpec &SS = D.getCXXScopeSpec(); 16395 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 16396 assert(NameInfo.getName()); 16397 16398 // Check for unexpanded parameter packs. 16399 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 16400 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 16401 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 16402 return nullptr; 16403 16404 // The context we found the declaration in, or in which we should 16405 // create the declaration. 16406 DeclContext *DC; 16407 Scope *DCScope = S; 16408 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 16409 ForExternalRedeclaration); 16410 16411 // There are five cases here. 16412 // - There's no scope specifier and we're in a local class. Only look 16413 // for functions declared in the immediately-enclosing block scope. 16414 // We recover from invalid scope qualifiers as if they just weren't there. 16415 FunctionDecl *FunctionContainingLocalClass = nullptr; 16416 if ((SS.isInvalid() || !SS.isSet()) && 16417 (FunctionContainingLocalClass = 16418 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 16419 // C++11 [class.friend]p11: 16420 // If a friend declaration appears in a local class and the name 16421 // specified is an unqualified name, a prior declaration is 16422 // looked up without considering scopes that are outside the 16423 // innermost enclosing non-class scope. For a friend function 16424 // declaration, if there is no prior declaration, the program is 16425 // ill-formed. 16426 16427 // Find the innermost enclosing non-class scope. This is the block 16428 // scope containing the local class definition (or for a nested class, 16429 // the outer local class). 16430 DCScope = S->getFnParent(); 16431 16432 // Look up the function name in the scope. 16433 Previous.clear(LookupLocalFriendName); 16434 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 16435 16436 if (!Previous.empty()) { 16437 // All possible previous declarations must have the same context: 16438 // either they were declared at block scope or they are members of 16439 // one of the enclosing local classes. 16440 DC = Previous.getRepresentativeDecl()->getDeclContext(); 16441 } else { 16442 // This is ill-formed, but provide the context that we would have 16443 // declared the function in, if we were permitted to, for error recovery. 16444 DC = FunctionContainingLocalClass; 16445 } 16446 adjustContextForLocalExternDecl(DC); 16447 16448 // C++ [class.friend]p6: 16449 // A function can be defined in a friend declaration of a class if and 16450 // only if the class is a non-local class (9.8), the function name is 16451 // unqualified, and the function has namespace scope. 16452 if (D.isFunctionDefinition()) { 16453 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 16454 } 16455 16456 // - There's no scope specifier, in which case we just go to the 16457 // appropriate scope and look for a function or function template 16458 // there as appropriate. 16459 } else if (SS.isInvalid() || !SS.isSet()) { 16460 // C++11 [namespace.memdef]p3: 16461 // If the name in a friend declaration is neither qualified nor 16462 // a template-id and the declaration is a function or an 16463 // elaborated-type-specifier, the lookup to determine whether 16464 // the entity has been previously declared shall not consider 16465 // any scopes outside the innermost enclosing namespace. 16466 bool isTemplateId = 16467 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId; 16468 16469 // Find the appropriate context according to the above. 16470 DC = CurContext; 16471 16472 // Skip class contexts. If someone can cite chapter and verse 16473 // for this behavior, that would be nice --- it's what GCC and 16474 // EDG do, and it seems like a reasonable intent, but the spec 16475 // really only says that checks for unqualified existing 16476 // declarations should stop at the nearest enclosing namespace, 16477 // not that they should only consider the nearest enclosing 16478 // namespace. 16479 while (DC->isRecord()) 16480 DC = DC->getParent(); 16481 16482 DeclContext *LookupDC = DC; 16483 while (LookupDC->isTransparentContext()) 16484 LookupDC = LookupDC->getParent(); 16485 16486 while (true) { 16487 LookupQualifiedName(Previous, LookupDC); 16488 16489 if (!Previous.empty()) { 16490 DC = LookupDC; 16491 break; 16492 } 16493 16494 if (isTemplateId) { 16495 if (isa<TranslationUnitDecl>(LookupDC)) break; 16496 } else { 16497 if (LookupDC->isFileContext()) break; 16498 } 16499 LookupDC = LookupDC->getParent(); 16500 } 16501 16502 DCScope = getScopeForDeclContext(S, DC); 16503 16504 // - There's a non-dependent scope specifier, in which case we 16505 // compute it and do a previous lookup there for a function 16506 // or function template. 16507 } else if (!SS.getScopeRep()->isDependent()) { 16508 DC = computeDeclContext(SS); 16509 if (!DC) return nullptr; 16510 16511 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 16512 16513 LookupQualifiedName(Previous, DC); 16514 16515 // C++ [class.friend]p1: A friend of a class is a function or 16516 // class that is not a member of the class . . . 16517 if (DC->Equals(CurContext)) 16518 Diag(DS.getFriendSpecLoc(), 16519 getLangOpts().CPlusPlus11 ? 16520 diag::warn_cxx98_compat_friend_is_member : 16521 diag::err_friend_is_member); 16522 16523 if (D.isFunctionDefinition()) { 16524 // C++ [class.friend]p6: 16525 // A function can be defined in a friend declaration of a class if and 16526 // only if the class is a non-local class (9.8), the function name is 16527 // unqualified, and the function has namespace scope. 16528 // 16529 // FIXME: We should only do this if the scope specifier names the 16530 // innermost enclosing namespace; otherwise the fixit changes the 16531 // meaning of the code. 16532 SemaDiagnosticBuilder DB 16533 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 16534 16535 DB << SS.getScopeRep(); 16536 if (DC->isFileContext()) 16537 DB << FixItHint::CreateRemoval(SS.getRange()); 16538 SS.clear(); 16539 } 16540 16541 // - There's a scope specifier that does not match any template 16542 // parameter lists, in which case we use some arbitrary context, 16543 // create a method or method template, and wait for instantiation. 16544 // - There's a scope specifier that does match some template 16545 // parameter lists, which we don't handle right now. 16546 } else { 16547 if (D.isFunctionDefinition()) { 16548 // C++ [class.friend]p6: 16549 // A function can be defined in a friend declaration of a class if and 16550 // only if the class is a non-local class (9.8), the function name is 16551 // unqualified, and the function has namespace scope. 16552 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 16553 << SS.getScopeRep(); 16554 } 16555 16556 DC = CurContext; 16557 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 16558 } 16559 16560 if (!DC->isRecord()) { 16561 int DiagArg = -1; 16562 switch (D.getName().getKind()) { 16563 case UnqualifiedIdKind::IK_ConstructorTemplateId: 16564 case UnqualifiedIdKind::IK_ConstructorName: 16565 DiagArg = 0; 16566 break; 16567 case UnqualifiedIdKind::IK_DestructorName: 16568 DiagArg = 1; 16569 break; 16570 case UnqualifiedIdKind::IK_ConversionFunctionId: 16571 DiagArg = 2; 16572 break; 16573 case UnqualifiedIdKind::IK_DeductionGuideName: 16574 DiagArg = 3; 16575 break; 16576 case UnqualifiedIdKind::IK_Identifier: 16577 case UnqualifiedIdKind::IK_ImplicitSelfParam: 16578 case UnqualifiedIdKind::IK_LiteralOperatorId: 16579 case UnqualifiedIdKind::IK_OperatorFunctionId: 16580 case UnqualifiedIdKind::IK_TemplateId: 16581 break; 16582 } 16583 // This implies that it has to be an operator or function. 16584 if (DiagArg >= 0) { 16585 Diag(Loc, diag::err_introducing_special_friend) << DiagArg; 16586 return nullptr; 16587 } 16588 } 16589 16590 // FIXME: This is an egregious hack to cope with cases where the scope stack 16591 // does not contain the declaration context, i.e., in an out-of-line 16592 // definition of a class. 16593 Scope FakeDCScope(S, Scope::DeclScope, Diags); 16594 if (!DCScope) { 16595 FakeDCScope.setEntity(DC); 16596 DCScope = &FakeDCScope; 16597 } 16598 16599 bool AddToScope = true; 16600 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 16601 TemplateParams, AddToScope); 16602 if (!ND) return nullptr; 16603 16604 assert(ND->getLexicalDeclContext() == CurContext); 16605 16606 // If we performed typo correction, we might have added a scope specifier 16607 // and changed the decl context. 16608 DC = ND->getDeclContext(); 16609 16610 // Add the function declaration to the appropriate lookup tables, 16611 // adjusting the redeclarations list as necessary. We don't 16612 // want to do this yet if the friending class is dependent. 16613 // 16614 // Also update the scope-based lookup if the target context's 16615 // lookup context is in lexical scope. 16616 if (!CurContext->isDependentContext()) { 16617 DC = DC->getRedeclContext(); 16618 DC->makeDeclVisibleInContext(ND); 16619 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 16620 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 16621 } 16622 16623 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 16624 D.getIdentifierLoc(), ND, 16625 DS.getFriendSpecLoc()); 16626 FrD->setAccess(AS_public); 16627 CurContext->addDecl(FrD); 16628 16629 if (ND->isInvalidDecl()) { 16630 FrD->setInvalidDecl(); 16631 } else { 16632 if (DC->isRecord()) CheckFriendAccess(ND); 16633 16634 FunctionDecl *FD; 16635 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 16636 FD = FTD->getTemplatedDecl(); 16637 else 16638 FD = cast<FunctionDecl>(ND); 16639 16640 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 16641 // default argument expression, that declaration shall be a definition 16642 // and shall be the only declaration of the function or function 16643 // template in the translation unit. 16644 if (functionDeclHasDefaultArgument(FD)) { 16645 // We can't look at FD->getPreviousDecl() because it may not have been set 16646 // if we're in a dependent context. If the function is known to be a 16647 // redeclaration, we will have narrowed Previous down to the right decl. 16648 if (D.isRedeclaration()) { 16649 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 16650 Diag(Previous.getRepresentativeDecl()->getLocation(), 16651 diag::note_previous_declaration); 16652 } else if (!D.isFunctionDefinition()) 16653 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 16654 } 16655 16656 // Mark templated-scope function declarations as unsupported. 16657 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 16658 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 16659 << SS.getScopeRep() << SS.getRange() 16660 << cast<CXXRecordDecl>(CurContext); 16661 FrD->setUnsupportedFriend(true); 16662 } 16663 } 16664 16665 return ND; 16666 } 16667 16668 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 16669 AdjustDeclIfTemplate(Dcl); 16670 16671 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 16672 if (!Fn) { 16673 Diag(DelLoc, diag::err_deleted_non_function); 16674 return; 16675 } 16676 16677 // Deleted function does not have a body. 16678 Fn->setWillHaveBody(false); 16679 16680 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 16681 // Don't consider the implicit declaration we generate for explicit 16682 // specializations. FIXME: Do not generate these implicit declarations. 16683 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 16684 Prev->getPreviousDecl()) && 16685 !Prev->isDefined()) { 16686 Diag(DelLoc, diag::err_deleted_decl_not_first); 16687 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 16688 Prev->isImplicit() ? diag::note_previous_implicit_declaration 16689 : diag::note_previous_declaration); 16690 // We can't recover from this; the declaration might have already 16691 // been used. 16692 Fn->setInvalidDecl(); 16693 return; 16694 } 16695 16696 // To maintain the invariant that functions are only deleted on their first 16697 // declaration, mark the implicitly-instantiated declaration of the 16698 // explicitly-specialized function as deleted instead of marking the 16699 // instantiated redeclaration. 16700 Fn = Fn->getCanonicalDecl(); 16701 } 16702 16703 // dllimport/dllexport cannot be deleted. 16704 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 16705 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 16706 Fn->setInvalidDecl(); 16707 } 16708 16709 // C++11 [basic.start.main]p3: 16710 // A program that defines main as deleted [...] is ill-formed. 16711 if (Fn->isMain()) 16712 Diag(DelLoc, diag::err_deleted_main); 16713 16714 // C++11 [dcl.fct.def.delete]p4: 16715 // A deleted function is implicitly inline. 16716 Fn->setImplicitlyInline(); 16717 Fn->setDeletedAsWritten(); 16718 } 16719 16720 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 16721 if (!Dcl || Dcl->isInvalidDecl()) 16722 return; 16723 16724 auto *FD = dyn_cast<FunctionDecl>(Dcl); 16725 if (!FD) { 16726 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) { 16727 if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) { 16728 Diag(DefaultLoc, diag::err_defaulted_comparison_template); 16729 return; 16730 } 16731 } 16732 16733 Diag(DefaultLoc, diag::err_default_special_members) 16734 << getLangOpts().CPlusPlus20; 16735 return; 16736 } 16737 16738 // Reject if this can't possibly be a defaultable function. 16739 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD); 16740 if (!DefKind && 16741 // A dependent function that doesn't locally look defaultable can 16742 // still instantiate to a defaultable function if it's a constructor 16743 // or assignment operator. 16744 (!FD->isDependentContext() || 16745 (!isa<CXXConstructorDecl>(FD) && 16746 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) { 16747 Diag(DefaultLoc, diag::err_default_special_members) 16748 << getLangOpts().CPlusPlus20; 16749 return; 16750 } 16751 16752 if (DefKind.isComparison() && 16753 !isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 16754 Diag(FD->getLocation(), diag::err_defaulted_comparison_out_of_class) 16755 << (int)DefKind.asComparison(); 16756 return; 16757 } 16758 16759 // Issue compatibility warning. We already warned if the operator is 16760 // 'operator<=>' when parsing the '<=>' token. 16761 if (DefKind.isComparison() && 16762 DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) { 16763 Diag(DefaultLoc, getLangOpts().CPlusPlus20 16764 ? diag::warn_cxx17_compat_defaulted_comparison 16765 : diag::ext_defaulted_comparison); 16766 } 16767 16768 FD->setDefaulted(); 16769 FD->setExplicitlyDefaulted(); 16770 16771 // Defer checking functions that are defaulted in a dependent context. 16772 if (FD->isDependentContext()) 16773 return; 16774 16775 // Unset that we will have a body for this function. We might not, 16776 // if it turns out to be trivial, and we don't need this marking now 16777 // that we've marked it as defaulted. 16778 FD->setWillHaveBody(false); 16779 16780 // If this definition appears within the record, do the checking when 16781 // the record is complete. This is always the case for a defaulted 16782 // comparison. 16783 if (DefKind.isComparison()) 16784 return; 16785 auto *MD = cast<CXXMethodDecl>(FD); 16786 16787 const FunctionDecl *Primary = FD; 16788 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern()) 16789 // Ask the template instantiation pattern that actually had the 16790 // '= default' on it. 16791 Primary = Pattern; 16792 16793 // If the method was defaulted on its first declaration, we will have 16794 // already performed the checking in CheckCompletedCXXClass. Such a 16795 // declaration doesn't trigger an implicit definition. 16796 if (Primary->getCanonicalDecl()->isDefaulted()) 16797 return; 16798 16799 // FIXME: Once we support defining comparisons out of class, check for a 16800 // defaulted comparison here. 16801 if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember())) 16802 MD->setInvalidDecl(); 16803 else 16804 DefineDefaultedFunction(*this, MD, DefaultLoc); 16805 } 16806 16807 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 16808 for (Stmt *SubStmt : S->children()) { 16809 if (!SubStmt) 16810 continue; 16811 if (isa<ReturnStmt>(SubStmt)) 16812 Self.Diag(SubStmt->getBeginLoc(), 16813 diag::err_return_in_constructor_handler); 16814 if (!isa<Expr>(SubStmt)) 16815 SearchForReturnInStmt(Self, SubStmt); 16816 } 16817 } 16818 16819 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 16820 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 16821 CXXCatchStmt *Handler = TryBlock->getHandler(I); 16822 SearchForReturnInStmt(*this, Handler); 16823 } 16824 } 16825 16826 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 16827 const CXXMethodDecl *Old) { 16828 const auto *NewFT = New->getType()->castAs<FunctionProtoType>(); 16829 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>(); 16830 16831 if (OldFT->hasExtParameterInfos()) { 16832 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I) 16833 // A parameter of the overriding method should be annotated with noescape 16834 // if the corresponding parameter of the overridden method is annotated. 16835 if (OldFT->getExtParameterInfo(I).isNoEscape() && 16836 !NewFT->getExtParameterInfo(I).isNoEscape()) { 16837 Diag(New->getParamDecl(I)->getLocation(), 16838 diag::warn_overriding_method_missing_noescape); 16839 Diag(Old->getParamDecl(I)->getLocation(), 16840 diag::note_overridden_marked_noescape); 16841 } 16842 } 16843 16844 // Virtual overrides must have the same code_seg. 16845 const auto *OldCSA = Old->getAttr<CodeSegAttr>(); 16846 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 16847 if ((NewCSA || OldCSA) && 16848 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) { 16849 Diag(New->getLocation(), diag::err_mismatched_code_seg_override); 16850 Diag(Old->getLocation(), diag::note_previous_declaration); 16851 return true; 16852 } 16853 16854 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 16855 16856 // If the calling conventions match, everything is fine 16857 if (NewCC == OldCC) 16858 return false; 16859 16860 // If the calling conventions mismatch because the new function is static, 16861 // suppress the calling convention mismatch error; the error about static 16862 // function override (err_static_overrides_virtual from 16863 // Sema::CheckFunctionDeclaration) is more clear. 16864 if (New->getStorageClass() == SC_Static) 16865 return false; 16866 16867 Diag(New->getLocation(), 16868 diag::err_conflicting_overriding_cc_attributes) 16869 << New->getDeclName() << New->getType() << Old->getType(); 16870 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 16871 return true; 16872 } 16873 16874 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 16875 const CXXMethodDecl *Old) { 16876 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType(); 16877 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType(); 16878 16879 if (Context.hasSameType(NewTy, OldTy) || 16880 NewTy->isDependentType() || OldTy->isDependentType()) 16881 return false; 16882 16883 // Check if the return types are covariant 16884 QualType NewClassTy, OldClassTy; 16885 16886 /// Both types must be pointers or references to classes. 16887 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 16888 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 16889 NewClassTy = NewPT->getPointeeType(); 16890 OldClassTy = OldPT->getPointeeType(); 16891 } 16892 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 16893 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 16894 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 16895 NewClassTy = NewRT->getPointeeType(); 16896 OldClassTy = OldRT->getPointeeType(); 16897 } 16898 } 16899 } 16900 16901 // The return types aren't either both pointers or references to a class type. 16902 if (NewClassTy.isNull()) { 16903 Diag(New->getLocation(), 16904 diag::err_different_return_type_for_overriding_virtual_function) 16905 << New->getDeclName() << NewTy << OldTy 16906 << New->getReturnTypeSourceRange(); 16907 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 16908 << Old->getReturnTypeSourceRange(); 16909 16910 return true; 16911 } 16912 16913 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 16914 // C++14 [class.virtual]p8: 16915 // If the class type in the covariant return type of D::f differs from 16916 // that of B::f, the class type in the return type of D::f shall be 16917 // complete at the point of declaration of D::f or shall be the class 16918 // type D. 16919 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 16920 if (!RT->isBeingDefined() && 16921 RequireCompleteType(New->getLocation(), NewClassTy, 16922 diag::err_covariant_return_incomplete, 16923 New->getDeclName())) 16924 return true; 16925 } 16926 16927 // Check if the new class derives from the old class. 16928 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) { 16929 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 16930 << New->getDeclName() << NewTy << OldTy 16931 << New->getReturnTypeSourceRange(); 16932 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 16933 << Old->getReturnTypeSourceRange(); 16934 return true; 16935 } 16936 16937 // Check if we the conversion from derived to base is valid. 16938 if (CheckDerivedToBaseConversion( 16939 NewClassTy, OldClassTy, 16940 diag::err_covariant_return_inaccessible_base, 16941 diag::err_covariant_return_ambiguous_derived_to_base_conv, 16942 New->getLocation(), New->getReturnTypeSourceRange(), 16943 New->getDeclName(), nullptr)) { 16944 // FIXME: this note won't trigger for delayed access control 16945 // diagnostics, and it's impossible to get an undelayed error 16946 // here from access control during the original parse because 16947 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 16948 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 16949 << Old->getReturnTypeSourceRange(); 16950 return true; 16951 } 16952 } 16953 16954 // The qualifiers of the return types must be the same. 16955 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 16956 Diag(New->getLocation(), 16957 diag::err_covariant_return_type_different_qualifications) 16958 << New->getDeclName() << NewTy << OldTy 16959 << New->getReturnTypeSourceRange(); 16960 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 16961 << Old->getReturnTypeSourceRange(); 16962 return true; 16963 } 16964 16965 16966 // The new class type must have the same or less qualifiers as the old type. 16967 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 16968 Diag(New->getLocation(), 16969 diag::err_covariant_return_type_class_type_more_qualified) 16970 << New->getDeclName() << NewTy << OldTy 16971 << New->getReturnTypeSourceRange(); 16972 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 16973 << Old->getReturnTypeSourceRange(); 16974 return true; 16975 } 16976 16977 return false; 16978 } 16979 16980 /// Mark the given method pure. 16981 /// 16982 /// \param Method the method to be marked pure. 16983 /// 16984 /// \param InitRange the source range that covers the "0" initializer. 16985 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 16986 SourceLocation EndLoc = InitRange.getEnd(); 16987 if (EndLoc.isValid()) 16988 Method->setRangeEnd(EndLoc); 16989 16990 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 16991 Method->setPure(); 16992 return false; 16993 } 16994 16995 if (!Method->isInvalidDecl()) 16996 Diag(Method->getLocation(), diag::err_non_virtual_pure) 16997 << Method->getDeclName() << InitRange; 16998 return true; 16999 } 17000 17001 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) { 17002 if (D->getFriendObjectKind()) 17003 Diag(D->getLocation(), diag::err_pure_friend); 17004 else if (auto *M = dyn_cast<CXXMethodDecl>(D)) 17005 CheckPureMethod(M, ZeroLoc); 17006 else 17007 Diag(D->getLocation(), diag::err_illegal_initializer); 17008 } 17009 17010 /// Determine whether the given declaration is a global variable or 17011 /// static data member. 17012 static bool isNonlocalVariable(const Decl *D) { 17013 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 17014 return Var->hasGlobalStorage(); 17015 17016 return false; 17017 } 17018 17019 /// Invoked when we are about to parse an initializer for the declaration 17020 /// 'Dcl'. 17021 /// 17022 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 17023 /// static data member of class X, names should be looked up in the scope of 17024 /// class X. If the declaration had a scope specifier, a scope will have 17025 /// been created and passed in for this purpose. Otherwise, S will be null. 17026 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 17027 // If there is no declaration, there was an error parsing it. 17028 if (!D || D->isInvalidDecl()) 17029 return; 17030 17031 // We will always have a nested name specifier here, but this declaration 17032 // might not be out of line if the specifier names the current namespace: 17033 // extern int n; 17034 // int ::n = 0; 17035 if (S && D->isOutOfLine()) 17036 EnterDeclaratorContext(S, D->getDeclContext()); 17037 17038 // If we are parsing the initializer for a static data member, push a 17039 // new expression evaluation context that is associated with this static 17040 // data member. 17041 if (isNonlocalVariable(D)) 17042 PushExpressionEvaluationContext( 17043 ExpressionEvaluationContext::PotentiallyEvaluated, D); 17044 } 17045 17046 /// Invoked after we are finished parsing an initializer for the declaration D. 17047 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 17048 // If there is no declaration, there was an error parsing it. 17049 if (!D || D->isInvalidDecl()) 17050 return; 17051 17052 if (isNonlocalVariable(D)) 17053 PopExpressionEvaluationContext(); 17054 17055 if (S && D->isOutOfLine()) 17056 ExitDeclaratorContext(S); 17057 } 17058 17059 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 17060 /// C++ if/switch/while/for statement. 17061 /// e.g: "if (int x = f()) {...}" 17062 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 17063 // C++ 6.4p2: 17064 // The declarator shall not specify a function or an array. 17065 // The type-specifier-seq shall not contain typedef and shall not declare a 17066 // new class or enumeration. 17067 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 17068 "Parser allowed 'typedef' as storage class of condition decl."); 17069 17070 Decl *Dcl = ActOnDeclarator(S, D); 17071 if (!Dcl) 17072 return true; 17073 17074 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 17075 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 17076 << D.getSourceRange(); 17077 return true; 17078 } 17079 17080 return Dcl; 17081 } 17082 17083 void Sema::LoadExternalVTableUses() { 17084 if (!ExternalSource) 17085 return; 17086 17087 SmallVector<ExternalVTableUse, 4> VTables; 17088 ExternalSource->ReadUsedVTables(VTables); 17089 SmallVector<VTableUse, 4> NewUses; 17090 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 17091 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 17092 = VTablesUsed.find(VTables[I].Record); 17093 // Even if a definition wasn't required before, it may be required now. 17094 if (Pos != VTablesUsed.end()) { 17095 if (!Pos->second && VTables[I].DefinitionRequired) 17096 Pos->second = true; 17097 continue; 17098 } 17099 17100 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 17101 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 17102 } 17103 17104 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 17105 } 17106 17107 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 17108 bool DefinitionRequired) { 17109 // Ignore any vtable uses in unevaluated operands or for classes that do 17110 // not have a vtable. 17111 if (!Class->isDynamicClass() || Class->isDependentContext() || 17112 CurContext->isDependentContext() || isUnevaluatedContext()) 17113 return; 17114 // Do not mark as used if compiling for the device outside of the target 17115 // region. 17116 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice && 17117 !isInOpenMPDeclareTargetContext() && 17118 !isInOpenMPTargetExecutionDirective()) { 17119 if (!DefinitionRequired) 17120 MarkVirtualMembersReferenced(Loc, Class); 17121 return; 17122 } 17123 17124 // Try to insert this class into the map. 17125 LoadExternalVTableUses(); 17126 Class = Class->getCanonicalDecl(); 17127 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 17128 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 17129 if (!Pos.second) { 17130 // If we already had an entry, check to see if we are promoting this vtable 17131 // to require a definition. If so, we need to reappend to the VTableUses 17132 // list, since we may have already processed the first entry. 17133 if (DefinitionRequired && !Pos.first->second) { 17134 Pos.first->second = true; 17135 } else { 17136 // Otherwise, we can early exit. 17137 return; 17138 } 17139 } else { 17140 // The Microsoft ABI requires that we perform the destructor body 17141 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 17142 // the deleting destructor is emitted with the vtable, not with the 17143 // destructor definition as in the Itanium ABI. 17144 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 17145 CXXDestructorDecl *DD = Class->getDestructor(); 17146 if (DD && DD->isVirtual() && !DD->isDeleted()) { 17147 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) { 17148 // If this is an out-of-line declaration, marking it referenced will 17149 // not do anything. Manually call CheckDestructor to look up operator 17150 // delete(). 17151 ContextRAII SavedContext(*this, DD); 17152 CheckDestructor(DD); 17153 } else { 17154 MarkFunctionReferenced(Loc, Class->getDestructor()); 17155 } 17156 } 17157 } 17158 } 17159 17160 // Local classes need to have their virtual members marked 17161 // immediately. For all other classes, we mark their virtual members 17162 // at the end of the translation unit. 17163 if (Class->isLocalClass()) 17164 MarkVirtualMembersReferenced(Loc, Class); 17165 else 17166 VTableUses.push_back(std::make_pair(Class, Loc)); 17167 } 17168 17169 bool Sema::DefineUsedVTables() { 17170 LoadExternalVTableUses(); 17171 if (VTableUses.empty()) 17172 return false; 17173 17174 // Note: The VTableUses vector could grow as a result of marking 17175 // the members of a class as "used", so we check the size each 17176 // time through the loop and prefer indices (which are stable) to 17177 // iterators (which are not). 17178 bool DefinedAnything = false; 17179 for (unsigned I = 0; I != VTableUses.size(); ++I) { 17180 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 17181 if (!Class) 17182 continue; 17183 TemplateSpecializationKind ClassTSK = 17184 Class->getTemplateSpecializationKind(); 17185 17186 SourceLocation Loc = VTableUses[I].second; 17187 17188 bool DefineVTable = true; 17189 17190 // If this class has a key function, but that key function is 17191 // defined in another translation unit, we don't need to emit the 17192 // vtable even though we're using it. 17193 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 17194 if (KeyFunction && !KeyFunction->hasBody()) { 17195 // The key function is in another translation unit. 17196 DefineVTable = false; 17197 TemplateSpecializationKind TSK = 17198 KeyFunction->getTemplateSpecializationKind(); 17199 assert(TSK != TSK_ExplicitInstantiationDefinition && 17200 TSK != TSK_ImplicitInstantiation && 17201 "Instantiations don't have key functions"); 17202 (void)TSK; 17203 } else if (!KeyFunction) { 17204 // If we have a class with no key function that is the subject 17205 // of an explicit instantiation declaration, suppress the 17206 // vtable; it will live with the explicit instantiation 17207 // definition. 17208 bool IsExplicitInstantiationDeclaration = 17209 ClassTSK == TSK_ExplicitInstantiationDeclaration; 17210 for (auto R : Class->redecls()) { 17211 TemplateSpecializationKind TSK 17212 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 17213 if (TSK == TSK_ExplicitInstantiationDeclaration) 17214 IsExplicitInstantiationDeclaration = true; 17215 else if (TSK == TSK_ExplicitInstantiationDefinition) { 17216 IsExplicitInstantiationDeclaration = false; 17217 break; 17218 } 17219 } 17220 17221 if (IsExplicitInstantiationDeclaration) 17222 DefineVTable = false; 17223 } 17224 17225 // The exception specifications for all virtual members may be needed even 17226 // if we are not providing an authoritative form of the vtable in this TU. 17227 // We may choose to emit it available_externally anyway. 17228 if (!DefineVTable) { 17229 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 17230 continue; 17231 } 17232 17233 // Mark all of the virtual members of this class as referenced, so 17234 // that we can build a vtable. Then, tell the AST consumer that a 17235 // vtable for this class is required. 17236 DefinedAnything = true; 17237 MarkVirtualMembersReferenced(Loc, Class); 17238 CXXRecordDecl *Canonical = Class->getCanonicalDecl(); 17239 if (VTablesUsed[Canonical]) 17240 Consumer.HandleVTable(Class); 17241 17242 // Warn if we're emitting a weak vtable. The vtable will be weak if there is 17243 // no key function or the key function is inlined. Don't warn in C++ ABIs 17244 // that lack key functions, since the user won't be able to make one. 17245 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() && 17246 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) { 17247 const FunctionDecl *KeyFunctionDef = nullptr; 17248 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) && 17249 KeyFunctionDef->isInlined())) { 17250 Diag(Class->getLocation(), 17251 ClassTSK == TSK_ExplicitInstantiationDefinition 17252 ? diag::warn_weak_template_vtable 17253 : diag::warn_weak_vtable) 17254 << Class; 17255 } 17256 } 17257 } 17258 VTableUses.clear(); 17259 17260 return DefinedAnything; 17261 } 17262 17263 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 17264 const CXXRecordDecl *RD) { 17265 for (const auto *I : RD->methods()) 17266 if (I->isVirtual() && !I->isPure()) 17267 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 17268 } 17269 17270 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 17271 const CXXRecordDecl *RD, 17272 bool ConstexprOnly) { 17273 // Mark all functions which will appear in RD's vtable as used. 17274 CXXFinalOverriderMap FinalOverriders; 17275 RD->getFinalOverriders(FinalOverriders); 17276 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 17277 E = FinalOverriders.end(); 17278 I != E; ++I) { 17279 for (OverridingMethods::const_iterator OI = I->second.begin(), 17280 OE = I->second.end(); 17281 OI != OE; ++OI) { 17282 assert(OI->second.size() > 0 && "no final overrider"); 17283 CXXMethodDecl *Overrider = OI->second.front().Method; 17284 17285 // C++ [basic.def.odr]p2: 17286 // [...] A virtual member function is used if it is not pure. [...] 17287 if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr())) 17288 MarkFunctionReferenced(Loc, Overrider); 17289 } 17290 } 17291 17292 // Only classes that have virtual bases need a VTT. 17293 if (RD->getNumVBases() == 0) 17294 return; 17295 17296 for (const auto &I : RD->bases()) { 17297 const auto *Base = 17298 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 17299 if (Base->getNumVBases() == 0) 17300 continue; 17301 MarkVirtualMembersReferenced(Loc, Base); 17302 } 17303 } 17304 17305 /// SetIvarInitializers - This routine builds initialization ASTs for the 17306 /// Objective-C implementation whose ivars need be initialized. 17307 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 17308 if (!getLangOpts().CPlusPlus) 17309 return; 17310 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 17311 SmallVector<ObjCIvarDecl*, 8> ivars; 17312 CollectIvarsToConstructOrDestruct(OID, ivars); 17313 if (ivars.empty()) 17314 return; 17315 SmallVector<CXXCtorInitializer*, 32> AllToInit; 17316 for (unsigned i = 0; i < ivars.size(); i++) { 17317 FieldDecl *Field = ivars[i]; 17318 if (Field->isInvalidDecl()) 17319 continue; 17320 17321 CXXCtorInitializer *Member; 17322 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 17323 InitializationKind InitKind = 17324 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 17325 17326 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 17327 ExprResult MemberInit = 17328 InitSeq.Perform(*this, InitEntity, InitKind, None); 17329 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 17330 // Note, MemberInit could actually come back empty if no initialization 17331 // is required (e.g., because it would call a trivial default constructor) 17332 if (!MemberInit.get() || MemberInit.isInvalid()) 17333 continue; 17334 17335 Member = 17336 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 17337 SourceLocation(), 17338 MemberInit.getAs<Expr>(), 17339 SourceLocation()); 17340 AllToInit.push_back(Member); 17341 17342 // Be sure that the destructor is accessible and is marked as referenced. 17343 if (const RecordType *RecordTy = 17344 Context.getBaseElementType(Field->getType()) 17345 ->getAs<RecordType>()) { 17346 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 17347 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 17348 MarkFunctionReferenced(Field->getLocation(), Destructor); 17349 CheckDestructorAccess(Field->getLocation(), Destructor, 17350 PDiag(diag::err_access_dtor_ivar) 17351 << Context.getBaseElementType(Field->getType())); 17352 } 17353 } 17354 } 17355 ObjCImplementation->setIvarInitializers(Context, 17356 AllToInit.data(), AllToInit.size()); 17357 } 17358 } 17359 17360 static 17361 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 17362 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid, 17363 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid, 17364 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current, 17365 Sema &S) { 17366 if (Ctor->isInvalidDecl()) 17367 return; 17368 17369 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 17370 17371 // Target may not be determinable yet, for instance if this is a dependent 17372 // call in an uninstantiated template. 17373 if (Target) { 17374 const FunctionDecl *FNTarget = nullptr; 17375 (void)Target->hasBody(FNTarget); 17376 Target = const_cast<CXXConstructorDecl*>( 17377 cast_or_null<CXXConstructorDecl>(FNTarget)); 17378 } 17379 17380 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 17381 // Avoid dereferencing a null pointer here. 17382 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 17383 17384 if (!Current.insert(Canonical).second) 17385 return; 17386 17387 // We know that beyond here, we aren't chaining into a cycle. 17388 if (!Target || !Target->isDelegatingConstructor() || 17389 Target->isInvalidDecl() || Valid.count(TCanonical)) { 17390 Valid.insert(Current.begin(), Current.end()); 17391 Current.clear(); 17392 // We've hit a cycle. 17393 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 17394 Current.count(TCanonical)) { 17395 // If we haven't diagnosed this cycle yet, do so now. 17396 if (!Invalid.count(TCanonical)) { 17397 S.Diag((*Ctor->init_begin())->getSourceLocation(), 17398 diag::warn_delegating_ctor_cycle) 17399 << Ctor; 17400 17401 // Don't add a note for a function delegating directly to itself. 17402 if (TCanonical != Canonical) 17403 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 17404 17405 CXXConstructorDecl *C = Target; 17406 while (C->getCanonicalDecl() != Canonical) { 17407 const FunctionDecl *FNTarget = nullptr; 17408 (void)C->getTargetConstructor()->hasBody(FNTarget); 17409 assert(FNTarget && "Ctor cycle through bodiless function"); 17410 17411 C = const_cast<CXXConstructorDecl*>( 17412 cast<CXXConstructorDecl>(FNTarget)); 17413 S.Diag(C->getLocation(), diag::note_which_delegates_to); 17414 } 17415 } 17416 17417 Invalid.insert(Current.begin(), Current.end()); 17418 Current.clear(); 17419 } else { 17420 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 17421 } 17422 } 17423 17424 17425 void Sema::CheckDelegatingCtorCycles() { 17426 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 17427 17428 for (DelegatingCtorDeclsType::iterator 17429 I = DelegatingCtorDecls.begin(ExternalSource), 17430 E = DelegatingCtorDecls.end(); 17431 I != E; ++I) 17432 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 17433 17434 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI) 17435 (*CI)->setInvalidDecl(); 17436 } 17437 17438 namespace { 17439 /// AST visitor that finds references to the 'this' expression. 17440 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 17441 Sema &S; 17442 17443 public: 17444 explicit FindCXXThisExpr(Sema &S) : S(S) { } 17445 17446 bool VisitCXXThisExpr(CXXThisExpr *E) { 17447 S.Diag(E->getLocation(), diag::err_this_static_member_func) 17448 << E->isImplicit(); 17449 return false; 17450 } 17451 }; 17452 } 17453 17454 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 17455 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 17456 if (!TSInfo) 17457 return false; 17458 17459 TypeLoc TL = TSInfo->getTypeLoc(); 17460 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 17461 if (!ProtoTL) 17462 return false; 17463 17464 // C++11 [expr.prim.general]p3: 17465 // [The expression this] shall not appear before the optional 17466 // cv-qualifier-seq and it shall not appear within the declaration of a 17467 // static member function (although its type and value category are defined 17468 // within a static member function as they are within a non-static member 17469 // function). [ Note: this is because declaration matching does not occur 17470 // until the complete declarator is known. - end note ] 17471 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 17472 FindCXXThisExpr Finder(*this); 17473 17474 // If the return type came after the cv-qualifier-seq, check it now. 17475 if (Proto->hasTrailingReturn() && 17476 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 17477 return true; 17478 17479 // Check the exception specification. 17480 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 17481 return true; 17482 17483 // Check the trailing requires clause 17484 if (Expr *E = Method->getTrailingRequiresClause()) 17485 if (!Finder.TraverseStmt(E)) 17486 return true; 17487 17488 return checkThisInStaticMemberFunctionAttributes(Method); 17489 } 17490 17491 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 17492 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 17493 if (!TSInfo) 17494 return false; 17495 17496 TypeLoc TL = TSInfo->getTypeLoc(); 17497 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 17498 if (!ProtoTL) 17499 return false; 17500 17501 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 17502 FindCXXThisExpr Finder(*this); 17503 17504 switch (Proto->getExceptionSpecType()) { 17505 case EST_Unparsed: 17506 case EST_Uninstantiated: 17507 case EST_Unevaluated: 17508 case EST_BasicNoexcept: 17509 case EST_NoThrow: 17510 case EST_DynamicNone: 17511 case EST_MSAny: 17512 case EST_None: 17513 break; 17514 17515 case EST_DependentNoexcept: 17516 case EST_NoexceptFalse: 17517 case EST_NoexceptTrue: 17518 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 17519 return true; 17520 LLVM_FALLTHROUGH; 17521 17522 case EST_Dynamic: 17523 for (const auto &E : Proto->exceptions()) { 17524 if (!Finder.TraverseType(E)) 17525 return true; 17526 } 17527 break; 17528 } 17529 17530 return false; 17531 } 17532 17533 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 17534 FindCXXThisExpr Finder(*this); 17535 17536 // Check attributes. 17537 for (const auto *A : Method->attrs()) { 17538 // FIXME: This should be emitted by tblgen. 17539 Expr *Arg = nullptr; 17540 ArrayRef<Expr *> Args; 17541 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 17542 Arg = G->getArg(); 17543 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 17544 Arg = G->getArg(); 17545 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 17546 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 17547 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 17548 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 17549 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 17550 Arg = ETLF->getSuccessValue(); 17551 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 17552 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 17553 Arg = STLF->getSuccessValue(); 17554 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 17555 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 17556 Arg = LR->getArg(); 17557 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 17558 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 17559 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 17560 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 17561 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 17562 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 17563 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 17564 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 17565 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 17566 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 17567 17568 if (Arg && !Finder.TraverseStmt(Arg)) 17569 return true; 17570 17571 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 17572 if (!Finder.TraverseStmt(Args[I])) 17573 return true; 17574 } 17575 } 17576 17577 return false; 17578 } 17579 17580 void Sema::checkExceptionSpecification( 17581 bool IsTopLevel, ExceptionSpecificationType EST, 17582 ArrayRef<ParsedType> DynamicExceptions, 17583 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 17584 SmallVectorImpl<QualType> &Exceptions, 17585 FunctionProtoType::ExceptionSpecInfo &ESI) { 17586 Exceptions.clear(); 17587 ESI.Type = EST; 17588 if (EST == EST_Dynamic) { 17589 Exceptions.reserve(DynamicExceptions.size()); 17590 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 17591 // FIXME: Preserve type source info. 17592 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 17593 17594 if (IsTopLevel) { 17595 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 17596 collectUnexpandedParameterPacks(ET, Unexpanded); 17597 if (!Unexpanded.empty()) { 17598 DiagnoseUnexpandedParameterPacks( 17599 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 17600 Unexpanded); 17601 continue; 17602 } 17603 } 17604 17605 // Check that the type is valid for an exception spec, and 17606 // drop it if not. 17607 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 17608 Exceptions.push_back(ET); 17609 } 17610 ESI.Exceptions = Exceptions; 17611 return; 17612 } 17613 17614 if (isComputedNoexcept(EST)) { 17615 assert((NoexceptExpr->isTypeDependent() || 17616 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 17617 Context.BoolTy) && 17618 "Parser should have made sure that the expression is boolean"); 17619 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 17620 ESI.Type = EST_BasicNoexcept; 17621 return; 17622 } 17623 17624 ESI.NoexceptExpr = NoexceptExpr; 17625 return; 17626 } 17627 } 17628 17629 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 17630 ExceptionSpecificationType EST, 17631 SourceRange SpecificationRange, 17632 ArrayRef<ParsedType> DynamicExceptions, 17633 ArrayRef<SourceRange> DynamicExceptionRanges, 17634 Expr *NoexceptExpr) { 17635 if (!MethodD) 17636 return; 17637 17638 // Dig out the method we're referring to. 17639 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 17640 MethodD = FunTmpl->getTemplatedDecl(); 17641 17642 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 17643 if (!Method) 17644 return; 17645 17646 // Check the exception specification. 17647 llvm::SmallVector<QualType, 4> Exceptions; 17648 FunctionProtoType::ExceptionSpecInfo ESI; 17649 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 17650 DynamicExceptionRanges, NoexceptExpr, Exceptions, 17651 ESI); 17652 17653 // Update the exception specification on the function type. 17654 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 17655 17656 if (Method->isStatic()) 17657 checkThisInStaticMemberFunctionExceptionSpec(Method); 17658 17659 if (Method->isVirtual()) { 17660 // Check overrides, which we previously had to delay. 17661 for (const CXXMethodDecl *O : Method->overridden_methods()) 17662 CheckOverridingFunctionExceptionSpec(Method, O); 17663 } 17664 } 17665 17666 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 17667 /// 17668 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 17669 SourceLocation DeclStart, Declarator &D, 17670 Expr *BitWidth, 17671 InClassInitStyle InitStyle, 17672 AccessSpecifier AS, 17673 const ParsedAttr &MSPropertyAttr) { 17674 IdentifierInfo *II = D.getIdentifier(); 17675 if (!II) { 17676 Diag(DeclStart, diag::err_anonymous_property); 17677 return nullptr; 17678 } 17679 SourceLocation Loc = D.getIdentifierLoc(); 17680 17681 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 17682 QualType T = TInfo->getType(); 17683 if (getLangOpts().CPlusPlus) { 17684 CheckExtraCXXDefaultArguments(D); 17685 17686 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 17687 UPPC_DataMemberType)) { 17688 D.setInvalidType(); 17689 T = Context.IntTy; 17690 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 17691 } 17692 } 17693 17694 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 17695 17696 if (D.getDeclSpec().isInlineSpecified()) 17697 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 17698 << getLangOpts().CPlusPlus17; 17699 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 17700 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 17701 diag::err_invalid_thread) 17702 << DeclSpec::getSpecifierName(TSCS); 17703 17704 // Check to see if this name was declared as a member previously 17705 NamedDecl *PrevDecl = nullptr; 17706 LookupResult Previous(*this, II, Loc, LookupMemberName, 17707 ForVisibleRedeclaration); 17708 LookupName(Previous, S); 17709 switch (Previous.getResultKind()) { 17710 case LookupResult::Found: 17711 case LookupResult::FoundUnresolvedValue: 17712 PrevDecl = Previous.getAsSingle<NamedDecl>(); 17713 break; 17714 17715 case LookupResult::FoundOverloaded: 17716 PrevDecl = Previous.getRepresentativeDecl(); 17717 break; 17718 17719 case LookupResult::NotFound: 17720 case LookupResult::NotFoundInCurrentInstantiation: 17721 case LookupResult::Ambiguous: 17722 break; 17723 } 17724 17725 if (PrevDecl && PrevDecl->isTemplateParameter()) { 17726 // Maybe we will complain about the shadowed template parameter. 17727 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 17728 // Just pretend that we didn't see the previous declaration. 17729 PrevDecl = nullptr; 17730 } 17731 17732 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 17733 PrevDecl = nullptr; 17734 17735 SourceLocation TSSL = D.getBeginLoc(); 17736 MSPropertyDecl *NewPD = 17737 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL, 17738 MSPropertyAttr.getPropertyDataGetter(), 17739 MSPropertyAttr.getPropertyDataSetter()); 17740 ProcessDeclAttributes(TUScope, NewPD, D); 17741 NewPD->setAccess(AS); 17742 17743 if (NewPD->isInvalidDecl()) 17744 Record->setInvalidDecl(); 17745 17746 if (D.getDeclSpec().isModulePrivateSpecified()) 17747 NewPD->setModulePrivate(); 17748 17749 if (NewPD->isInvalidDecl() && PrevDecl) { 17750 // Don't introduce NewFD into scope; there's already something 17751 // with the same name in the same scope. 17752 } else if (II) { 17753 PushOnScopeChains(NewPD, S); 17754 } else 17755 Record->addDecl(NewPD); 17756 17757 return NewPD; 17758 } 17759 17760 void Sema::ActOnStartFunctionDeclarationDeclarator( 17761 Declarator &Declarator, unsigned TemplateParameterDepth) { 17762 auto &Info = InventedParameterInfos.emplace_back(); 17763 TemplateParameterList *ExplicitParams = nullptr; 17764 ArrayRef<TemplateParameterList *> ExplicitLists = 17765 Declarator.getTemplateParameterLists(); 17766 if (!ExplicitLists.empty()) { 17767 bool IsMemberSpecialization, IsInvalid; 17768 ExplicitParams = MatchTemplateParametersToScopeSpecifier( 17769 Declarator.getBeginLoc(), Declarator.getIdentifierLoc(), 17770 Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr, 17771 ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid, 17772 /*SuppressDiagnostic=*/true); 17773 } 17774 if (ExplicitParams) { 17775 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth(); 17776 for (NamedDecl *Param : *ExplicitParams) 17777 Info.TemplateParams.push_back(Param); 17778 Info.NumExplicitTemplateParams = ExplicitParams->size(); 17779 } else { 17780 Info.AutoTemplateParameterDepth = TemplateParameterDepth; 17781 Info.NumExplicitTemplateParams = 0; 17782 } 17783 } 17784 17785 void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) { 17786 auto &FSI = InventedParameterInfos.back(); 17787 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) { 17788 if (FSI.NumExplicitTemplateParams != 0) { 17789 TemplateParameterList *ExplicitParams = 17790 Declarator.getTemplateParameterLists().back(); 17791 Declarator.setInventedTemplateParameterList( 17792 TemplateParameterList::Create( 17793 Context, ExplicitParams->getTemplateLoc(), 17794 ExplicitParams->getLAngleLoc(), FSI.TemplateParams, 17795 ExplicitParams->getRAngleLoc(), 17796 ExplicitParams->getRequiresClause())); 17797 } else { 17798 Declarator.setInventedTemplateParameterList( 17799 TemplateParameterList::Create( 17800 Context, SourceLocation(), SourceLocation(), FSI.TemplateParams, 17801 SourceLocation(), /*RequiresClause=*/nullptr)); 17802 } 17803 } 17804 InventedParameterInfos.pop_back(); 17805 } 17806