1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements semantic analysis for C++ declarations. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/AST/ASTConsumer.h" 14 #include "clang/AST/ASTContext.h" 15 #include "clang/AST/ASTLambda.h" 16 #include "clang/AST/ASTMutationListener.h" 17 #include "clang/AST/CXXInheritance.h" 18 #include "clang/AST/CharUnits.h" 19 #include "clang/AST/ComparisonCategories.h" 20 #include "clang/AST/EvaluatedExprVisitor.h" 21 #include "clang/AST/ExprCXX.h" 22 #include "clang/AST/RecordLayout.h" 23 #include "clang/AST/RecursiveASTVisitor.h" 24 #include "clang/AST/StmtVisitor.h" 25 #include "clang/AST/TypeLoc.h" 26 #include "clang/AST/TypeOrdering.h" 27 #include "clang/Basic/AttributeCommonInfo.h" 28 #include "clang/Basic/PartialDiagnostic.h" 29 #include "clang/Basic/Specifiers.h" 30 #include "clang/Basic/TargetInfo.h" 31 #include "clang/Lex/LiteralSupport.h" 32 #include "clang/Lex/Preprocessor.h" 33 #include "clang/Sema/CXXFieldCollector.h" 34 #include "clang/Sema/DeclSpec.h" 35 #include "clang/Sema/Initialization.h" 36 #include "clang/Sema/Lookup.h" 37 #include "clang/Sema/ParsedTemplate.h" 38 #include "clang/Sema/Scope.h" 39 #include "clang/Sema/ScopeInfo.h" 40 #include "clang/Sema/SemaInternal.h" 41 #include "clang/Sema/Template.h" 42 #include "llvm/ADT/ScopeExit.h" 43 #include "llvm/ADT/SmallString.h" 44 #include "llvm/ADT/STLExtras.h" 45 #include "llvm/ADT/StringExtras.h" 46 #include <map> 47 #include <set> 48 49 using namespace clang; 50 51 //===----------------------------------------------------------------------===// 52 // CheckDefaultArgumentVisitor 53 //===----------------------------------------------------------------------===// 54 55 namespace { 56 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 57 /// the default argument of a parameter to determine whether it 58 /// contains any ill-formed subexpressions. For example, this will 59 /// diagnose the use of local variables or parameters within the 60 /// default argument expression. 61 class CheckDefaultArgumentVisitor 62 : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> { 63 Sema &S; 64 const Expr *DefaultArg; 65 66 public: 67 CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg) 68 : S(S), DefaultArg(DefaultArg) {} 69 70 bool VisitExpr(const Expr *Node); 71 bool VisitDeclRefExpr(const DeclRefExpr *DRE); 72 bool VisitCXXThisExpr(const CXXThisExpr *ThisE); 73 bool VisitLambdaExpr(const LambdaExpr *Lambda); 74 bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE); 75 }; 76 77 /// VisitExpr - Visit all of the children of this expression. 78 bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) { 79 bool IsInvalid = false; 80 for (const Stmt *SubStmt : Node->children()) 81 IsInvalid |= Visit(SubStmt); 82 return IsInvalid; 83 } 84 85 /// VisitDeclRefExpr - Visit a reference to a declaration, to 86 /// determine whether this declaration can be used in the default 87 /// argument expression. 88 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) { 89 const NamedDecl *Decl = DRE->getDecl(); 90 if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) { 91 // C++ [dcl.fct.default]p9: 92 // [...] parameters of a function shall not be used in default 93 // argument expressions, even if they are not evaluated. [...] 94 // 95 // C++17 [dcl.fct.default]p9 (by CWG 2082): 96 // [...] A parameter shall not appear as a potentially-evaluated 97 // expression in a default argument. [...] 98 // 99 if (DRE->isNonOdrUse() != NOUR_Unevaluated) 100 return S.Diag(DRE->getBeginLoc(), 101 diag::err_param_default_argument_references_param) 102 << Param->getDeclName() << DefaultArg->getSourceRange(); 103 } else if (const auto *VDecl = dyn_cast<VarDecl>(Decl)) { 104 // C++ [dcl.fct.default]p7: 105 // Local variables shall not be used in default argument 106 // expressions. 107 // 108 // C++17 [dcl.fct.default]p7 (by CWG 2082): 109 // A local variable shall not appear as a potentially-evaluated 110 // expression in a default argument. 111 // 112 // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346): 113 // Note: A local variable cannot be odr-used (6.3) in a default argument. 114 // 115 if (VDecl->isLocalVarDecl() && !DRE->isNonOdrUse()) 116 return S.Diag(DRE->getBeginLoc(), 117 diag::err_param_default_argument_references_local) 118 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 119 } 120 121 return false; 122 } 123 124 /// VisitCXXThisExpr - Visit a C++ "this" expression. 125 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) { 126 // C++ [dcl.fct.default]p8: 127 // The keyword this shall not be used in a default argument of a 128 // member function. 129 return S.Diag(ThisE->getBeginLoc(), 130 diag::err_param_default_argument_references_this) 131 << ThisE->getSourceRange(); 132 } 133 134 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr( 135 const PseudoObjectExpr *POE) { 136 bool Invalid = false; 137 for (const Expr *E : POE->semantics()) { 138 // Look through bindings. 139 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) { 140 E = OVE->getSourceExpr(); 141 assert(E && "pseudo-object binding without source expression?"); 142 } 143 144 Invalid |= Visit(E); 145 } 146 return Invalid; 147 } 148 149 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) { 150 // C++11 [expr.lambda.prim]p13: 151 // A lambda-expression appearing in a default argument shall not 152 // implicitly or explicitly capture any entity. 153 if (Lambda->capture_begin() == Lambda->capture_end()) 154 return false; 155 156 return S.Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg); 157 } 158 } // namespace 159 160 void 161 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc, 162 const CXXMethodDecl *Method) { 163 // If we have an MSAny spec already, don't bother. 164 if (!Method || ComputedEST == EST_MSAny) 165 return; 166 167 const FunctionProtoType *Proto 168 = Method->getType()->getAs<FunctionProtoType>(); 169 Proto = Self->ResolveExceptionSpec(CallLoc, Proto); 170 if (!Proto) 171 return; 172 173 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 174 175 // If we have a throw-all spec at this point, ignore the function. 176 if (ComputedEST == EST_None) 177 return; 178 179 if (EST == EST_None && Method->hasAttr<NoThrowAttr>()) 180 EST = EST_BasicNoexcept; 181 182 switch (EST) { 183 case EST_Unparsed: 184 case EST_Uninstantiated: 185 case EST_Unevaluated: 186 llvm_unreachable("should not see unresolved exception specs here"); 187 188 // If this function can throw any exceptions, make a note of that. 189 case EST_MSAny: 190 case EST_None: 191 // FIXME: Whichever we see last of MSAny and None determines our result. 192 // We should make a consistent, order-independent choice here. 193 ClearExceptions(); 194 ComputedEST = EST; 195 return; 196 case EST_NoexceptFalse: 197 ClearExceptions(); 198 ComputedEST = EST_None; 199 return; 200 // FIXME: If the call to this decl is using any of its default arguments, we 201 // need to search them for potentially-throwing calls. 202 // If this function has a basic noexcept, it doesn't affect the outcome. 203 case EST_BasicNoexcept: 204 case EST_NoexceptTrue: 205 case EST_NoThrow: 206 return; 207 // If we're still at noexcept(true) and there's a throw() callee, 208 // change to that specification. 209 case EST_DynamicNone: 210 if (ComputedEST == EST_BasicNoexcept) 211 ComputedEST = EST_DynamicNone; 212 return; 213 case EST_DependentNoexcept: 214 llvm_unreachable( 215 "should not generate implicit declarations for dependent cases"); 216 case EST_Dynamic: 217 break; 218 } 219 assert(EST == EST_Dynamic && "EST case not considered earlier."); 220 assert(ComputedEST != EST_None && 221 "Shouldn't collect exceptions when throw-all is guaranteed."); 222 ComputedEST = EST_Dynamic; 223 // Record the exceptions in this function's exception specification. 224 for (const auto &E : Proto->exceptions()) 225 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second) 226 Exceptions.push_back(E); 227 } 228 229 void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) { 230 if (!S || ComputedEST == EST_MSAny) 231 return; 232 233 // FIXME: 234 // 235 // C++0x [except.spec]p14: 236 // [An] implicit exception-specification specifies the type-id T if and 237 // only if T is allowed by the exception-specification of a function directly 238 // invoked by f's implicit definition; f shall allow all exceptions if any 239 // function it directly invokes allows all exceptions, and f shall allow no 240 // exceptions if every function it directly invokes allows no exceptions. 241 // 242 // Note in particular that if an implicit exception-specification is generated 243 // for a function containing a throw-expression, that specification can still 244 // be noexcept(true). 245 // 246 // Note also that 'directly invoked' is not defined in the standard, and there 247 // is no indication that we should only consider potentially-evaluated calls. 248 // 249 // Ultimately we should implement the intent of the standard: the exception 250 // specification should be the set of exceptions which can be thrown by the 251 // implicit definition. For now, we assume that any non-nothrow expression can 252 // throw any exception. 253 254 if (Self->canThrow(S)) 255 ComputedEST = EST_None; 256 } 257 258 ExprResult Sema::ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 259 SourceLocation EqualLoc) { 260 if (RequireCompleteType(Param->getLocation(), Param->getType(), 261 diag::err_typecheck_decl_incomplete_type)) 262 return true; 263 264 // C++ [dcl.fct.default]p5 265 // A default argument expression is implicitly converted (clause 266 // 4) to the parameter type. The default argument expression has 267 // the same semantic constraints as the initializer expression in 268 // a declaration of a variable of the parameter type, using the 269 // copy-initialization semantics (8.5). 270 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 271 Param); 272 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 273 EqualLoc); 274 InitializationSequence InitSeq(*this, Entity, Kind, Arg); 275 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); 276 if (Result.isInvalid()) 277 return true; 278 Arg = Result.getAs<Expr>(); 279 280 CheckCompletedExpr(Arg, EqualLoc); 281 Arg = MaybeCreateExprWithCleanups(Arg); 282 283 return Arg; 284 } 285 286 void Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 287 SourceLocation EqualLoc) { 288 // Add the default argument to the parameter 289 Param->setDefaultArg(Arg); 290 291 // We have already instantiated this parameter; provide each of the 292 // instantiations with the uninstantiated default argument. 293 UnparsedDefaultArgInstantiationsMap::iterator InstPos 294 = UnparsedDefaultArgInstantiations.find(Param); 295 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 296 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 297 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 298 299 // We're done tracking this parameter's instantiations. 300 UnparsedDefaultArgInstantiations.erase(InstPos); 301 } 302 } 303 304 /// ActOnParamDefaultArgument - Check whether the default argument 305 /// provided for a function parameter is well-formed. If so, attach it 306 /// to the parameter declaration. 307 void 308 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 309 Expr *DefaultArg) { 310 if (!param || !DefaultArg) 311 return; 312 313 ParmVarDecl *Param = cast<ParmVarDecl>(param); 314 UnparsedDefaultArgLocs.erase(Param); 315 316 auto Fail = [&] { 317 Param->setInvalidDecl(); 318 Param->setDefaultArg(new (Context) OpaqueValueExpr( 319 EqualLoc, Param->getType().getNonReferenceType(), VK_PRValue)); 320 }; 321 322 // Default arguments are only permitted in C++ 323 if (!getLangOpts().CPlusPlus) { 324 Diag(EqualLoc, diag::err_param_default_argument) 325 << DefaultArg->getSourceRange(); 326 return Fail(); 327 } 328 329 // Check for unexpanded parameter packs. 330 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 331 return Fail(); 332 } 333 334 // C++11 [dcl.fct.default]p3 335 // A default argument expression [...] shall not be specified for a 336 // parameter pack. 337 if (Param->isParameterPack()) { 338 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack) 339 << DefaultArg->getSourceRange(); 340 // Recover by discarding the default argument. 341 Param->setDefaultArg(nullptr); 342 return; 343 } 344 345 ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc); 346 if (Result.isInvalid()) 347 return Fail(); 348 349 DefaultArg = Result.getAs<Expr>(); 350 351 // Check that the default argument is well-formed 352 CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg); 353 if (DefaultArgChecker.Visit(DefaultArg)) 354 return Fail(); 355 356 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 357 } 358 359 /// ActOnParamUnparsedDefaultArgument - We've seen a default 360 /// argument for a function parameter, but we can't parse it yet 361 /// because we're inside a class definition. Note that this default 362 /// argument will be parsed later. 363 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 364 SourceLocation EqualLoc, 365 SourceLocation ArgLoc) { 366 if (!param) 367 return; 368 369 ParmVarDecl *Param = cast<ParmVarDecl>(param); 370 Param->setUnparsedDefaultArg(); 371 UnparsedDefaultArgLocs[Param] = ArgLoc; 372 } 373 374 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 375 /// the default argument for the parameter param failed. 376 void Sema::ActOnParamDefaultArgumentError(Decl *param, 377 SourceLocation EqualLoc) { 378 if (!param) 379 return; 380 381 ParmVarDecl *Param = cast<ParmVarDecl>(param); 382 Param->setInvalidDecl(); 383 UnparsedDefaultArgLocs.erase(Param); 384 Param->setDefaultArg(new (Context) OpaqueValueExpr( 385 EqualLoc, Param->getType().getNonReferenceType(), VK_PRValue)); 386 } 387 388 /// CheckExtraCXXDefaultArguments - Check for any extra default 389 /// arguments in the declarator, which is not a function declaration 390 /// or definition and therefore is not permitted to have default 391 /// arguments. This routine should be invoked for every declarator 392 /// that is not a function declaration or definition. 393 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 394 // C++ [dcl.fct.default]p3 395 // A default argument expression shall be specified only in the 396 // parameter-declaration-clause of a function declaration or in a 397 // template-parameter (14.1). It shall not be specified for a 398 // parameter pack. If it is specified in a 399 // parameter-declaration-clause, it shall not occur within a 400 // declarator or abstract-declarator of a parameter-declaration. 401 bool MightBeFunction = D.isFunctionDeclarationContext(); 402 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 403 DeclaratorChunk &chunk = D.getTypeObject(i); 404 if (chunk.Kind == DeclaratorChunk::Function) { 405 if (MightBeFunction) { 406 // This is a function declaration. It can have default arguments, but 407 // keep looking in case its return type is a function type with default 408 // arguments. 409 MightBeFunction = false; 410 continue; 411 } 412 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e; 413 ++argIdx) { 414 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param); 415 if (Param->hasUnparsedDefaultArg()) { 416 std::unique_ptr<CachedTokens> Toks = 417 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens); 418 SourceRange SR; 419 if (Toks->size() > 1) 420 SR = SourceRange((*Toks)[1].getLocation(), 421 Toks->back().getLocation()); 422 else 423 SR = UnparsedDefaultArgLocs[Param]; 424 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 425 << SR; 426 } else if (Param->getDefaultArg()) { 427 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 428 << Param->getDefaultArg()->getSourceRange(); 429 Param->setDefaultArg(nullptr); 430 } 431 } 432 } else if (chunk.Kind != DeclaratorChunk::Paren) { 433 MightBeFunction = false; 434 } 435 } 436 } 437 438 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { 439 return llvm::any_of(FD->parameters(), [](ParmVarDecl *P) { 440 return P->hasDefaultArg() && !P->hasInheritedDefaultArg(); 441 }); 442 } 443 444 /// MergeCXXFunctionDecl - Merge two declarations of the same C++ 445 /// function, once we already know that they have the same 446 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an 447 /// error, false otherwise. 448 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 449 Scope *S) { 450 bool Invalid = false; 451 452 // The declaration context corresponding to the scope is the semantic 453 // parent, unless this is a local function declaration, in which case 454 // it is that surrounding function. 455 DeclContext *ScopeDC = New->isLocalExternDecl() 456 ? New->getLexicalDeclContext() 457 : New->getDeclContext(); 458 459 // Find the previous declaration for the purpose of default arguments. 460 FunctionDecl *PrevForDefaultArgs = Old; 461 for (/**/; PrevForDefaultArgs; 462 // Don't bother looking back past the latest decl if this is a local 463 // extern declaration; nothing else could work. 464 PrevForDefaultArgs = New->isLocalExternDecl() 465 ? nullptr 466 : PrevForDefaultArgs->getPreviousDecl()) { 467 // Ignore hidden declarations. 468 if (!LookupResult::isVisible(*this, PrevForDefaultArgs)) 469 continue; 470 471 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) && 472 !New->isCXXClassMember()) { 473 // Ignore default arguments of old decl if they are not in 474 // the same scope and this is not an out-of-line definition of 475 // a member function. 476 continue; 477 } 478 479 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) { 480 // If only one of these is a local function declaration, then they are 481 // declared in different scopes, even though isDeclInScope may think 482 // they're in the same scope. (If both are local, the scope check is 483 // sufficient, and if neither is local, then they are in the same scope.) 484 continue; 485 } 486 487 // We found the right previous declaration. 488 break; 489 } 490 491 // C++ [dcl.fct.default]p4: 492 // For non-template functions, default arguments can be added in 493 // later declarations of a function in the same 494 // scope. Declarations in different scopes have completely 495 // distinct sets of default arguments. That is, declarations in 496 // inner scopes do not acquire default arguments from 497 // declarations in outer scopes, and vice versa. In a given 498 // function declaration, all parameters subsequent to a 499 // parameter with a default argument shall have default 500 // arguments supplied in this or previous declarations. A 501 // default argument shall not be redefined by a later 502 // declaration (not even to the same value). 503 // 504 // C++ [dcl.fct.default]p6: 505 // Except for member functions of class templates, the default arguments 506 // in a member function definition that appears outside of the class 507 // definition are added to the set of default arguments provided by the 508 // member function declaration in the class definition. 509 for (unsigned p = 0, NumParams = PrevForDefaultArgs 510 ? PrevForDefaultArgs->getNumParams() 511 : 0; 512 p < NumParams; ++p) { 513 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p); 514 ParmVarDecl *NewParam = New->getParamDecl(p); 515 516 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false; 517 bool NewParamHasDfl = NewParam->hasDefaultArg(); 518 519 if (OldParamHasDfl && NewParamHasDfl) { 520 unsigned DiagDefaultParamID = 521 diag::err_param_default_argument_redefinition; 522 523 // MSVC accepts that default parameters be redefined for member functions 524 // of template class. The new default parameter's value is ignored. 525 Invalid = true; 526 if (getLangOpts().MicrosoftExt) { 527 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New); 528 if (MD && MD->getParent()->getDescribedClassTemplate()) { 529 // Merge the old default argument into the new parameter. 530 NewParam->setHasInheritedDefaultArg(); 531 if (OldParam->hasUninstantiatedDefaultArg()) 532 NewParam->setUninstantiatedDefaultArg( 533 OldParam->getUninstantiatedDefaultArg()); 534 else 535 NewParam->setDefaultArg(OldParam->getInit()); 536 DiagDefaultParamID = diag::ext_param_default_argument_redefinition; 537 Invalid = false; 538 } 539 } 540 541 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 542 // hint here. Alternatively, we could walk the type-source information 543 // for NewParam to find the last source location in the type... but it 544 // isn't worth the effort right now. This is the kind of test case that 545 // is hard to get right: 546 // int f(int); 547 // void g(int (*fp)(int) = f); 548 // void g(int (*fp)(int) = &f); 549 Diag(NewParam->getLocation(), DiagDefaultParamID) 550 << NewParam->getDefaultArgRange(); 551 552 // Look for the function declaration where the default argument was 553 // actually written, which may be a declaration prior to Old. 554 for (auto Older = PrevForDefaultArgs; 555 OldParam->hasInheritedDefaultArg(); /**/) { 556 Older = Older->getPreviousDecl(); 557 OldParam = Older->getParamDecl(p); 558 } 559 560 Diag(OldParam->getLocation(), diag::note_previous_definition) 561 << OldParam->getDefaultArgRange(); 562 } else if (OldParamHasDfl) { 563 // Merge the old default argument into the new parameter unless the new 564 // function is a friend declaration in a template class. In the latter 565 // case the default arguments will be inherited when the friend 566 // declaration will be instantiated. 567 if (New->getFriendObjectKind() == Decl::FOK_None || 568 !New->getLexicalDeclContext()->isDependentContext()) { 569 // It's important to use getInit() here; getDefaultArg() 570 // strips off any top-level ExprWithCleanups. 571 NewParam->setHasInheritedDefaultArg(); 572 if (OldParam->hasUnparsedDefaultArg()) 573 NewParam->setUnparsedDefaultArg(); 574 else if (OldParam->hasUninstantiatedDefaultArg()) 575 NewParam->setUninstantiatedDefaultArg( 576 OldParam->getUninstantiatedDefaultArg()); 577 else 578 NewParam->setDefaultArg(OldParam->getInit()); 579 } 580 } else if (NewParamHasDfl) { 581 if (New->getDescribedFunctionTemplate()) { 582 // Paragraph 4, quoted above, only applies to non-template functions. 583 Diag(NewParam->getLocation(), 584 diag::err_param_default_argument_template_redecl) 585 << NewParam->getDefaultArgRange(); 586 Diag(PrevForDefaultArgs->getLocation(), 587 diag::note_template_prev_declaration) 588 << false; 589 } else if (New->getTemplateSpecializationKind() 590 != TSK_ImplicitInstantiation && 591 New->getTemplateSpecializationKind() != TSK_Undeclared) { 592 // C++ [temp.expr.spec]p21: 593 // Default function arguments shall not be specified in a declaration 594 // or a definition for one of the following explicit specializations: 595 // - the explicit specialization of a function template; 596 // - the explicit specialization of a member function template; 597 // - the explicit specialization of a member function of a class 598 // template where the class template specialization to which the 599 // member function specialization belongs is implicitly 600 // instantiated. 601 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 602 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 603 << New->getDeclName() 604 << NewParam->getDefaultArgRange(); 605 } else if (New->getDeclContext()->isDependentContext()) { 606 // C++ [dcl.fct.default]p6 (DR217): 607 // Default arguments for a member function of a class template shall 608 // be specified on the initial declaration of the member function 609 // within the class template. 610 // 611 // Reading the tea leaves a bit in DR217 and its reference to DR205 612 // leads me to the conclusion that one cannot add default function 613 // arguments for an out-of-line definition of a member function of a 614 // dependent type. 615 int WhichKind = 2; 616 if (CXXRecordDecl *Record 617 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 618 if (Record->getDescribedClassTemplate()) 619 WhichKind = 0; 620 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 621 WhichKind = 1; 622 else 623 WhichKind = 2; 624 } 625 626 Diag(NewParam->getLocation(), 627 diag::err_param_default_argument_member_template_redecl) 628 << WhichKind 629 << NewParam->getDefaultArgRange(); 630 } 631 } 632 } 633 634 // DR1344: If a default argument is added outside a class definition and that 635 // default argument makes the function a special member function, the program 636 // is ill-formed. This can only happen for constructors. 637 if (isa<CXXConstructorDecl>(New) && 638 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 639 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 640 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 641 if (NewSM != OldSM) { 642 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 643 assert(NewParam->hasDefaultArg()); 644 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 645 << NewParam->getDefaultArgRange() << NewSM; 646 Diag(Old->getLocation(), diag::note_previous_declaration); 647 } 648 } 649 650 const FunctionDecl *Def; 651 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 652 // template has a constexpr specifier then all its declarations shall 653 // contain the constexpr specifier. 654 if (New->getConstexprKind() != Old->getConstexprKind()) { 655 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 656 << New << static_cast<int>(New->getConstexprKind()) 657 << static_cast<int>(Old->getConstexprKind()); 658 Diag(Old->getLocation(), diag::note_previous_declaration); 659 Invalid = true; 660 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() && 661 Old->isDefined(Def) && 662 // If a friend function is inlined but does not have 'inline' 663 // specifier, it is a definition. Do not report attribute conflict 664 // in this case, redefinition will be diagnosed later. 665 (New->isInlineSpecified() || 666 New->getFriendObjectKind() == Decl::FOK_None)) { 667 // C++11 [dcl.fcn.spec]p4: 668 // If the definition of a function appears in a translation unit before its 669 // first declaration as inline, the program is ill-formed. 670 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 671 Diag(Def->getLocation(), diag::note_previous_definition); 672 Invalid = true; 673 } 674 675 // C++17 [temp.deduct.guide]p3: 676 // Two deduction guide declarations in the same translation unit 677 // for the same class template shall not have equivalent 678 // parameter-declaration-clauses. 679 if (isa<CXXDeductionGuideDecl>(New) && 680 !New->isFunctionTemplateSpecialization() && isVisible(Old)) { 681 Diag(New->getLocation(), diag::err_deduction_guide_redeclared); 682 Diag(Old->getLocation(), diag::note_previous_declaration); 683 } 684 685 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 686 // argument expression, that declaration shall be a definition and shall be 687 // the only declaration of the function or function template in the 688 // translation unit. 689 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 690 functionDeclHasDefaultArgument(Old)) { 691 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 692 Diag(Old->getLocation(), diag::note_previous_declaration); 693 Invalid = true; 694 } 695 696 // C++11 [temp.friend]p4 (DR329): 697 // When a function is defined in a friend function declaration in a class 698 // template, the function is instantiated when the function is odr-used. 699 // The same restrictions on multiple declarations and definitions that 700 // apply to non-template function declarations and definitions also apply 701 // to these implicit definitions. 702 const FunctionDecl *OldDefinition = nullptr; 703 if (New->isThisDeclarationInstantiatedFromAFriendDefinition() && 704 Old->isDefined(OldDefinition, true)) 705 CheckForFunctionRedefinition(New, OldDefinition); 706 707 return Invalid; 708 } 709 710 NamedDecl * 711 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D, 712 MultiTemplateParamsArg TemplateParamLists) { 713 assert(D.isDecompositionDeclarator()); 714 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 715 716 // The syntax only allows a decomposition declarator as a simple-declaration, 717 // a for-range-declaration, or a condition in Clang, but we parse it in more 718 // cases than that. 719 if (!D.mayHaveDecompositionDeclarator()) { 720 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 721 << Decomp.getSourceRange(); 722 return nullptr; 723 } 724 725 if (!TemplateParamLists.empty()) { 726 // FIXME: There's no rule against this, but there are also no rules that 727 // would actually make it usable, so we reject it for now. 728 Diag(TemplateParamLists.front()->getTemplateLoc(), 729 diag::err_decomp_decl_template); 730 return nullptr; 731 } 732 733 Diag(Decomp.getLSquareLoc(), 734 !getLangOpts().CPlusPlus17 735 ? diag::ext_decomp_decl 736 : D.getContext() == DeclaratorContext::Condition 737 ? diag::ext_decomp_decl_cond 738 : diag::warn_cxx14_compat_decomp_decl) 739 << Decomp.getSourceRange(); 740 741 // The semantic context is always just the current context. 742 DeclContext *const DC = CurContext; 743 744 // C++17 [dcl.dcl]/8: 745 // The decl-specifier-seq shall contain only the type-specifier auto 746 // and cv-qualifiers. 747 // C++2a [dcl.dcl]/8: 748 // If decl-specifier-seq contains any decl-specifier other than static, 749 // thread_local, auto, or cv-qualifiers, the program is ill-formed. 750 auto &DS = D.getDeclSpec(); 751 { 752 SmallVector<StringRef, 8> BadSpecifiers; 753 SmallVector<SourceLocation, 8> BadSpecifierLocs; 754 SmallVector<StringRef, 8> CPlusPlus20Specifiers; 755 SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs; 756 if (auto SCS = DS.getStorageClassSpec()) { 757 if (SCS == DeclSpec::SCS_static) { 758 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS)); 759 CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 760 } else { 761 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS)); 762 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 763 } 764 } 765 if (auto TSCS = DS.getThreadStorageClassSpec()) { 766 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS)); 767 CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc()); 768 } 769 if (DS.hasConstexprSpecifier()) { 770 BadSpecifiers.push_back( 771 DeclSpec::getSpecifierName(DS.getConstexprSpecifier())); 772 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc()); 773 } 774 if (DS.isInlineSpecified()) { 775 BadSpecifiers.push_back("inline"); 776 BadSpecifierLocs.push_back(DS.getInlineSpecLoc()); 777 } 778 if (!BadSpecifiers.empty()) { 779 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec); 780 Err << (int)BadSpecifiers.size() 781 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " "); 782 // Don't add FixItHints to remove the specifiers; we do still respect 783 // them when building the underlying variable. 784 for (auto Loc : BadSpecifierLocs) 785 Err << SourceRange(Loc, Loc); 786 } else if (!CPlusPlus20Specifiers.empty()) { 787 auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(), 788 getLangOpts().CPlusPlus20 789 ? diag::warn_cxx17_compat_decomp_decl_spec 790 : diag::ext_decomp_decl_spec); 791 Warn << (int)CPlusPlus20Specifiers.size() 792 << llvm::join(CPlusPlus20Specifiers.begin(), 793 CPlusPlus20Specifiers.end(), " "); 794 for (auto Loc : CPlusPlus20SpecifierLocs) 795 Warn << SourceRange(Loc, Loc); 796 } 797 // We can't recover from it being declared as a typedef. 798 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 799 return nullptr; 800 } 801 802 // C++2a [dcl.struct.bind]p1: 803 // A cv that includes volatile is deprecated 804 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) && 805 getLangOpts().CPlusPlus20) 806 Diag(DS.getVolatileSpecLoc(), 807 diag::warn_deprecated_volatile_structured_binding); 808 809 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 810 QualType R = TInfo->getType(); 811 812 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 813 UPPC_DeclarationType)) 814 D.setInvalidType(); 815 816 // The syntax only allows a single ref-qualifier prior to the decomposition 817 // declarator. No other declarator chunks are permitted. Also check the type 818 // specifier here. 819 if (DS.getTypeSpecType() != DeclSpec::TST_auto || 820 D.hasGroupingParens() || D.getNumTypeObjects() > 1 || 821 (D.getNumTypeObjects() == 1 && 822 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) { 823 Diag(Decomp.getLSquareLoc(), 824 (D.hasGroupingParens() || 825 (D.getNumTypeObjects() && 826 D.getTypeObject(0).Kind == DeclaratorChunk::Paren)) 827 ? diag::err_decomp_decl_parens 828 : diag::err_decomp_decl_type) 829 << R; 830 831 // In most cases, there's no actual problem with an explicitly-specified 832 // type, but a function type won't work here, and ActOnVariableDeclarator 833 // shouldn't be called for such a type. 834 if (R->isFunctionType()) 835 D.setInvalidType(); 836 } 837 838 // Build the BindingDecls. 839 SmallVector<BindingDecl*, 8> Bindings; 840 841 // Build the BindingDecls. 842 for (auto &B : D.getDecompositionDeclarator().bindings()) { 843 // Check for name conflicts. 844 DeclarationNameInfo NameInfo(B.Name, B.NameLoc); 845 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 846 ForVisibleRedeclaration); 847 LookupName(Previous, S, 848 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit()); 849 850 // It's not permitted to shadow a template parameter name. 851 if (Previous.isSingleResult() && 852 Previous.getFoundDecl()->isTemplateParameter()) { 853 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 854 Previous.getFoundDecl()); 855 Previous.clear(); 856 } 857 858 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name); 859 860 // Find the shadowed declaration before filtering for scope. 861 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 862 ? getShadowedDeclaration(BD, Previous) 863 : nullptr; 864 865 bool ConsiderLinkage = DC->isFunctionOrMethod() && 866 DS.getStorageClassSpec() == DeclSpec::SCS_extern; 867 FilterLookupForScope(Previous, DC, S, ConsiderLinkage, 868 /*AllowInlineNamespace*/false); 869 870 if (!Previous.empty()) { 871 auto *Old = Previous.getRepresentativeDecl(); 872 Diag(B.NameLoc, diag::err_redefinition) << B.Name; 873 Diag(Old->getLocation(), diag::note_previous_definition); 874 } else if (ShadowedDecl && !D.isRedeclaration()) { 875 CheckShadow(BD, ShadowedDecl, Previous); 876 } 877 PushOnScopeChains(BD, S, true); 878 Bindings.push_back(BD); 879 ParsingInitForAutoVars.insert(BD); 880 } 881 882 // There are no prior lookup results for the variable itself, because it 883 // is unnamed. 884 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr, 885 Decomp.getLSquareLoc()); 886 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 887 ForVisibleRedeclaration); 888 889 // Build the variable that holds the non-decomposed object. 890 bool AddToScope = true; 891 NamedDecl *New = 892 ActOnVariableDeclarator(S, D, DC, TInfo, Previous, 893 MultiTemplateParamsArg(), AddToScope, Bindings); 894 if (AddToScope) { 895 S->AddDecl(New); 896 CurContext->addHiddenDecl(New); 897 } 898 899 if (isInOpenMPDeclareTargetContext()) 900 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 901 902 return New; 903 } 904 905 static bool checkSimpleDecomposition( 906 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src, 907 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType, 908 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) { 909 if ((int64_t)Bindings.size() != NumElems) { 910 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 911 << DecompType << (unsigned)Bindings.size() 912 << (unsigned)NumElems.getLimitedValue(UINT_MAX) 913 << toString(NumElems, 10) << (NumElems < Bindings.size()); 914 return true; 915 } 916 917 unsigned I = 0; 918 for (auto *B : Bindings) { 919 SourceLocation Loc = B->getLocation(); 920 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 921 if (E.isInvalid()) 922 return true; 923 E = GetInit(Loc, E.get(), I++); 924 if (E.isInvalid()) 925 return true; 926 B->setBinding(ElemType, E.get()); 927 } 928 929 return false; 930 } 931 932 static bool checkArrayLikeDecomposition(Sema &S, 933 ArrayRef<BindingDecl *> Bindings, 934 ValueDecl *Src, QualType DecompType, 935 const llvm::APSInt &NumElems, 936 QualType ElemType) { 937 return checkSimpleDecomposition( 938 S, Bindings, Src, DecompType, NumElems, ElemType, 939 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 940 ExprResult E = S.ActOnIntegerConstant(Loc, I); 941 if (E.isInvalid()) 942 return ExprError(); 943 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc); 944 }); 945 } 946 947 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 948 ValueDecl *Src, QualType DecompType, 949 const ConstantArrayType *CAT) { 950 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType, 951 llvm::APSInt(CAT->getSize()), 952 CAT->getElementType()); 953 } 954 955 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 956 ValueDecl *Src, QualType DecompType, 957 const VectorType *VT) { 958 return checkArrayLikeDecomposition( 959 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()), 960 S.Context.getQualifiedType(VT->getElementType(), 961 DecompType.getQualifiers())); 962 } 963 964 static bool checkComplexDecomposition(Sema &S, 965 ArrayRef<BindingDecl *> Bindings, 966 ValueDecl *Src, QualType DecompType, 967 const ComplexType *CT) { 968 return checkSimpleDecomposition( 969 S, Bindings, Src, DecompType, llvm::APSInt::get(2), 970 S.Context.getQualifiedType(CT->getElementType(), 971 DecompType.getQualifiers()), 972 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 973 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base); 974 }); 975 } 976 977 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy, 978 TemplateArgumentListInfo &Args, 979 const TemplateParameterList *Params) { 980 SmallString<128> SS; 981 llvm::raw_svector_ostream OS(SS); 982 bool First = true; 983 unsigned I = 0; 984 for (auto &Arg : Args.arguments()) { 985 if (!First) 986 OS << ", "; 987 Arg.getArgument().print(PrintingPolicy, OS, 988 TemplateParameterList::shouldIncludeTypeForArgument( 989 PrintingPolicy, Params, I)); 990 First = false; 991 I++; 992 } 993 return std::string(OS.str()); 994 } 995 996 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup, 997 SourceLocation Loc, StringRef Trait, 998 TemplateArgumentListInfo &Args, 999 unsigned DiagID) { 1000 auto DiagnoseMissing = [&] { 1001 if (DiagID) 1002 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(), 1003 Args, /*Params*/ nullptr); 1004 return true; 1005 }; 1006 1007 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine. 1008 NamespaceDecl *Std = S.getStdNamespace(); 1009 if (!Std) 1010 return DiagnoseMissing(); 1011 1012 // Look up the trait itself, within namespace std. We can diagnose various 1013 // problems with this lookup even if we've been asked to not diagnose a 1014 // missing specialization, because this can only fail if the user has been 1015 // declaring their own names in namespace std or we don't support the 1016 // standard library implementation in use. 1017 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait), 1018 Loc, Sema::LookupOrdinaryName); 1019 if (!S.LookupQualifiedName(Result, Std)) 1020 return DiagnoseMissing(); 1021 if (Result.isAmbiguous()) 1022 return true; 1023 1024 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>(); 1025 if (!TraitTD) { 1026 Result.suppressDiagnostics(); 1027 NamedDecl *Found = *Result.begin(); 1028 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait; 1029 S.Diag(Found->getLocation(), diag::note_declared_at); 1030 return true; 1031 } 1032 1033 // Build the template-id. 1034 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args); 1035 if (TraitTy.isNull()) 1036 return true; 1037 if (!S.isCompleteType(Loc, TraitTy)) { 1038 if (DiagID) 1039 S.RequireCompleteType( 1040 Loc, TraitTy, DiagID, 1041 printTemplateArgs(S.Context.getPrintingPolicy(), Args, 1042 TraitTD->getTemplateParameters())); 1043 return true; 1044 } 1045 1046 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl(); 1047 assert(RD && "specialization of class template is not a class?"); 1048 1049 // Look up the member of the trait type. 1050 S.LookupQualifiedName(TraitMemberLookup, RD); 1051 return TraitMemberLookup.isAmbiguous(); 1052 } 1053 1054 static TemplateArgumentLoc 1055 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, 1056 uint64_t I) { 1057 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T); 1058 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc); 1059 } 1060 1061 static TemplateArgumentLoc 1062 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) { 1063 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc); 1064 } 1065 1066 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; } 1067 1068 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, 1069 llvm::APSInt &Size) { 1070 EnterExpressionEvaluationContext ContextRAII( 1071 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 1072 1073 DeclarationName Value = S.PP.getIdentifierInfo("value"); 1074 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName); 1075 1076 // Form template argument list for tuple_size<T>. 1077 TemplateArgumentListInfo Args(Loc, Loc); 1078 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1079 1080 // If there's no tuple_size specialization or the lookup of 'value' is empty, 1081 // it's not tuple-like. 1082 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) || 1083 R.empty()) 1084 return IsTupleLike::NotTupleLike; 1085 1086 // If we get this far, we've committed to the tuple interpretation, but 1087 // we can still fail if there actually isn't a usable ::value. 1088 1089 struct ICEDiagnoser : Sema::VerifyICEDiagnoser { 1090 LookupResult &R; 1091 TemplateArgumentListInfo &Args; 1092 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args) 1093 : R(R), Args(Args) {} 1094 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S, 1095 SourceLocation Loc) override { 1096 return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant) 1097 << printTemplateArgs(S.Context.getPrintingPolicy(), Args, 1098 /*Params*/ nullptr); 1099 } 1100 } Diagnoser(R, Args); 1101 1102 ExprResult E = 1103 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false); 1104 if (E.isInvalid()) 1105 return IsTupleLike::Error; 1106 1107 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser); 1108 if (E.isInvalid()) 1109 return IsTupleLike::Error; 1110 1111 return IsTupleLike::TupleLike; 1112 } 1113 1114 /// \return std::tuple_element<I, T>::type. 1115 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, 1116 unsigned I, QualType T) { 1117 // Form template argument list for tuple_element<I, T>. 1118 TemplateArgumentListInfo Args(Loc, Loc); 1119 Args.addArgument( 1120 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1121 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1122 1123 DeclarationName TypeDN = S.PP.getIdentifierInfo("type"); 1124 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName); 1125 if (lookupStdTypeTraitMember( 1126 S, R, Loc, "tuple_element", Args, 1127 diag::err_decomp_decl_std_tuple_element_not_specialized)) 1128 return QualType(); 1129 1130 auto *TD = R.getAsSingle<TypeDecl>(); 1131 if (!TD) { 1132 R.suppressDiagnostics(); 1133 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized) 1134 << printTemplateArgs(S.Context.getPrintingPolicy(), Args, 1135 /*Params*/ nullptr); 1136 if (!R.empty()) 1137 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at); 1138 return QualType(); 1139 } 1140 1141 return S.Context.getTypeDeclType(TD); 1142 } 1143 1144 namespace { 1145 struct InitializingBinding { 1146 Sema &S; 1147 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) { 1148 Sema::CodeSynthesisContext Ctx; 1149 Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding; 1150 Ctx.PointOfInstantiation = BD->getLocation(); 1151 Ctx.Entity = BD; 1152 S.pushCodeSynthesisContext(Ctx); 1153 } 1154 ~InitializingBinding() { 1155 S.popCodeSynthesisContext(); 1156 } 1157 }; 1158 } 1159 1160 static bool checkTupleLikeDecomposition(Sema &S, 1161 ArrayRef<BindingDecl *> Bindings, 1162 VarDecl *Src, QualType DecompType, 1163 const llvm::APSInt &TupleSize) { 1164 if ((int64_t)Bindings.size() != TupleSize) { 1165 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1166 << DecompType << (unsigned)Bindings.size() 1167 << (unsigned)TupleSize.getLimitedValue(UINT_MAX) 1168 << toString(TupleSize, 10) << (TupleSize < Bindings.size()); 1169 return true; 1170 } 1171 1172 if (Bindings.empty()) 1173 return false; 1174 1175 DeclarationName GetDN = S.PP.getIdentifierInfo("get"); 1176 1177 // [dcl.decomp]p3: 1178 // The unqualified-id get is looked up in the scope of E by class member 1179 // access lookup ... 1180 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName); 1181 bool UseMemberGet = false; 1182 if (S.isCompleteType(Src->getLocation(), DecompType)) { 1183 if (auto *RD = DecompType->getAsCXXRecordDecl()) 1184 S.LookupQualifiedName(MemberGet, RD); 1185 if (MemberGet.isAmbiguous()) 1186 return true; 1187 // ... and if that finds at least one declaration that is a function 1188 // template whose first template parameter is a non-type parameter ... 1189 for (NamedDecl *D : MemberGet) { 1190 if (FunctionTemplateDecl *FTD = 1191 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) { 1192 TemplateParameterList *TPL = FTD->getTemplateParameters(); 1193 if (TPL->size() != 0 && 1194 isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) { 1195 // ... the initializer is e.get<i>(). 1196 UseMemberGet = true; 1197 break; 1198 } 1199 } 1200 } 1201 } 1202 1203 unsigned I = 0; 1204 for (auto *B : Bindings) { 1205 InitializingBinding InitContext(S, B); 1206 SourceLocation Loc = B->getLocation(); 1207 1208 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1209 if (E.isInvalid()) 1210 return true; 1211 1212 // e is an lvalue if the type of the entity is an lvalue reference and 1213 // an xvalue otherwise 1214 if (!Src->getType()->isLValueReferenceType()) 1215 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp, 1216 E.get(), nullptr, VK_XValue, 1217 FPOptionsOverride()); 1218 1219 TemplateArgumentListInfo Args(Loc, Loc); 1220 Args.addArgument( 1221 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1222 1223 if (UseMemberGet) { 1224 // if [lookup of member get] finds at least one declaration, the 1225 // initializer is e.get<i-1>(). 1226 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false, 1227 CXXScopeSpec(), SourceLocation(), nullptr, 1228 MemberGet, &Args, nullptr); 1229 if (E.isInvalid()) 1230 return true; 1231 1232 E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc); 1233 } else { 1234 // Otherwise, the initializer is get<i-1>(e), where get is looked up 1235 // in the associated namespaces. 1236 Expr *Get = UnresolvedLookupExpr::Create( 1237 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(), 1238 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args, 1239 UnresolvedSetIterator(), UnresolvedSetIterator()); 1240 1241 Expr *Arg = E.get(); 1242 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc); 1243 } 1244 if (E.isInvalid()) 1245 return true; 1246 Expr *Init = E.get(); 1247 1248 // Given the type T designated by std::tuple_element<i - 1, E>::type, 1249 QualType T = getTupleLikeElementType(S, Loc, I, DecompType); 1250 if (T.isNull()) 1251 return true; 1252 1253 // each vi is a variable of type "reference to T" initialized with the 1254 // initializer, where the reference is an lvalue reference if the 1255 // initializer is an lvalue and an rvalue reference otherwise 1256 QualType RefType = 1257 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName()); 1258 if (RefType.isNull()) 1259 return true; 1260 auto *RefVD = VarDecl::Create( 1261 S.Context, Src->getDeclContext(), Loc, Loc, 1262 B->getDeclName().getAsIdentifierInfo(), RefType, 1263 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass()); 1264 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext()); 1265 RefVD->setTSCSpec(Src->getTSCSpec()); 1266 RefVD->setImplicit(); 1267 if (Src->isInlineSpecified()) 1268 RefVD->setInlineSpecified(); 1269 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD); 1270 1271 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD); 1272 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc); 1273 InitializationSequence Seq(S, Entity, Kind, Init); 1274 E = Seq.Perform(S, Entity, Kind, Init); 1275 if (E.isInvalid()) 1276 return true; 1277 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false); 1278 if (E.isInvalid()) 1279 return true; 1280 RefVD->setInit(E.get()); 1281 S.CheckCompleteVariableDeclaration(RefVD); 1282 1283 E = S.BuildDeclarationNameExpr(CXXScopeSpec(), 1284 DeclarationNameInfo(B->getDeclName(), Loc), 1285 RefVD); 1286 if (E.isInvalid()) 1287 return true; 1288 1289 B->setBinding(T, E.get()); 1290 I++; 1291 } 1292 1293 return false; 1294 } 1295 1296 /// Find the base class to decompose in a built-in decomposition of a class type. 1297 /// This base class search is, unfortunately, not quite like any other that we 1298 /// perform anywhere else in C++. 1299 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc, 1300 const CXXRecordDecl *RD, 1301 CXXCastPath &BasePath) { 1302 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier, 1303 CXXBasePath &Path) { 1304 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields(); 1305 }; 1306 1307 const CXXRecordDecl *ClassWithFields = nullptr; 1308 AccessSpecifier AS = AS_public; 1309 if (RD->hasDirectFields()) 1310 // [dcl.decomp]p4: 1311 // Otherwise, all of E's non-static data members shall be public direct 1312 // members of E ... 1313 ClassWithFields = RD; 1314 else { 1315 // ... or of ... 1316 CXXBasePaths Paths; 1317 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD)); 1318 if (!RD->lookupInBases(BaseHasFields, Paths)) { 1319 // If no classes have fields, just decompose RD itself. (This will work 1320 // if and only if zero bindings were provided.) 1321 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public); 1322 } 1323 1324 CXXBasePath *BestPath = nullptr; 1325 for (auto &P : Paths) { 1326 if (!BestPath) 1327 BestPath = &P; 1328 else if (!S.Context.hasSameType(P.back().Base->getType(), 1329 BestPath->back().Base->getType())) { 1330 // ... the same ... 1331 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1332 << false << RD << BestPath->back().Base->getType() 1333 << P.back().Base->getType(); 1334 return DeclAccessPair(); 1335 } else if (P.Access < BestPath->Access) { 1336 BestPath = &P; 1337 } 1338 } 1339 1340 // ... unambiguous ... 1341 QualType BaseType = BestPath->back().Base->getType(); 1342 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) { 1343 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base) 1344 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths); 1345 return DeclAccessPair(); 1346 } 1347 1348 // ... [accessible, implied by other rules] base class of E. 1349 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD), 1350 *BestPath, diag::err_decomp_decl_inaccessible_base); 1351 AS = BestPath->Access; 1352 1353 ClassWithFields = BaseType->getAsCXXRecordDecl(); 1354 S.BuildBasePathArray(Paths, BasePath); 1355 } 1356 1357 // The above search did not check whether the selected class itself has base 1358 // classes with fields, so check that now. 1359 CXXBasePaths Paths; 1360 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) { 1361 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1362 << (ClassWithFields == RD) << RD << ClassWithFields 1363 << Paths.front().back().Base->getType(); 1364 return DeclAccessPair(); 1365 } 1366 1367 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS); 1368 } 1369 1370 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 1371 ValueDecl *Src, QualType DecompType, 1372 const CXXRecordDecl *OrigRD) { 1373 if (S.RequireCompleteType(Src->getLocation(), DecompType, 1374 diag::err_incomplete_type)) 1375 return true; 1376 1377 CXXCastPath BasePath; 1378 DeclAccessPair BasePair = 1379 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath); 1380 const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl()); 1381 if (!RD) 1382 return true; 1383 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD), 1384 DecompType.getQualifiers()); 1385 1386 auto DiagnoseBadNumberOfBindings = [&]() -> bool { 1387 unsigned NumFields = llvm::count_if( 1388 RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); }); 1389 assert(Bindings.size() != NumFields); 1390 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1391 << DecompType << (unsigned)Bindings.size() << NumFields << NumFields 1392 << (NumFields < Bindings.size()); 1393 return true; 1394 }; 1395 1396 // all of E's non-static data members shall be [...] well-formed 1397 // when named as e.name in the context of the structured binding, 1398 // E shall not have an anonymous union member, ... 1399 unsigned I = 0; 1400 for (auto *FD : RD->fields()) { 1401 if (FD->isUnnamedBitfield()) 1402 continue; 1403 1404 // All the non-static data members are required to be nameable, so they 1405 // must all have names. 1406 if (!FD->getDeclName()) { 1407 if (RD->isLambda()) { 1408 S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda); 1409 S.Diag(RD->getLocation(), diag::note_lambda_decl); 1410 return true; 1411 } 1412 1413 if (FD->isAnonymousStructOrUnion()) { 1414 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member) 1415 << DecompType << FD->getType()->isUnionType(); 1416 S.Diag(FD->getLocation(), diag::note_declared_at); 1417 return true; 1418 } 1419 1420 // FIXME: Are there any other ways we could have an anonymous member? 1421 } 1422 1423 // We have a real field to bind. 1424 if (I >= Bindings.size()) 1425 return DiagnoseBadNumberOfBindings(); 1426 auto *B = Bindings[I++]; 1427 SourceLocation Loc = B->getLocation(); 1428 1429 // The field must be accessible in the context of the structured binding. 1430 // We already checked that the base class is accessible. 1431 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the 1432 // const_cast here. 1433 S.CheckStructuredBindingMemberAccess( 1434 Loc, const_cast<CXXRecordDecl *>(OrigRD), 1435 DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess( 1436 BasePair.getAccess(), FD->getAccess()))); 1437 1438 // Initialize the binding to Src.FD. 1439 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1440 if (E.isInvalid()) 1441 return true; 1442 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase, 1443 VK_LValue, &BasePath); 1444 if (E.isInvalid()) 1445 return true; 1446 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc, 1447 CXXScopeSpec(), FD, 1448 DeclAccessPair::make(FD, FD->getAccess()), 1449 DeclarationNameInfo(FD->getDeclName(), Loc)); 1450 if (E.isInvalid()) 1451 return true; 1452 1453 // If the type of the member is T, the referenced type is cv T, where cv is 1454 // the cv-qualification of the decomposition expression. 1455 // 1456 // FIXME: We resolve a defect here: if the field is mutable, we do not add 1457 // 'const' to the type of the field. 1458 Qualifiers Q = DecompType.getQualifiers(); 1459 if (FD->isMutable()) 1460 Q.removeConst(); 1461 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get()); 1462 } 1463 1464 if (I != Bindings.size()) 1465 return DiagnoseBadNumberOfBindings(); 1466 1467 return false; 1468 } 1469 1470 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) { 1471 QualType DecompType = DD->getType(); 1472 1473 // If the type of the decomposition is dependent, then so is the type of 1474 // each binding. 1475 if (DecompType->isDependentType()) { 1476 for (auto *B : DD->bindings()) 1477 B->setType(Context.DependentTy); 1478 return; 1479 } 1480 1481 DecompType = DecompType.getNonReferenceType(); 1482 ArrayRef<BindingDecl*> Bindings = DD->bindings(); 1483 1484 // C++1z [dcl.decomp]/2: 1485 // If E is an array type [...] 1486 // As an extension, we also support decomposition of built-in complex and 1487 // vector types. 1488 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) { 1489 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT)) 1490 DD->setInvalidDecl(); 1491 return; 1492 } 1493 if (auto *VT = DecompType->getAs<VectorType>()) { 1494 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT)) 1495 DD->setInvalidDecl(); 1496 return; 1497 } 1498 if (auto *CT = DecompType->getAs<ComplexType>()) { 1499 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT)) 1500 DD->setInvalidDecl(); 1501 return; 1502 } 1503 1504 // C++1z [dcl.decomp]/3: 1505 // if the expression std::tuple_size<E>::value is a well-formed integral 1506 // constant expression, [...] 1507 llvm::APSInt TupleSize(32); 1508 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) { 1509 case IsTupleLike::Error: 1510 DD->setInvalidDecl(); 1511 return; 1512 1513 case IsTupleLike::TupleLike: 1514 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize)) 1515 DD->setInvalidDecl(); 1516 return; 1517 1518 case IsTupleLike::NotTupleLike: 1519 break; 1520 } 1521 1522 // C++1z [dcl.dcl]/8: 1523 // [E shall be of array or non-union class type] 1524 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl(); 1525 if (!RD || RD->isUnion()) { 1526 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type) 1527 << DD << !RD << DecompType; 1528 DD->setInvalidDecl(); 1529 return; 1530 } 1531 1532 // C++1z [dcl.decomp]/4: 1533 // all of E's non-static data members shall be [...] direct members of 1534 // E or of the same unambiguous public base class of E, ... 1535 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD)) 1536 DD->setInvalidDecl(); 1537 } 1538 1539 /// Merge the exception specifications of two variable declarations. 1540 /// 1541 /// This is called when there's a redeclaration of a VarDecl. The function 1542 /// checks if the redeclaration might have an exception specification and 1543 /// validates compatibility and merges the specs if necessary. 1544 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 1545 // Shortcut if exceptions are disabled. 1546 if (!getLangOpts().CXXExceptions) 1547 return; 1548 1549 assert(Context.hasSameType(New->getType(), Old->getType()) && 1550 "Should only be called if types are otherwise the same."); 1551 1552 QualType NewType = New->getType(); 1553 QualType OldType = Old->getType(); 1554 1555 // We're only interested in pointers and references to functions, as well 1556 // as pointers to member functions. 1557 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 1558 NewType = R->getPointeeType(); 1559 OldType = OldType->castAs<ReferenceType>()->getPointeeType(); 1560 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 1561 NewType = P->getPointeeType(); 1562 OldType = OldType->castAs<PointerType>()->getPointeeType(); 1563 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 1564 NewType = M->getPointeeType(); 1565 OldType = OldType->castAs<MemberPointerType>()->getPointeeType(); 1566 } 1567 1568 if (!NewType->isFunctionProtoType()) 1569 return; 1570 1571 // There's lots of special cases for functions. For function pointers, system 1572 // libraries are hopefully not as broken so that we don't need these 1573 // workarounds. 1574 if (CheckEquivalentExceptionSpec( 1575 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 1576 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 1577 New->setInvalidDecl(); 1578 } 1579 } 1580 1581 /// CheckCXXDefaultArguments - Verify that the default arguments for a 1582 /// function declaration are well-formed according to C++ 1583 /// [dcl.fct.default]. 1584 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 1585 unsigned NumParams = FD->getNumParams(); 1586 unsigned ParamIdx = 0; 1587 1588 // This checking doesn't make sense for explicit specializations; their 1589 // default arguments are determined by the declaration we're specializing, 1590 // not by FD. 1591 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 1592 return; 1593 if (auto *FTD = FD->getDescribedFunctionTemplate()) 1594 if (FTD->isMemberSpecialization()) 1595 return; 1596 1597 // Find first parameter with a default argument 1598 for (; ParamIdx < NumParams; ++ParamIdx) { 1599 ParmVarDecl *Param = FD->getParamDecl(ParamIdx); 1600 if (Param->hasDefaultArg()) 1601 break; 1602 } 1603 1604 // C++20 [dcl.fct.default]p4: 1605 // In a given function declaration, each parameter subsequent to a parameter 1606 // with a default argument shall have a default argument supplied in this or 1607 // a previous declaration, unless the parameter was expanded from a 1608 // parameter pack, or shall be a function parameter pack. 1609 for (; ParamIdx < NumParams; ++ParamIdx) { 1610 ParmVarDecl *Param = FD->getParamDecl(ParamIdx); 1611 if (!Param->hasDefaultArg() && !Param->isParameterPack() && 1612 !(CurrentInstantiationScope && 1613 CurrentInstantiationScope->isLocalPackExpansion(Param))) { 1614 if (Param->isInvalidDecl()) 1615 /* We already complained about this parameter. */; 1616 else if (Param->getIdentifier()) 1617 Diag(Param->getLocation(), 1618 diag::err_param_default_argument_missing_name) 1619 << Param->getIdentifier(); 1620 else 1621 Diag(Param->getLocation(), 1622 diag::err_param_default_argument_missing); 1623 } 1624 } 1625 } 1626 1627 /// Check that the given type is a literal type. Issue a diagnostic if not, 1628 /// if Kind is Diagnose. 1629 /// \return \c true if a problem has been found (and optionally diagnosed). 1630 template <typename... Ts> 1631 static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind, 1632 SourceLocation Loc, QualType T, unsigned DiagID, 1633 Ts &&...DiagArgs) { 1634 if (T->isDependentType()) 1635 return false; 1636 1637 switch (Kind) { 1638 case Sema::CheckConstexprKind::Diagnose: 1639 return SemaRef.RequireLiteralType(Loc, T, DiagID, 1640 std::forward<Ts>(DiagArgs)...); 1641 1642 case Sema::CheckConstexprKind::CheckValid: 1643 return !T->isLiteralType(SemaRef.Context); 1644 } 1645 1646 llvm_unreachable("unknown CheckConstexprKind"); 1647 } 1648 1649 /// Determine whether a destructor cannot be constexpr due to 1650 static bool CheckConstexprDestructorSubobjects(Sema &SemaRef, 1651 const CXXDestructorDecl *DD, 1652 Sema::CheckConstexprKind Kind) { 1653 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) { 1654 const CXXRecordDecl *RD = 1655 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 1656 if (!RD || RD->hasConstexprDestructor()) 1657 return true; 1658 1659 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1660 SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject) 1661 << static_cast<int>(DD->getConstexprKind()) << !FD 1662 << (FD ? FD->getDeclName() : DeclarationName()) << T; 1663 SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject) 1664 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T; 1665 } 1666 return false; 1667 }; 1668 1669 const CXXRecordDecl *RD = DD->getParent(); 1670 for (const CXXBaseSpecifier &B : RD->bases()) 1671 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr)) 1672 return false; 1673 for (const FieldDecl *FD : RD->fields()) 1674 if (!Check(FD->getLocation(), FD->getType(), FD)) 1675 return false; 1676 return true; 1677 } 1678 1679 /// Check whether a function's parameter types are all literal types. If so, 1680 /// return true. If not, produce a suitable diagnostic and return false. 1681 static bool CheckConstexprParameterTypes(Sema &SemaRef, 1682 const FunctionDecl *FD, 1683 Sema::CheckConstexprKind Kind) { 1684 unsigned ArgIndex = 0; 1685 const auto *FT = FD->getType()->castAs<FunctionProtoType>(); 1686 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 1687 e = FT->param_type_end(); 1688 i != e; ++i, ++ArgIndex) { 1689 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 1690 SourceLocation ParamLoc = PD->getLocation(); 1691 if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i, 1692 diag::err_constexpr_non_literal_param, ArgIndex + 1, 1693 PD->getSourceRange(), isa<CXXConstructorDecl>(FD), 1694 FD->isConsteval())) 1695 return false; 1696 } 1697 return true; 1698 } 1699 1700 /// Check whether a function's return type is a literal type. If so, return 1701 /// true. If not, produce a suitable diagnostic and return false. 1702 static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD, 1703 Sema::CheckConstexprKind Kind) { 1704 if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(), 1705 diag::err_constexpr_non_literal_return, 1706 FD->isConsteval())) 1707 return false; 1708 return true; 1709 } 1710 1711 /// Get diagnostic %select index for tag kind for 1712 /// record diagnostic message. 1713 /// WARNING: Indexes apply to particular diagnostics only! 1714 /// 1715 /// \returns diagnostic %select index. 1716 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 1717 switch (Tag) { 1718 case TTK_Struct: return 0; 1719 case TTK_Interface: return 1; 1720 case TTK_Class: return 2; 1721 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 1722 } 1723 } 1724 1725 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, 1726 Stmt *Body, 1727 Sema::CheckConstexprKind Kind); 1728 1729 // Check whether a function declaration satisfies the requirements of a 1730 // constexpr function definition or a constexpr constructor definition. If so, 1731 // return true. If not, produce appropriate diagnostics (unless asked not to by 1732 // Kind) and return false. 1733 // 1734 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 1735 bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD, 1736 CheckConstexprKind Kind) { 1737 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 1738 if (MD && MD->isInstance()) { 1739 // C++11 [dcl.constexpr]p4: 1740 // The definition of a constexpr constructor shall satisfy the following 1741 // constraints: 1742 // - the class shall not have any virtual base classes; 1743 // 1744 // FIXME: This only applies to constructors and destructors, not arbitrary 1745 // member functions. 1746 const CXXRecordDecl *RD = MD->getParent(); 1747 if (RD->getNumVBases()) { 1748 if (Kind == CheckConstexprKind::CheckValid) 1749 return false; 1750 1751 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 1752 << isa<CXXConstructorDecl>(NewFD) 1753 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 1754 for (const auto &I : RD->vbases()) 1755 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here) 1756 << I.getSourceRange(); 1757 return false; 1758 } 1759 } 1760 1761 if (!isa<CXXConstructorDecl>(NewFD)) { 1762 // C++11 [dcl.constexpr]p3: 1763 // The definition of a constexpr function shall satisfy the following 1764 // constraints: 1765 // - it shall not be virtual; (removed in C++20) 1766 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 1767 if (Method && Method->isVirtual()) { 1768 if (getLangOpts().CPlusPlus20) { 1769 if (Kind == CheckConstexprKind::Diagnose) 1770 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual); 1771 } else { 1772 if (Kind == CheckConstexprKind::CheckValid) 1773 return false; 1774 1775 Method = Method->getCanonicalDecl(); 1776 Diag(Method->getLocation(), diag::err_constexpr_virtual); 1777 1778 // If it's not obvious why this function is virtual, find an overridden 1779 // function which uses the 'virtual' keyword. 1780 const CXXMethodDecl *WrittenVirtual = Method; 1781 while (!WrittenVirtual->isVirtualAsWritten()) 1782 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 1783 if (WrittenVirtual != Method) 1784 Diag(WrittenVirtual->getLocation(), 1785 diag::note_overridden_virtual_function); 1786 return false; 1787 } 1788 } 1789 1790 // - its return type shall be a literal type; 1791 if (!CheckConstexprReturnType(*this, NewFD, Kind)) 1792 return false; 1793 } 1794 1795 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) { 1796 // A destructor can be constexpr only if the defaulted destructor could be; 1797 // we don't need to check the members and bases if we already know they all 1798 // have constexpr destructors. 1799 if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) { 1800 if (Kind == CheckConstexprKind::CheckValid) 1801 return false; 1802 if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind)) 1803 return false; 1804 } 1805 } 1806 1807 // - each of its parameter types shall be a literal type; 1808 if (!CheckConstexprParameterTypes(*this, NewFD, Kind)) 1809 return false; 1810 1811 Stmt *Body = NewFD->getBody(); 1812 assert(Body && 1813 "CheckConstexprFunctionDefinition called on function with no body"); 1814 return CheckConstexprFunctionBody(*this, NewFD, Body, Kind); 1815 } 1816 1817 /// Check the given declaration statement is legal within a constexpr function 1818 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 1819 /// 1820 /// \return true if the body is OK (maybe only as an extension), false if we 1821 /// have diagnosed a problem. 1822 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 1823 DeclStmt *DS, SourceLocation &Cxx1yLoc, 1824 Sema::CheckConstexprKind Kind) { 1825 // C++11 [dcl.constexpr]p3 and p4: 1826 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 1827 // contain only 1828 for (const auto *DclIt : DS->decls()) { 1829 switch (DclIt->getKind()) { 1830 case Decl::StaticAssert: 1831 case Decl::Using: 1832 case Decl::UsingShadow: 1833 case Decl::UsingDirective: 1834 case Decl::UnresolvedUsingTypename: 1835 case Decl::UnresolvedUsingValue: 1836 case Decl::UsingEnum: 1837 // - static_assert-declarations 1838 // - using-declarations, 1839 // - using-directives, 1840 // - using-enum-declaration 1841 continue; 1842 1843 case Decl::Typedef: 1844 case Decl::TypeAlias: { 1845 // - typedef declarations and alias-declarations that do not define 1846 // classes or enumerations, 1847 const auto *TN = cast<TypedefNameDecl>(DclIt); 1848 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 1849 // Don't allow variably-modified types in constexpr functions. 1850 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1851 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 1852 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 1853 << TL.getSourceRange() << TL.getType() 1854 << isa<CXXConstructorDecl>(Dcl); 1855 } 1856 return false; 1857 } 1858 continue; 1859 } 1860 1861 case Decl::Enum: 1862 case Decl::CXXRecord: 1863 // C++1y allows types to be defined, not just declared. 1864 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) { 1865 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1866 SemaRef.Diag(DS->getBeginLoc(), 1867 SemaRef.getLangOpts().CPlusPlus14 1868 ? diag::warn_cxx11_compat_constexpr_type_definition 1869 : diag::ext_constexpr_type_definition) 1870 << isa<CXXConstructorDecl>(Dcl); 1871 } else if (!SemaRef.getLangOpts().CPlusPlus14) { 1872 return false; 1873 } 1874 } 1875 continue; 1876 1877 case Decl::EnumConstant: 1878 case Decl::IndirectField: 1879 case Decl::ParmVar: 1880 // These can only appear with other declarations which are banned in 1881 // C++11 and permitted in C++1y, so ignore them. 1882 continue; 1883 1884 case Decl::Var: 1885 case Decl::Decomposition: { 1886 // C++1y [dcl.constexpr]p3 allows anything except: 1887 // a definition of a variable of non-literal type or of static or 1888 // thread storage duration or [before C++2a] for which no 1889 // initialization is performed. 1890 const auto *VD = cast<VarDecl>(DclIt); 1891 if (VD->isThisDeclarationADefinition()) { 1892 if (VD->isStaticLocal()) { 1893 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1894 SemaRef.Diag(VD->getLocation(), 1895 diag::err_constexpr_local_var_static) 1896 << isa<CXXConstructorDecl>(Dcl) 1897 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 1898 } 1899 return false; 1900 } 1901 if (CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(), 1902 diag::err_constexpr_local_var_non_literal_type, 1903 isa<CXXConstructorDecl>(Dcl))) 1904 return false; 1905 if (!VD->getType()->isDependentType() && 1906 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 1907 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1908 SemaRef.Diag( 1909 VD->getLocation(), 1910 SemaRef.getLangOpts().CPlusPlus20 1911 ? diag::warn_cxx17_compat_constexpr_local_var_no_init 1912 : diag::ext_constexpr_local_var_no_init) 1913 << isa<CXXConstructorDecl>(Dcl); 1914 } else if (!SemaRef.getLangOpts().CPlusPlus20) { 1915 return false; 1916 } 1917 continue; 1918 } 1919 } 1920 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1921 SemaRef.Diag(VD->getLocation(), 1922 SemaRef.getLangOpts().CPlusPlus14 1923 ? diag::warn_cxx11_compat_constexpr_local_var 1924 : diag::ext_constexpr_local_var) 1925 << isa<CXXConstructorDecl>(Dcl); 1926 } else if (!SemaRef.getLangOpts().CPlusPlus14) { 1927 return false; 1928 } 1929 continue; 1930 } 1931 1932 case Decl::NamespaceAlias: 1933 case Decl::Function: 1934 // These are disallowed in C++11 and permitted in C++1y. Allow them 1935 // everywhere as an extension. 1936 if (!Cxx1yLoc.isValid()) 1937 Cxx1yLoc = DS->getBeginLoc(); 1938 continue; 1939 1940 default: 1941 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1942 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 1943 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 1944 } 1945 return false; 1946 } 1947 } 1948 1949 return true; 1950 } 1951 1952 /// Check that the given field is initialized within a constexpr constructor. 1953 /// 1954 /// \param Dcl The constexpr constructor being checked. 1955 /// \param Field The field being checked. This may be a member of an anonymous 1956 /// struct or union nested within the class being checked. 1957 /// \param Inits All declarations, including anonymous struct/union members and 1958 /// indirect members, for which any initialization was provided. 1959 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach 1960 /// multiple notes for different members to the same error. 1961 /// \param Kind Whether we're diagnosing a constructor as written or determining 1962 /// whether the formal requirements are satisfied. 1963 /// \return \c false if we're checking for validity and the constructor does 1964 /// not satisfy the requirements on a constexpr constructor. 1965 static bool CheckConstexprCtorInitializer(Sema &SemaRef, 1966 const FunctionDecl *Dcl, 1967 FieldDecl *Field, 1968 llvm::SmallSet<Decl*, 16> &Inits, 1969 bool &Diagnosed, 1970 Sema::CheckConstexprKind Kind) { 1971 // In C++20 onwards, there's nothing to check for validity. 1972 if (Kind == Sema::CheckConstexprKind::CheckValid && 1973 SemaRef.getLangOpts().CPlusPlus20) 1974 return true; 1975 1976 if (Field->isInvalidDecl()) 1977 return true; 1978 1979 if (Field->isUnnamedBitfield()) 1980 return true; 1981 1982 // Anonymous unions with no variant members and empty anonymous structs do not 1983 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 1984 // indirect fields don't need initializing. 1985 if (Field->isAnonymousStructOrUnion() && 1986 (Field->getType()->isUnionType() 1987 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 1988 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 1989 return true; 1990 1991 if (!Inits.count(Field)) { 1992 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1993 if (!Diagnosed) { 1994 SemaRef.Diag(Dcl->getLocation(), 1995 SemaRef.getLangOpts().CPlusPlus20 1996 ? diag::warn_cxx17_compat_constexpr_ctor_missing_init 1997 : diag::ext_constexpr_ctor_missing_init); 1998 Diagnosed = true; 1999 } 2000 SemaRef.Diag(Field->getLocation(), 2001 diag::note_constexpr_ctor_missing_init); 2002 } else if (!SemaRef.getLangOpts().CPlusPlus20) { 2003 return false; 2004 } 2005 } else if (Field->isAnonymousStructOrUnion()) { 2006 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 2007 for (auto *I : RD->fields()) 2008 // If an anonymous union contains an anonymous struct of which any member 2009 // is initialized, all members must be initialized. 2010 if (!RD->isUnion() || Inits.count(I)) 2011 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, 2012 Kind)) 2013 return false; 2014 } 2015 return true; 2016 } 2017 2018 /// Check the provided statement is allowed in a constexpr function 2019 /// definition. 2020 static bool 2021 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 2022 SmallVectorImpl<SourceLocation> &ReturnStmts, 2023 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc, 2024 Sema::CheckConstexprKind Kind) { 2025 // - its function-body shall be [...] a compound-statement that contains only 2026 switch (S->getStmtClass()) { 2027 case Stmt::NullStmtClass: 2028 // - null statements, 2029 return true; 2030 2031 case Stmt::DeclStmtClass: 2032 // - static_assert-declarations 2033 // - using-declarations, 2034 // - using-directives, 2035 // - typedef declarations and alias-declarations that do not define 2036 // classes or enumerations, 2037 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind)) 2038 return false; 2039 return true; 2040 2041 case Stmt::ReturnStmtClass: 2042 // - and exactly one return statement; 2043 if (isa<CXXConstructorDecl>(Dcl)) { 2044 // C++1y allows return statements in constexpr constructors. 2045 if (!Cxx1yLoc.isValid()) 2046 Cxx1yLoc = S->getBeginLoc(); 2047 return true; 2048 } 2049 2050 ReturnStmts.push_back(S->getBeginLoc()); 2051 return true; 2052 2053 case Stmt::AttributedStmtClass: 2054 // Attributes on a statement don't affect its formal kind and hence don't 2055 // affect its validity in a constexpr function. 2056 return CheckConstexprFunctionStmt(SemaRef, Dcl, 2057 cast<AttributedStmt>(S)->getSubStmt(), 2058 ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind); 2059 2060 case Stmt::CompoundStmtClass: { 2061 // C++1y allows compound-statements. 2062 if (!Cxx1yLoc.isValid()) 2063 Cxx1yLoc = S->getBeginLoc(); 2064 2065 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 2066 for (auto *BodyIt : CompStmt->body()) { 2067 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 2068 Cxx1yLoc, Cxx2aLoc, Kind)) 2069 return false; 2070 } 2071 return true; 2072 } 2073 2074 case Stmt::IfStmtClass: { 2075 // C++1y allows if-statements. 2076 if (!Cxx1yLoc.isValid()) 2077 Cxx1yLoc = S->getBeginLoc(); 2078 2079 IfStmt *If = cast<IfStmt>(S); 2080 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 2081 Cxx1yLoc, Cxx2aLoc, Kind)) 2082 return false; 2083 if (If->getElse() && 2084 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 2085 Cxx1yLoc, Cxx2aLoc, Kind)) 2086 return false; 2087 return true; 2088 } 2089 2090 case Stmt::WhileStmtClass: 2091 case Stmt::DoStmtClass: 2092 case Stmt::ForStmtClass: 2093 case Stmt::CXXForRangeStmtClass: 2094 case Stmt::ContinueStmtClass: 2095 // C++1y allows all of these. We don't allow them as extensions in C++11, 2096 // because they don't make sense without variable mutation. 2097 if (!SemaRef.getLangOpts().CPlusPlus14) 2098 break; 2099 if (!Cxx1yLoc.isValid()) 2100 Cxx1yLoc = S->getBeginLoc(); 2101 for (Stmt *SubStmt : S->children()) 2102 if (SubStmt && 2103 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2104 Cxx1yLoc, Cxx2aLoc, Kind)) 2105 return false; 2106 return true; 2107 2108 case Stmt::SwitchStmtClass: 2109 case Stmt::CaseStmtClass: 2110 case Stmt::DefaultStmtClass: 2111 case Stmt::BreakStmtClass: 2112 // C++1y allows switch-statements, and since they don't need variable 2113 // mutation, we can reasonably allow them in C++11 as an extension. 2114 if (!Cxx1yLoc.isValid()) 2115 Cxx1yLoc = S->getBeginLoc(); 2116 for (Stmt *SubStmt : S->children()) 2117 if (SubStmt && 2118 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2119 Cxx1yLoc, Cxx2aLoc, Kind)) 2120 return false; 2121 return true; 2122 2123 case Stmt::GCCAsmStmtClass: 2124 case Stmt::MSAsmStmtClass: 2125 // C++2a allows inline assembly statements. 2126 case Stmt::CXXTryStmtClass: 2127 if (Cxx2aLoc.isInvalid()) 2128 Cxx2aLoc = S->getBeginLoc(); 2129 for (Stmt *SubStmt : S->children()) { 2130 if (SubStmt && 2131 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2132 Cxx1yLoc, Cxx2aLoc, Kind)) 2133 return false; 2134 } 2135 return true; 2136 2137 case Stmt::CXXCatchStmtClass: 2138 // Do not bother checking the language mode (already covered by the 2139 // try block check). 2140 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, 2141 cast<CXXCatchStmt>(S)->getHandlerBlock(), 2142 ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind)) 2143 return false; 2144 return true; 2145 2146 default: 2147 if (!isa<Expr>(S)) 2148 break; 2149 2150 // C++1y allows expression-statements. 2151 if (!Cxx1yLoc.isValid()) 2152 Cxx1yLoc = S->getBeginLoc(); 2153 return true; 2154 } 2155 2156 if (Kind == Sema::CheckConstexprKind::Diagnose) { 2157 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 2158 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 2159 } 2160 return false; 2161 } 2162 2163 /// Check the body for the given constexpr function declaration only contains 2164 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 2165 /// 2166 /// \return true if the body is OK, false if we have found or diagnosed a 2167 /// problem. 2168 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, 2169 Stmt *Body, 2170 Sema::CheckConstexprKind Kind) { 2171 SmallVector<SourceLocation, 4> ReturnStmts; 2172 2173 if (isa<CXXTryStmt>(Body)) { 2174 // C++11 [dcl.constexpr]p3: 2175 // The definition of a constexpr function shall satisfy the following 2176 // constraints: [...] 2177 // - its function-body shall be = delete, = default, or a 2178 // compound-statement 2179 // 2180 // C++11 [dcl.constexpr]p4: 2181 // In the definition of a constexpr constructor, [...] 2182 // - its function-body shall not be a function-try-block; 2183 // 2184 // This restriction is lifted in C++2a, as long as inner statements also 2185 // apply the general constexpr rules. 2186 switch (Kind) { 2187 case Sema::CheckConstexprKind::CheckValid: 2188 if (!SemaRef.getLangOpts().CPlusPlus20) 2189 return false; 2190 break; 2191 2192 case Sema::CheckConstexprKind::Diagnose: 2193 SemaRef.Diag(Body->getBeginLoc(), 2194 !SemaRef.getLangOpts().CPlusPlus20 2195 ? diag::ext_constexpr_function_try_block_cxx20 2196 : diag::warn_cxx17_compat_constexpr_function_try_block) 2197 << isa<CXXConstructorDecl>(Dcl); 2198 break; 2199 } 2200 } 2201 2202 // - its function-body shall be [...] a compound-statement that contains only 2203 // [... list of cases ...] 2204 // 2205 // Note that walking the children here is enough to properly check for 2206 // CompoundStmt and CXXTryStmt body. 2207 SourceLocation Cxx1yLoc, Cxx2aLoc; 2208 for (Stmt *SubStmt : Body->children()) { 2209 if (SubStmt && 2210 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2211 Cxx1yLoc, Cxx2aLoc, Kind)) 2212 return false; 2213 } 2214 2215 if (Kind == Sema::CheckConstexprKind::CheckValid) { 2216 // If this is only valid as an extension, report that we don't satisfy the 2217 // constraints of the current language. 2218 if ((Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) || 2219 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17)) 2220 return false; 2221 } else if (Cxx2aLoc.isValid()) { 2222 SemaRef.Diag(Cxx2aLoc, 2223 SemaRef.getLangOpts().CPlusPlus20 2224 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt 2225 : diag::ext_constexpr_body_invalid_stmt_cxx20) 2226 << isa<CXXConstructorDecl>(Dcl); 2227 } else if (Cxx1yLoc.isValid()) { 2228 SemaRef.Diag(Cxx1yLoc, 2229 SemaRef.getLangOpts().CPlusPlus14 2230 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 2231 : diag::ext_constexpr_body_invalid_stmt) 2232 << isa<CXXConstructorDecl>(Dcl); 2233 } 2234 2235 if (const CXXConstructorDecl *Constructor 2236 = dyn_cast<CXXConstructorDecl>(Dcl)) { 2237 const CXXRecordDecl *RD = Constructor->getParent(); 2238 // DR1359: 2239 // - every non-variant non-static data member and base class sub-object 2240 // shall be initialized; 2241 // DR1460: 2242 // - if the class is a union having variant members, exactly one of them 2243 // shall be initialized; 2244 if (RD->isUnion()) { 2245 if (Constructor->getNumCtorInitializers() == 0 && 2246 RD->hasVariantMembers()) { 2247 if (Kind == Sema::CheckConstexprKind::Diagnose) { 2248 SemaRef.Diag( 2249 Dcl->getLocation(), 2250 SemaRef.getLangOpts().CPlusPlus20 2251 ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init 2252 : diag::ext_constexpr_union_ctor_no_init); 2253 } else if (!SemaRef.getLangOpts().CPlusPlus20) { 2254 return false; 2255 } 2256 } 2257 } else if (!Constructor->isDependentContext() && 2258 !Constructor->isDelegatingConstructor()) { 2259 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 2260 2261 // Skip detailed checking if we have enough initializers, and we would 2262 // allow at most one initializer per member. 2263 bool AnyAnonStructUnionMembers = false; 2264 unsigned Fields = 0; 2265 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 2266 E = RD->field_end(); I != E; ++I, ++Fields) { 2267 if (I->isAnonymousStructOrUnion()) { 2268 AnyAnonStructUnionMembers = true; 2269 break; 2270 } 2271 } 2272 // DR1460: 2273 // - if the class is a union-like class, but is not a union, for each of 2274 // its anonymous union members having variant members, exactly one of 2275 // them shall be initialized; 2276 if (AnyAnonStructUnionMembers || 2277 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 2278 // Check initialization of non-static data members. Base classes are 2279 // always initialized so do not need to be checked. Dependent bases 2280 // might not have initializers in the member initializer list. 2281 llvm::SmallSet<Decl*, 16> Inits; 2282 for (const auto *I: Constructor->inits()) { 2283 if (FieldDecl *FD = I->getMember()) 2284 Inits.insert(FD); 2285 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 2286 Inits.insert(ID->chain_begin(), ID->chain_end()); 2287 } 2288 2289 bool Diagnosed = false; 2290 for (auto *I : RD->fields()) 2291 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, 2292 Kind)) 2293 return false; 2294 } 2295 } 2296 } else { 2297 if (ReturnStmts.empty()) { 2298 // C++1y doesn't require constexpr functions to contain a 'return' 2299 // statement. We still do, unless the return type might be void, because 2300 // otherwise if there's no return statement, the function cannot 2301 // be used in a core constant expression. 2302 bool OK = SemaRef.getLangOpts().CPlusPlus14 && 2303 (Dcl->getReturnType()->isVoidType() || 2304 Dcl->getReturnType()->isDependentType()); 2305 switch (Kind) { 2306 case Sema::CheckConstexprKind::Diagnose: 2307 SemaRef.Diag(Dcl->getLocation(), 2308 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 2309 : diag::err_constexpr_body_no_return) 2310 << Dcl->isConsteval(); 2311 if (!OK) 2312 return false; 2313 break; 2314 2315 case Sema::CheckConstexprKind::CheckValid: 2316 // The formal requirements don't include this rule in C++14, even 2317 // though the "must be able to produce a constant expression" rules 2318 // still imply it in some cases. 2319 if (!SemaRef.getLangOpts().CPlusPlus14) 2320 return false; 2321 break; 2322 } 2323 } else if (ReturnStmts.size() > 1) { 2324 switch (Kind) { 2325 case Sema::CheckConstexprKind::Diagnose: 2326 SemaRef.Diag( 2327 ReturnStmts.back(), 2328 SemaRef.getLangOpts().CPlusPlus14 2329 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 2330 : diag::ext_constexpr_body_multiple_return); 2331 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 2332 SemaRef.Diag(ReturnStmts[I], 2333 diag::note_constexpr_body_previous_return); 2334 break; 2335 2336 case Sema::CheckConstexprKind::CheckValid: 2337 if (!SemaRef.getLangOpts().CPlusPlus14) 2338 return false; 2339 break; 2340 } 2341 } 2342 } 2343 2344 // C++11 [dcl.constexpr]p5: 2345 // if no function argument values exist such that the function invocation 2346 // substitution would produce a constant expression, the program is 2347 // ill-formed; no diagnostic required. 2348 // C++11 [dcl.constexpr]p3: 2349 // - every constructor call and implicit conversion used in initializing the 2350 // return value shall be one of those allowed in a constant expression. 2351 // C++11 [dcl.constexpr]p4: 2352 // - every constructor involved in initializing non-static data members and 2353 // base class sub-objects shall be a constexpr constructor. 2354 // 2355 // Note that this rule is distinct from the "requirements for a constexpr 2356 // function", so is not checked in CheckValid mode. 2357 SmallVector<PartialDiagnosticAt, 8> Diags; 2358 if (Kind == Sema::CheckConstexprKind::Diagnose && 2359 !Expr::isPotentialConstantExpr(Dcl, Diags)) { 2360 SemaRef.Diag(Dcl->getLocation(), 2361 diag::ext_constexpr_function_never_constant_expr) 2362 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 2363 for (size_t I = 0, N = Diags.size(); I != N; ++I) 2364 SemaRef.Diag(Diags[I].first, Diags[I].second); 2365 // Don't return false here: we allow this for compatibility in 2366 // system headers. 2367 } 2368 2369 return true; 2370 } 2371 2372 /// Get the class that is directly named by the current context. This is the 2373 /// class for which an unqualified-id in this scope could name a constructor 2374 /// or destructor. 2375 /// 2376 /// If the scope specifier denotes a class, this will be that class. 2377 /// If the scope specifier is empty, this will be the class whose 2378 /// member-specification we are currently within. Otherwise, there 2379 /// is no such class. 2380 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) { 2381 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2382 2383 if (SS && SS->isInvalid()) 2384 return nullptr; 2385 2386 if (SS && SS->isNotEmpty()) { 2387 DeclContext *DC = computeDeclContext(*SS, true); 2388 return dyn_cast_or_null<CXXRecordDecl>(DC); 2389 } 2390 2391 return dyn_cast_or_null<CXXRecordDecl>(CurContext); 2392 } 2393 2394 /// isCurrentClassName - Determine whether the identifier II is the 2395 /// name of the class type currently being defined. In the case of 2396 /// nested classes, this will only return true if II is the name of 2397 /// the innermost class. 2398 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S, 2399 const CXXScopeSpec *SS) { 2400 CXXRecordDecl *CurDecl = getCurrentClass(S, SS); 2401 return CurDecl && &II == CurDecl->getIdentifier(); 2402 } 2403 2404 /// Determine whether the identifier II is a typo for the name of 2405 /// the class type currently being defined. If so, update it to the identifier 2406 /// that should have been used. 2407 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 2408 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2409 2410 if (!getLangOpts().SpellChecking) 2411 return false; 2412 2413 CXXRecordDecl *CurDecl; 2414 if (SS && SS->isSet() && !SS->isInvalid()) { 2415 DeclContext *DC = computeDeclContext(*SS, true); 2416 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 2417 } else 2418 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 2419 2420 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 2421 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 2422 < II->getLength()) { 2423 II = CurDecl->getIdentifier(); 2424 return true; 2425 } 2426 2427 return false; 2428 } 2429 2430 /// Determine whether the given class is a base class of the given 2431 /// class, including looking at dependent bases. 2432 static bool findCircularInheritance(const CXXRecordDecl *Class, 2433 const CXXRecordDecl *Current) { 2434 SmallVector<const CXXRecordDecl*, 8> Queue; 2435 2436 Class = Class->getCanonicalDecl(); 2437 while (true) { 2438 for (const auto &I : Current->bases()) { 2439 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 2440 if (!Base) 2441 continue; 2442 2443 Base = Base->getDefinition(); 2444 if (!Base) 2445 continue; 2446 2447 if (Base->getCanonicalDecl() == Class) 2448 return true; 2449 2450 Queue.push_back(Base); 2451 } 2452 2453 if (Queue.empty()) 2454 return false; 2455 2456 Current = Queue.pop_back_val(); 2457 } 2458 2459 return false; 2460 } 2461 2462 /// Check the validity of a C++ base class specifier. 2463 /// 2464 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 2465 /// and returns NULL otherwise. 2466 CXXBaseSpecifier * 2467 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 2468 SourceRange SpecifierRange, 2469 bool Virtual, AccessSpecifier Access, 2470 TypeSourceInfo *TInfo, 2471 SourceLocation EllipsisLoc) { 2472 QualType BaseType = TInfo->getType(); 2473 if (BaseType->containsErrors()) { 2474 // Already emitted a diagnostic when parsing the error type. 2475 return nullptr; 2476 } 2477 // C++ [class.union]p1: 2478 // A union shall not have base classes. 2479 if (Class->isUnion()) { 2480 Diag(Class->getLocation(), diag::err_base_clause_on_union) 2481 << SpecifierRange; 2482 return nullptr; 2483 } 2484 2485 if (EllipsisLoc.isValid() && 2486 !TInfo->getType()->containsUnexpandedParameterPack()) { 2487 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2488 << TInfo->getTypeLoc().getSourceRange(); 2489 EllipsisLoc = SourceLocation(); 2490 } 2491 2492 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 2493 2494 if (BaseType->isDependentType()) { 2495 // Make sure that we don't have circular inheritance among our dependent 2496 // bases. For non-dependent bases, the check for completeness below handles 2497 // this. 2498 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 2499 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 2500 ((BaseDecl = BaseDecl->getDefinition()) && 2501 findCircularInheritance(Class, BaseDecl))) { 2502 Diag(BaseLoc, diag::err_circular_inheritance) 2503 << BaseType << Context.getTypeDeclType(Class); 2504 2505 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 2506 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 2507 << BaseType; 2508 2509 return nullptr; 2510 } 2511 } 2512 2513 // Make sure that we don't make an ill-formed AST where the type of the 2514 // Class is non-dependent and its attached base class specifier is an 2515 // dependent type, which violates invariants in many clang code paths (e.g. 2516 // constexpr evaluator). If this case happens (in errory-recovery mode), we 2517 // explicitly mark the Class decl invalid. The diagnostic was already 2518 // emitted. 2519 if (!Class->getTypeForDecl()->isDependentType()) 2520 Class->setInvalidDecl(); 2521 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2522 Class->getTagKind() == TTK_Class, 2523 Access, TInfo, EllipsisLoc); 2524 } 2525 2526 // Base specifiers must be record types. 2527 if (!BaseType->isRecordType()) { 2528 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 2529 return nullptr; 2530 } 2531 2532 // C++ [class.union]p1: 2533 // A union shall not be used as a base class. 2534 if (BaseType->isUnionType()) { 2535 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 2536 return nullptr; 2537 } 2538 2539 // For the MS ABI, propagate DLL attributes to base class templates. 2540 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 2541 if (Attr *ClassAttr = getDLLAttr(Class)) { 2542 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 2543 BaseType->getAsCXXRecordDecl())) { 2544 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate, 2545 BaseLoc); 2546 } 2547 } 2548 } 2549 2550 // C++ [class.derived]p2: 2551 // The class-name in a base-specifier shall not be an incompletely 2552 // defined class. 2553 if (RequireCompleteType(BaseLoc, BaseType, 2554 diag::err_incomplete_base_class, SpecifierRange)) { 2555 Class->setInvalidDecl(); 2556 return nullptr; 2557 } 2558 2559 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 2560 RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl(); 2561 assert(BaseDecl && "Record type has no declaration"); 2562 BaseDecl = BaseDecl->getDefinition(); 2563 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 2564 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 2565 assert(CXXBaseDecl && "Base type is not a C++ type"); 2566 2567 // Microsoft docs say: 2568 // "If a base-class has a code_seg attribute, derived classes must have the 2569 // same attribute." 2570 const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>(); 2571 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>(); 2572 if ((DerivedCSA || BaseCSA) && 2573 (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) { 2574 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base); 2575 Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here) 2576 << CXXBaseDecl; 2577 return nullptr; 2578 } 2579 2580 // A class which contains a flexible array member is not suitable for use as a 2581 // base class: 2582 // - If the layout determines that a base comes before another base, 2583 // the flexible array member would index into the subsequent base. 2584 // - If the layout determines that base comes before the derived class, 2585 // the flexible array member would index into the derived class. 2586 if (CXXBaseDecl->hasFlexibleArrayMember()) { 2587 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 2588 << CXXBaseDecl->getDeclName(); 2589 return nullptr; 2590 } 2591 2592 // C++ [class]p3: 2593 // If a class is marked final and it appears as a base-type-specifier in 2594 // base-clause, the program is ill-formed. 2595 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 2596 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 2597 << CXXBaseDecl->getDeclName() 2598 << FA->isSpelledAsSealed(); 2599 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 2600 << CXXBaseDecl->getDeclName() << FA->getRange(); 2601 return nullptr; 2602 } 2603 2604 if (BaseDecl->isInvalidDecl()) 2605 Class->setInvalidDecl(); 2606 2607 // Create the base specifier. 2608 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2609 Class->getTagKind() == TTK_Class, 2610 Access, TInfo, EllipsisLoc); 2611 } 2612 2613 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 2614 /// one entry in the base class list of a class specifier, for 2615 /// example: 2616 /// class foo : public bar, virtual private baz { 2617 /// 'public bar' and 'virtual private baz' are each base-specifiers. 2618 BaseResult 2619 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 2620 ParsedAttributes &Attributes, 2621 bool Virtual, AccessSpecifier Access, 2622 ParsedType basetype, SourceLocation BaseLoc, 2623 SourceLocation EllipsisLoc) { 2624 if (!classdecl) 2625 return true; 2626 2627 AdjustDeclIfTemplate(classdecl); 2628 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 2629 if (!Class) 2630 return true; 2631 2632 // We haven't yet attached the base specifiers. 2633 Class->setIsParsingBaseSpecifiers(); 2634 2635 // We do not support any C++11 attributes on base-specifiers yet. 2636 // Diagnose any attributes we see. 2637 for (const ParsedAttr &AL : Attributes) { 2638 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute) 2639 continue; 2640 Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute 2641 ? (unsigned)diag::warn_unknown_attribute_ignored 2642 : (unsigned)diag::err_base_specifier_attribute) 2643 << AL << AL.getRange(); 2644 } 2645 2646 TypeSourceInfo *TInfo = nullptr; 2647 GetTypeFromParser(basetype, &TInfo); 2648 2649 if (EllipsisLoc.isInvalid() && 2650 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 2651 UPPC_BaseType)) 2652 return true; 2653 2654 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 2655 Virtual, Access, TInfo, 2656 EllipsisLoc)) 2657 return BaseSpec; 2658 else 2659 Class->setInvalidDecl(); 2660 2661 return true; 2662 } 2663 2664 /// Use small set to collect indirect bases. As this is only used 2665 /// locally, there's no need to abstract the small size parameter. 2666 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet; 2667 2668 /// Recursively add the bases of Type. Don't add Type itself. 2669 static void 2670 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, 2671 const QualType &Type) 2672 { 2673 // Even though the incoming type is a base, it might not be 2674 // a class -- it could be a template parm, for instance. 2675 if (auto Rec = Type->getAs<RecordType>()) { 2676 auto Decl = Rec->getAsCXXRecordDecl(); 2677 2678 // Iterate over its bases. 2679 for (const auto &BaseSpec : Decl->bases()) { 2680 QualType Base = Context.getCanonicalType(BaseSpec.getType()) 2681 .getUnqualifiedType(); 2682 if (Set.insert(Base).second) 2683 // If we've not already seen it, recurse. 2684 NoteIndirectBases(Context, Set, Base); 2685 } 2686 } 2687 } 2688 2689 /// Performs the actual work of attaching the given base class 2690 /// specifiers to a C++ class. 2691 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, 2692 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2693 if (Bases.empty()) 2694 return false; 2695 2696 // Used to keep track of which base types we have already seen, so 2697 // that we can properly diagnose redundant direct base types. Note 2698 // that the key is always the unqualified canonical type of the base 2699 // class. 2700 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 2701 2702 // Used to track indirect bases so we can see if a direct base is 2703 // ambiguous. 2704 IndirectBaseSet IndirectBaseTypes; 2705 2706 // Copy non-redundant base specifiers into permanent storage. 2707 unsigned NumGoodBases = 0; 2708 bool Invalid = false; 2709 for (unsigned idx = 0; idx < Bases.size(); ++idx) { 2710 QualType NewBaseType 2711 = Context.getCanonicalType(Bases[idx]->getType()); 2712 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 2713 2714 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 2715 if (KnownBase) { 2716 // C++ [class.mi]p3: 2717 // A class shall not be specified as a direct base class of a 2718 // derived class more than once. 2719 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class) 2720 << KnownBase->getType() << Bases[idx]->getSourceRange(); 2721 2722 // Delete the duplicate base class specifier; we're going to 2723 // overwrite its pointer later. 2724 Context.Deallocate(Bases[idx]); 2725 2726 Invalid = true; 2727 } else { 2728 // Okay, add this new base class. 2729 KnownBase = Bases[idx]; 2730 Bases[NumGoodBases++] = Bases[idx]; 2731 2732 // Note this base's direct & indirect bases, if there could be ambiguity. 2733 if (Bases.size() > 1) 2734 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType); 2735 2736 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 2737 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 2738 if (Class->isInterface() && 2739 (!RD->isInterfaceLike() || 2740 KnownBase->getAccessSpecifier() != AS_public)) { 2741 // The Microsoft extension __interface does not permit bases that 2742 // are not themselves public interfaces. 2743 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface) 2744 << getRecordDiagFromTagKind(RD->getTagKind()) << RD 2745 << RD->getSourceRange(); 2746 Invalid = true; 2747 } 2748 if (RD->hasAttr<WeakAttr>()) 2749 Class->addAttr(WeakAttr::CreateImplicit(Context)); 2750 } 2751 } 2752 } 2753 2754 // Attach the remaining base class specifiers to the derived class. 2755 Class->setBases(Bases.data(), NumGoodBases); 2756 2757 // Check that the only base classes that are duplicate are virtual. 2758 for (unsigned idx = 0; idx < NumGoodBases; ++idx) { 2759 // Check whether this direct base is inaccessible due to ambiguity. 2760 QualType BaseType = Bases[idx]->getType(); 2761 2762 // Skip all dependent types in templates being used as base specifiers. 2763 // Checks below assume that the base specifier is a CXXRecord. 2764 if (BaseType->isDependentType()) 2765 continue; 2766 2767 CanQualType CanonicalBase = Context.getCanonicalType(BaseType) 2768 .getUnqualifiedType(); 2769 2770 if (IndirectBaseTypes.count(CanonicalBase)) { 2771 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2772 /*DetectVirtual=*/true); 2773 bool found 2774 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); 2775 assert(found); 2776 (void)found; 2777 2778 if (Paths.isAmbiguous(CanonicalBase)) 2779 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class) 2780 << BaseType << getAmbiguousPathsDisplayString(Paths) 2781 << Bases[idx]->getSourceRange(); 2782 else 2783 assert(Bases[idx]->isVirtual()); 2784 } 2785 2786 // Delete the base class specifier, since its data has been copied 2787 // into the CXXRecordDecl. 2788 Context.Deallocate(Bases[idx]); 2789 } 2790 2791 return Invalid; 2792 } 2793 2794 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 2795 /// class, after checking whether there are any duplicate base 2796 /// classes. 2797 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, 2798 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2799 if (!ClassDecl || Bases.empty()) 2800 return; 2801 2802 AdjustDeclIfTemplate(ClassDecl); 2803 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases); 2804 } 2805 2806 /// Determine whether the type \p Derived is a C++ class that is 2807 /// derived from the type \p Base. 2808 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) { 2809 if (!getLangOpts().CPlusPlus) 2810 return false; 2811 2812 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2813 if (!DerivedRD) 2814 return false; 2815 2816 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2817 if (!BaseRD) 2818 return false; 2819 2820 // If either the base or the derived type is invalid, don't try to 2821 // check whether one is derived from the other. 2822 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 2823 return false; 2824 2825 // FIXME: In a modules build, do we need the entire path to be visible for us 2826 // to be able to use the inheritance relationship? 2827 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2828 return false; 2829 2830 return DerivedRD->isDerivedFrom(BaseRD); 2831 } 2832 2833 /// Determine whether the type \p Derived is a C++ class that is 2834 /// derived from the type \p Base. 2835 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, 2836 CXXBasePaths &Paths) { 2837 if (!getLangOpts().CPlusPlus) 2838 return false; 2839 2840 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2841 if (!DerivedRD) 2842 return false; 2843 2844 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2845 if (!BaseRD) 2846 return false; 2847 2848 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2849 return false; 2850 2851 return DerivedRD->isDerivedFrom(BaseRD, Paths); 2852 } 2853 2854 static void BuildBasePathArray(const CXXBasePath &Path, 2855 CXXCastPath &BasePathArray) { 2856 // We first go backward and check if we have a virtual base. 2857 // FIXME: It would be better if CXXBasePath had the base specifier for 2858 // the nearest virtual base. 2859 unsigned Start = 0; 2860 for (unsigned I = Path.size(); I != 0; --I) { 2861 if (Path[I - 1].Base->isVirtual()) { 2862 Start = I - 1; 2863 break; 2864 } 2865 } 2866 2867 // Now add all bases. 2868 for (unsigned I = Start, E = Path.size(); I != E; ++I) 2869 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 2870 } 2871 2872 2873 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 2874 CXXCastPath &BasePathArray) { 2875 assert(BasePathArray.empty() && "Base path array must be empty!"); 2876 assert(Paths.isRecordingPaths() && "Must record paths!"); 2877 return ::BuildBasePathArray(Paths.front(), BasePathArray); 2878 } 2879 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 2880 /// conversion (where Derived and Base are class types) is 2881 /// well-formed, meaning that the conversion is unambiguous (and 2882 /// that all of the base classes are accessible). Returns true 2883 /// and emits a diagnostic if the code is ill-formed, returns false 2884 /// otherwise. Loc is the location where this routine should point to 2885 /// if there is an error, and Range is the source range to highlight 2886 /// if there is an error. 2887 /// 2888 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the 2889 /// diagnostic for the respective type of error will be suppressed, but the 2890 /// check for ill-formed code will still be performed. 2891 bool 2892 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2893 unsigned InaccessibleBaseID, 2894 unsigned AmbiguousBaseConvID, 2895 SourceLocation Loc, SourceRange Range, 2896 DeclarationName Name, 2897 CXXCastPath *BasePath, 2898 bool IgnoreAccess) { 2899 // First, determine whether the path from Derived to Base is 2900 // ambiguous. This is slightly more expensive than checking whether 2901 // the Derived to Base conversion exists, because here we need to 2902 // explore multiple paths to determine if there is an ambiguity. 2903 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2904 /*DetectVirtual=*/false); 2905 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2906 if (!DerivationOkay) 2907 return true; 2908 2909 const CXXBasePath *Path = nullptr; 2910 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) 2911 Path = &Paths.front(); 2912 2913 // For MSVC compatibility, check if Derived directly inherits from Base. Clang 2914 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the 2915 // user to access such bases. 2916 if (!Path && getLangOpts().MSVCCompat) { 2917 for (const CXXBasePath &PossiblePath : Paths) { 2918 if (PossiblePath.size() == 1) { 2919 Path = &PossiblePath; 2920 if (AmbiguousBaseConvID) 2921 Diag(Loc, diag::ext_ms_ambiguous_direct_base) 2922 << Base << Derived << Range; 2923 break; 2924 } 2925 } 2926 } 2927 2928 if (Path) { 2929 if (!IgnoreAccess) { 2930 // Check that the base class can be accessed. 2931 switch ( 2932 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) { 2933 case AR_inaccessible: 2934 return true; 2935 case AR_accessible: 2936 case AR_dependent: 2937 case AR_delayed: 2938 break; 2939 } 2940 } 2941 2942 // Build a base path if necessary. 2943 if (BasePath) 2944 ::BuildBasePathArray(*Path, *BasePath); 2945 return false; 2946 } 2947 2948 if (AmbiguousBaseConvID) { 2949 // We know that the derived-to-base conversion is ambiguous, and 2950 // we're going to produce a diagnostic. Perform the derived-to-base 2951 // search just one more time to compute all of the possible paths so 2952 // that we can print them out. This is more expensive than any of 2953 // the previous derived-to-base checks we've done, but at this point 2954 // performance isn't as much of an issue. 2955 Paths.clear(); 2956 Paths.setRecordingPaths(true); 2957 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2958 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 2959 (void)StillOkay; 2960 2961 // Build up a textual representation of the ambiguous paths, e.g., 2962 // D -> B -> A, that will be used to illustrate the ambiguous 2963 // conversions in the diagnostic. We only print one of the paths 2964 // to each base class subobject. 2965 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2966 2967 Diag(Loc, AmbiguousBaseConvID) 2968 << Derived << Base << PathDisplayStr << Range << Name; 2969 } 2970 return true; 2971 } 2972 2973 bool 2974 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2975 SourceLocation Loc, SourceRange Range, 2976 CXXCastPath *BasePath, 2977 bool IgnoreAccess) { 2978 return CheckDerivedToBaseConversion( 2979 Derived, Base, diag::err_upcast_to_inaccessible_base, 2980 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(), 2981 BasePath, IgnoreAccess); 2982 } 2983 2984 2985 /// Builds a string representing ambiguous paths from a 2986 /// specific derived class to different subobjects of the same base 2987 /// class. 2988 /// 2989 /// This function builds a string that can be used in error messages 2990 /// to show the different paths that one can take through the 2991 /// inheritance hierarchy to go from the derived class to different 2992 /// subobjects of a base class. The result looks something like this: 2993 /// @code 2994 /// struct D -> struct B -> struct A 2995 /// struct D -> struct C -> struct A 2996 /// @endcode 2997 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 2998 std::string PathDisplayStr; 2999 std::set<unsigned> DisplayedPaths; 3000 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 3001 Path != Paths.end(); ++Path) { 3002 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 3003 // We haven't displayed a path to this particular base 3004 // class subobject yet. 3005 PathDisplayStr += "\n "; 3006 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 3007 for (CXXBasePath::const_iterator Element = Path->begin(); 3008 Element != Path->end(); ++Element) 3009 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 3010 } 3011 } 3012 3013 return PathDisplayStr; 3014 } 3015 3016 //===----------------------------------------------------------------------===// 3017 // C++ class member Handling 3018 //===----------------------------------------------------------------------===// 3019 3020 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 3021 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, 3022 SourceLocation ColonLoc, 3023 const ParsedAttributesView &Attrs) { 3024 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 3025 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 3026 ASLoc, ColonLoc); 3027 CurContext->addHiddenDecl(ASDecl); 3028 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 3029 } 3030 3031 /// CheckOverrideControl - Check C++11 override control semantics. 3032 void Sema::CheckOverrideControl(NamedDecl *D) { 3033 if (D->isInvalidDecl()) 3034 return; 3035 3036 // We only care about "override" and "final" declarations. 3037 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 3038 return; 3039 3040 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 3041 3042 // We can't check dependent instance methods. 3043 if (MD && MD->isInstance() && 3044 (MD->getParent()->hasAnyDependentBases() || 3045 MD->getType()->isDependentType())) 3046 return; 3047 3048 if (MD && !MD->isVirtual()) { 3049 // If we have a non-virtual method, check if if hides a virtual method. 3050 // (In that case, it's most likely the method has the wrong type.) 3051 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 3052 FindHiddenVirtualMethods(MD, OverloadedMethods); 3053 3054 if (!OverloadedMethods.empty()) { 3055 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 3056 Diag(OA->getLocation(), 3057 diag::override_keyword_hides_virtual_member_function) 3058 << "override" << (OverloadedMethods.size() > 1); 3059 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 3060 Diag(FA->getLocation(), 3061 diag::override_keyword_hides_virtual_member_function) 3062 << (FA->isSpelledAsSealed() ? "sealed" : "final") 3063 << (OverloadedMethods.size() > 1); 3064 } 3065 NoteHiddenVirtualMethods(MD, OverloadedMethods); 3066 MD->setInvalidDecl(); 3067 return; 3068 } 3069 // Fall through into the general case diagnostic. 3070 // FIXME: We might want to attempt typo correction here. 3071 } 3072 3073 if (!MD || !MD->isVirtual()) { 3074 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 3075 Diag(OA->getLocation(), 3076 diag::override_keyword_only_allowed_on_virtual_member_functions) 3077 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 3078 D->dropAttr<OverrideAttr>(); 3079 } 3080 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 3081 Diag(FA->getLocation(), 3082 diag::override_keyword_only_allowed_on_virtual_member_functions) 3083 << (FA->isSpelledAsSealed() ? "sealed" : "final") 3084 << FixItHint::CreateRemoval(FA->getLocation()); 3085 D->dropAttr<FinalAttr>(); 3086 } 3087 return; 3088 } 3089 3090 // C++11 [class.virtual]p5: 3091 // If a function is marked with the virt-specifier override and 3092 // does not override a member function of a base class, the program is 3093 // ill-formed. 3094 bool HasOverriddenMethods = MD->size_overridden_methods() != 0; 3095 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 3096 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 3097 << MD->getDeclName(); 3098 } 3099 3100 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) { 3101 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) 3102 return; 3103 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 3104 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>()) 3105 return; 3106 3107 SourceLocation Loc = MD->getLocation(); 3108 SourceLocation SpellingLoc = Loc; 3109 if (getSourceManager().isMacroArgExpansion(Loc)) 3110 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin(); 3111 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); 3112 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) 3113 return; 3114 3115 if (MD->size_overridden_methods() > 0) { 3116 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) { 3117 unsigned DiagID = 3118 Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation()) 3119 ? DiagInconsistent 3120 : DiagSuggest; 3121 Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 3122 const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); 3123 Diag(OMD->getLocation(), diag::note_overridden_virtual_function); 3124 }; 3125 if (isa<CXXDestructorDecl>(MD)) 3126 EmitDiag( 3127 diag::warn_inconsistent_destructor_marked_not_override_overriding, 3128 diag::warn_suggest_destructor_marked_not_override_overriding); 3129 else 3130 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding, 3131 diag::warn_suggest_function_marked_not_override_overriding); 3132 } 3133 } 3134 3135 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 3136 /// function overrides a virtual member function marked 'final', according to 3137 /// C++11 [class.virtual]p4. 3138 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 3139 const CXXMethodDecl *Old) { 3140 FinalAttr *FA = Old->getAttr<FinalAttr>(); 3141 if (!FA) 3142 return false; 3143 3144 Diag(New->getLocation(), diag::err_final_function_overridden) 3145 << New->getDeclName() 3146 << FA->isSpelledAsSealed(); 3147 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 3148 return true; 3149 } 3150 3151 static bool InitializationHasSideEffects(const FieldDecl &FD) { 3152 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 3153 // FIXME: Destruction of ObjC lifetime types has side-effects. 3154 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 3155 return !RD->isCompleteDefinition() || 3156 !RD->hasTrivialDefaultConstructor() || 3157 !RD->hasTrivialDestructor(); 3158 return false; 3159 } 3160 3161 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) { 3162 ParsedAttributesView::const_iterator Itr = 3163 llvm::find_if(list, [](const ParsedAttr &AL) { 3164 return AL.isDeclspecPropertyAttribute(); 3165 }); 3166 if (Itr != list.end()) 3167 return &*Itr; 3168 return nullptr; 3169 } 3170 3171 // Check if there is a field shadowing. 3172 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc, 3173 DeclarationName FieldName, 3174 const CXXRecordDecl *RD, 3175 bool DeclIsField) { 3176 if (Diags.isIgnored(diag::warn_shadow_field, Loc)) 3177 return; 3178 3179 // To record a shadowed field in a base 3180 std::map<CXXRecordDecl*, NamedDecl*> Bases; 3181 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier, 3182 CXXBasePath &Path) { 3183 const auto Base = Specifier->getType()->getAsCXXRecordDecl(); 3184 // Record an ambiguous path directly 3185 if (Bases.find(Base) != Bases.end()) 3186 return true; 3187 for (const auto Field : Base->lookup(FieldName)) { 3188 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) && 3189 Field->getAccess() != AS_private) { 3190 assert(Field->getAccess() != AS_none); 3191 assert(Bases.find(Base) == Bases.end()); 3192 Bases[Base] = Field; 3193 return true; 3194 } 3195 } 3196 return false; 3197 }; 3198 3199 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3200 /*DetectVirtual=*/true); 3201 if (!RD->lookupInBases(FieldShadowed, Paths)) 3202 return; 3203 3204 for (const auto &P : Paths) { 3205 auto Base = P.back().Base->getType()->getAsCXXRecordDecl(); 3206 auto It = Bases.find(Base); 3207 // Skip duplicated bases 3208 if (It == Bases.end()) 3209 continue; 3210 auto BaseField = It->second; 3211 assert(BaseField->getAccess() != AS_private); 3212 if (AS_none != 3213 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) { 3214 Diag(Loc, diag::warn_shadow_field) 3215 << FieldName << RD << Base << DeclIsField; 3216 Diag(BaseField->getLocation(), diag::note_shadow_field); 3217 Bases.erase(It); 3218 } 3219 } 3220 } 3221 3222 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 3223 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 3224 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 3225 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 3226 /// present (but parsing it has been deferred). 3227 NamedDecl * 3228 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 3229 MultiTemplateParamsArg TemplateParameterLists, 3230 Expr *BW, const VirtSpecifiers &VS, 3231 InClassInitStyle InitStyle) { 3232 const DeclSpec &DS = D.getDeclSpec(); 3233 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 3234 DeclarationName Name = NameInfo.getName(); 3235 SourceLocation Loc = NameInfo.getLoc(); 3236 3237 // For anonymous bitfields, the location should point to the type. 3238 if (Loc.isInvalid()) 3239 Loc = D.getBeginLoc(); 3240 3241 Expr *BitWidth = static_cast<Expr*>(BW); 3242 3243 assert(isa<CXXRecordDecl>(CurContext)); 3244 assert(!DS.isFriendSpecified()); 3245 3246 bool isFunc = D.isDeclarationOfFunction(); 3247 const ParsedAttr *MSPropertyAttr = 3248 getMSPropertyAttr(D.getDeclSpec().getAttributes()); 3249 3250 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 3251 // The Microsoft extension __interface only permits public member functions 3252 // and prohibits constructors, destructors, operators, non-public member 3253 // functions, static methods and data members. 3254 unsigned InvalidDecl; 3255 bool ShowDeclName = true; 3256 if (!isFunc && 3257 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr)) 3258 InvalidDecl = 0; 3259 else if (!isFunc) 3260 InvalidDecl = 1; 3261 else if (AS != AS_public) 3262 InvalidDecl = 2; 3263 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 3264 InvalidDecl = 3; 3265 else switch (Name.getNameKind()) { 3266 case DeclarationName::CXXConstructorName: 3267 InvalidDecl = 4; 3268 ShowDeclName = false; 3269 break; 3270 3271 case DeclarationName::CXXDestructorName: 3272 InvalidDecl = 5; 3273 ShowDeclName = false; 3274 break; 3275 3276 case DeclarationName::CXXOperatorName: 3277 case DeclarationName::CXXConversionFunctionName: 3278 InvalidDecl = 6; 3279 break; 3280 3281 default: 3282 InvalidDecl = 0; 3283 break; 3284 } 3285 3286 if (InvalidDecl) { 3287 if (ShowDeclName) 3288 Diag(Loc, diag::err_invalid_member_in_interface) 3289 << (InvalidDecl-1) << Name; 3290 else 3291 Diag(Loc, diag::err_invalid_member_in_interface) 3292 << (InvalidDecl-1) << ""; 3293 return nullptr; 3294 } 3295 } 3296 3297 // C++ 9.2p6: A member shall not be declared to have automatic storage 3298 // duration (auto, register) or with the extern storage-class-specifier. 3299 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 3300 // data members and cannot be applied to names declared const or static, 3301 // and cannot be applied to reference members. 3302 switch (DS.getStorageClassSpec()) { 3303 case DeclSpec::SCS_unspecified: 3304 case DeclSpec::SCS_typedef: 3305 case DeclSpec::SCS_static: 3306 break; 3307 case DeclSpec::SCS_mutable: 3308 if (isFunc) { 3309 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 3310 3311 // FIXME: It would be nicer if the keyword was ignored only for this 3312 // declarator. Otherwise we could get follow-up errors. 3313 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3314 } 3315 break; 3316 default: 3317 Diag(DS.getStorageClassSpecLoc(), 3318 diag::err_storageclass_invalid_for_member); 3319 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3320 break; 3321 } 3322 3323 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 3324 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 3325 !isFunc); 3326 3327 if (DS.hasConstexprSpecifier() && isInstField) { 3328 SemaDiagnosticBuilder B = 3329 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 3330 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 3331 if (InitStyle == ICIS_NoInit) { 3332 B << 0 << 0; 3333 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 3334 B << FixItHint::CreateRemoval(ConstexprLoc); 3335 else { 3336 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 3337 D.getMutableDeclSpec().ClearConstexprSpec(); 3338 const char *PrevSpec; 3339 unsigned DiagID; 3340 bool Failed = D.getMutableDeclSpec().SetTypeQual( 3341 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 3342 (void)Failed; 3343 assert(!Failed && "Making a constexpr member const shouldn't fail"); 3344 } 3345 } else { 3346 B << 1; 3347 const char *PrevSpec; 3348 unsigned DiagID; 3349 if (D.getMutableDeclSpec().SetStorageClassSpec( 3350 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 3351 Context.getPrintingPolicy())) { 3352 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 3353 "This is the only DeclSpec that should fail to be applied"); 3354 B << 1; 3355 } else { 3356 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 3357 isInstField = false; 3358 } 3359 } 3360 } 3361 3362 NamedDecl *Member; 3363 if (isInstField) { 3364 CXXScopeSpec &SS = D.getCXXScopeSpec(); 3365 3366 // Data members must have identifiers for names. 3367 if (!Name.isIdentifier()) { 3368 Diag(Loc, diag::err_bad_variable_name) 3369 << Name; 3370 return nullptr; 3371 } 3372 3373 IdentifierInfo *II = Name.getAsIdentifierInfo(); 3374 3375 // Member field could not be with "template" keyword. 3376 // So TemplateParameterLists should be empty in this case. 3377 if (TemplateParameterLists.size()) { 3378 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 3379 if (TemplateParams->size()) { 3380 // There is no such thing as a member field template. 3381 Diag(D.getIdentifierLoc(), diag::err_template_member) 3382 << II 3383 << SourceRange(TemplateParams->getTemplateLoc(), 3384 TemplateParams->getRAngleLoc()); 3385 } else { 3386 // There is an extraneous 'template<>' for this member. 3387 Diag(TemplateParams->getTemplateLoc(), 3388 diag::err_template_member_noparams) 3389 << II 3390 << SourceRange(TemplateParams->getTemplateLoc(), 3391 TemplateParams->getRAngleLoc()); 3392 } 3393 return nullptr; 3394 } 3395 3396 if (SS.isSet() && !SS.isInvalid()) { 3397 // The user provided a superfluous scope specifier inside a class 3398 // definition: 3399 // 3400 // class X { 3401 // int X::member; 3402 // }; 3403 if (DeclContext *DC = computeDeclContext(SS, false)) 3404 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(), 3405 D.getName().getKind() == 3406 UnqualifiedIdKind::IK_TemplateId); 3407 else 3408 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 3409 << Name << SS.getRange(); 3410 3411 SS.clear(); 3412 } 3413 3414 if (MSPropertyAttr) { 3415 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3416 BitWidth, InitStyle, AS, *MSPropertyAttr); 3417 if (!Member) 3418 return nullptr; 3419 isInstField = false; 3420 } else { 3421 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3422 BitWidth, InitStyle, AS); 3423 if (!Member) 3424 return nullptr; 3425 } 3426 3427 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext)); 3428 } else { 3429 Member = HandleDeclarator(S, D, TemplateParameterLists); 3430 if (!Member) 3431 return nullptr; 3432 3433 // Non-instance-fields can't have a bitfield. 3434 if (BitWidth) { 3435 if (Member->isInvalidDecl()) { 3436 // don't emit another diagnostic. 3437 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) { 3438 // C++ 9.6p3: A bit-field shall not be a static member. 3439 // "static member 'A' cannot be a bit-field" 3440 Diag(Loc, diag::err_static_not_bitfield) 3441 << Name << BitWidth->getSourceRange(); 3442 } else if (isa<TypedefDecl>(Member)) { 3443 // "typedef member 'x' cannot be a bit-field" 3444 Diag(Loc, diag::err_typedef_not_bitfield) 3445 << Name << BitWidth->getSourceRange(); 3446 } else { 3447 // A function typedef ("typedef int f(); f a;"). 3448 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 3449 Diag(Loc, diag::err_not_integral_type_bitfield) 3450 << Name << cast<ValueDecl>(Member)->getType() 3451 << BitWidth->getSourceRange(); 3452 } 3453 3454 BitWidth = nullptr; 3455 Member->setInvalidDecl(); 3456 } 3457 3458 NamedDecl *NonTemplateMember = Member; 3459 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 3460 NonTemplateMember = FunTmpl->getTemplatedDecl(); 3461 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 3462 NonTemplateMember = VarTmpl->getTemplatedDecl(); 3463 3464 Member->setAccess(AS); 3465 3466 // If we have declared a member function template or static data member 3467 // template, set the access of the templated declaration as well. 3468 if (NonTemplateMember != Member) 3469 NonTemplateMember->setAccess(AS); 3470 3471 // C++ [temp.deduct.guide]p3: 3472 // A deduction guide [...] for a member class template [shall be 3473 // declared] with the same access [as the template]. 3474 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) { 3475 auto *TD = DG->getDeducedTemplate(); 3476 // Access specifiers are only meaningful if both the template and the 3477 // deduction guide are from the same scope. 3478 if (AS != TD->getAccess() && 3479 TD->getDeclContext()->getRedeclContext()->Equals( 3480 DG->getDeclContext()->getRedeclContext())) { 3481 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access); 3482 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access) 3483 << TD->getAccess(); 3484 const AccessSpecDecl *LastAccessSpec = nullptr; 3485 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) { 3486 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D)) 3487 LastAccessSpec = AccessSpec; 3488 } 3489 assert(LastAccessSpec && "differing access with no access specifier"); 3490 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access) 3491 << AS; 3492 } 3493 } 3494 } 3495 3496 if (VS.isOverrideSpecified()) 3497 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(), 3498 AttributeCommonInfo::AS_Keyword)); 3499 if (VS.isFinalSpecified()) 3500 Member->addAttr(FinalAttr::Create( 3501 Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword, 3502 static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed()))); 3503 3504 if (VS.getLastLocation().isValid()) { 3505 // Update the end location of a method that has a virt-specifiers. 3506 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 3507 MD->setRangeEnd(VS.getLastLocation()); 3508 } 3509 3510 CheckOverrideControl(Member); 3511 3512 assert((Name || isInstField) && "No identifier for non-field ?"); 3513 3514 if (isInstField) { 3515 FieldDecl *FD = cast<FieldDecl>(Member); 3516 FieldCollector->Add(FD); 3517 3518 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 3519 // Remember all explicit private FieldDecls that have a name, no side 3520 // effects and are not part of a dependent type declaration. 3521 if (!FD->isImplicit() && FD->getDeclName() && 3522 FD->getAccess() == AS_private && 3523 !FD->hasAttr<UnusedAttr>() && 3524 !FD->getParent()->isDependentContext() && 3525 !InitializationHasSideEffects(*FD)) 3526 UnusedPrivateFields.insert(FD); 3527 } 3528 } 3529 3530 return Member; 3531 } 3532 3533 namespace { 3534 class UninitializedFieldVisitor 3535 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 3536 Sema &S; 3537 // List of Decls to generate a warning on. Also remove Decls that become 3538 // initialized. 3539 llvm::SmallPtrSetImpl<ValueDecl*> &Decls; 3540 // List of base classes of the record. Classes are removed after their 3541 // initializers. 3542 llvm::SmallPtrSetImpl<QualType> &BaseClasses; 3543 // Vector of decls to be removed from the Decl set prior to visiting the 3544 // nodes. These Decls may have been initialized in the prior initializer. 3545 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; 3546 // If non-null, add a note to the warning pointing back to the constructor. 3547 const CXXConstructorDecl *Constructor; 3548 // Variables to hold state when processing an initializer list. When 3549 // InitList is true, special case initialization of FieldDecls matching 3550 // InitListFieldDecl. 3551 bool InitList; 3552 FieldDecl *InitListFieldDecl; 3553 llvm::SmallVector<unsigned, 4> InitFieldIndex; 3554 3555 public: 3556 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 3557 UninitializedFieldVisitor(Sema &S, 3558 llvm::SmallPtrSetImpl<ValueDecl*> &Decls, 3559 llvm::SmallPtrSetImpl<QualType> &BaseClasses) 3560 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), 3561 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} 3562 3563 // Returns true if the use of ME is not an uninitialized use. 3564 bool IsInitListMemberExprInitialized(MemberExpr *ME, 3565 bool CheckReferenceOnly) { 3566 llvm::SmallVector<FieldDecl*, 4> Fields; 3567 bool ReferenceField = false; 3568 while (ME) { 3569 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 3570 if (!FD) 3571 return false; 3572 Fields.push_back(FD); 3573 if (FD->getType()->isReferenceType()) 3574 ReferenceField = true; 3575 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); 3576 } 3577 3578 // Binding a reference to an uninitialized field is not an 3579 // uninitialized use. 3580 if (CheckReferenceOnly && !ReferenceField) 3581 return true; 3582 3583 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 3584 // Discard the first field since it is the field decl that is being 3585 // initialized. 3586 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) { 3587 UsedFieldIndex.push_back((*I)->getFieldIndex()); 3588 } 3589 3590 for (auto UsedIter = UsedFieldIndex.begin(), 3591 UsedEnd = UsedFieldIndex.end(), 3592 OrigIter = InitFieldIndex.begin(), 3593 OrigEnd = InitFieldIndex.end(); 3594 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 3595 if (*UsedIter < *OrigIter) 3596 return true; 3597 if (*UsedIter > *OrigIter) 3598 break; 3599 } 3600 3601 return false; 3602 } 3603 3604 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, 3605 bool AddressOf) { 3606 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 3607 return; 3608 3609 // FieldME is the inner-most MemberExpr that is not an anonymous struct 3610 // or union. 3611 MemberExpr *FieldME = ME; 3612 3613 bool AllPODFields = FieldME->getType().isPODType(S.Context); 3614 3615 Expr *Base = ME; 3616 while (MemberExpr *SubME = 3617 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { 3618 3619 if (isa<VarDecl>(SubME->getMemberDecl())) 3620 return; 3621 3622 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) 3623 if (!FD->isAnonymousStructOrUnion()) 3624 FieldME = SubME; 3625 3626 if (!FieldME->getType().isPODType(S.Context)) 3627 AllPODFields = false; 3628 3629 Base = SubME->getBase(); 3630 } 3631 3632 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) { 3633 Visit(Base); 3634 return; 3635 } 3636 3637 if (AddressOf && AllPODFields) 3638 return; 3639 3640 ValueDecl* FoundVD = FieldME->getMemberDecl(); 3641 3642 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { 3643 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { 3644 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); 3645 } 3646 3647 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { 3648 QualType T = BaseCast->getType(); 3649 if (T->isPointerType() && 3650 BaseClasses.count(T->getPointeeType())) { 3651 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) 3652 << T->getPointeeType() << FoundVD; 3653 } 3654 } 3655 } 3656 3657 if (!Decls.count(FoundVD)) 3658 return; 3659 3660 const bool IsReference = FoundVD->getType()->isReferenceType(); 3661 3662 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { 3663 // Special checking for initializer lists. 3664 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { 3665 return; 3666 } 3667 } else { 3668 // Prevent double warnings on use of unbounded references. 3669 if (CheckReferenceOnly && !IsReference) 3670 return; 3671 } 3672 3673 unsigned diag = IsReference 3674 ? diag::warn_reference_field_is_uninit 3675 : diag::warn_field_is_uninit; 3676 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 3677 if (Constructor) 3678 S.Diag(Constructor->getLocation(), 3679 diag::note_uninit_in_this_constructor) 3680 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 3681 3682 } 3683 3684 void HandleValue(Expr *E, bool AddressOf) { 3685 E = E->IgnoreParens(); 3686 3687 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3688 HandleMemberExpr(ME, false /*CheckReferenceOnly*/, 3689 AddressOf /*AddressOf*/); 3690 return; 3691 } 3692 3693 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 3694 Visit(CO->getCond()); 3695 HandleValue(CO->getTrueExpr(), AddressOf); 3696 HandleValue(CO->getFalseExpr(), AddressOf); 3697 return; 3698 } 3699 3700 if (BinaryConditionalOperator *BCO = 3701 dyn_cast<BinaryConditionalOperator>(E)) { 3702 Visit(BCO->getCond()); 3703 HandleValue(BCO->getFalseExpr(), AddressOf); 3704 return; 3705 } 3706 3707 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 3708 HandleValue(OVE->getSourceExpr(), AddressOf); 3709 return; 3710 } 3711 3712 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 3713 switch (BO->getOpcode()) { 3714 default: 3715 break; 3716 case(BO_PtrMemD): 3717 case(BO_PtrMemI): 3718 HandleValue(BO->getLHS(), AddressOf); 3719 Visit(BO->getRHS()); 3720 return; 3721 case(BO_Comma): 3722 Visit(BO->getLHS()); 3723 HandleValue(BO->getRHS(), AddressOf); 3724 return; 3725 } 3726 } 3727 3728 Visit(E); 3729 } 3730 3731 void CheckInitListExpr(InitListExpr *ILE) { 3732 InitFieldIndex.push_back(0); 3733 for (auto Child : ILE->children()) { 3734 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { 3735 CheckInitListExpr(SubList); 3736 } else { 3737 Visit(Child); 3738 } 3739 ++InitFieldIndex.back(); 3740 } 3741 InitFieldIndex.pop_back(); 3742 } 3743 3744 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, 3745 FieldDecl *Field, const Type *BaseClass) { 3746 // Remove Decls that may have been initialized in the previous 3747 // initializer. 3748 for (ValueDecl* VD : DeclsToRemove) 3749 Decls.erase(VD); 3750 DeclsToRemove.clear(); 3751 3752 Constructor = FieldConstructor; 3753 InitListExpr *ILE = dyn_cast<InitListExpr>(E); 3754 3755 if (ILE && Field) { 3756 InitList = true; 3757 InitListFieldDecl = Field; 3758 InitFieldIndex.clear(); 3759 CheckInitListExpr(ILE); 3760 } else { 3761 InitList = false; 3762 Visit(E); 3763 } 3764 3765 if (Field) 3766 Decls.erase(Field); 3767 if (BaseClass) 3768 BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); 3769 } 3770 3771 void VisitMemberExpr(MemberExpr *ME) { 3772 // All uses of unbounded reference fields will warn. 3773 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); 3774 } 3775 3776 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 3777 if (E->getCastKind() == CK_LValueToRValue) { 3778 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3779 return; 3780 } 3781 3782 Inherited::VisitImplicitCastExpr(E); 3783 } 3784 3785 void VisitCXXConstructExpr(CXXConstructExpr *E) { 3786 if (E->getConstructor()->isCopyConstructor()) { 3787 Expr *ArgExpr = E->getArg(0); 3788 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 3789 if (ILE->getNumInits() == 1) 3790 ArgExpr = ILE->getInit(0); 3791 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 3792 if (ICE->getCastKind() == CK_NoOp) 3793 ArgExpr = ICE->getSubExpr(); 3794 HandleValue(ArgExpr, false /*AddressOf*/); 3795 return; 3796 } 3797 Inherited::VisitCXXConstructExpr(E); 3798 } 3799 3800 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 3801 Expr *Callee = E->getCallee(); 3802 if (isa<MemberExpr>(Callee)) { 3803 HandleValue(Callee, false /*AddressOf*/); 3804 for (auto Arg : E->arguments()) 3805 Visit(Arg); 3806 return; 3807 } 3808 3809 Inherited::VisitCXXMemberCallExpr(E); 3810 } 3811 3812 void VisitCallExpr(CallExpr *E) { 3813 // Treat std::move as a use. 3814 if (E->isCallToStdMove()) { 3815 HandleValue(E->getArg(0), /*AddressOf=*/false); 3816 return; 3817 } 3818 3819 Inherited::VisitCallExpr(E); 3820 } 3821 3822 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 3823 Expr *Callee = E->getCallee(); 3824 3825 if (isa<UnresolvedLookupExpr>(Callee)) 3826 return Inherited::VisitCXXOperatorCallExpr(E); 3827 3828 Visit(Callee); 3829 for (auto Arg : E->arguments()) 3830 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); 3831 } 3832 3833 void VisitBinaryOperator(BinaryOperator *E) { 3834 // If a field assignment is detected, remove the field from the 3835 // uninitiailized field set. 3836 if (E->getOpcode() == BO_Assign) 3837 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 3838 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 3839 if (!FD->getType()->isReferenceType()) 3840 DeclsToRemove.push_back(FD); 3841 3842 if (E->isCompoundAssignmentOp()) { 3843 HandleValue(E->getLHS(), false /*AddressOf*/); 3844 Visit(E->getRHS()); 3845 return; 3846 } 3847 3848 Inherited::VisitBinaryOperator(E); 3849 } 3850 3851 void VisitUnaryOperator(UnaryOperator *E) { 3852 if (E->isIncrementDecrementOp()) { 3853 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3854 return; 3855 } 3856 if (E->getOpcode() == UO_AddrOf) { 3857 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { 3858 HandleValue(ME->getBase(), true /*AddressOf*/); 3859 return; 3860 } 3861 } 3862 3863 Inherited::VisitUnaryOperator(E); 3864 } 3865 }; 3866 3867 // Diagnose value-uses of fields to initialize themselves, e.g. 3868 // foo(foo) 3869 // where foo is not also a parameter to the constructor. 3870 // Also diagnose across field uninitialized use such as 3871 // x(y), y(x) 3872 // TODO: implement -Wuninitialized and fold this into that framework. 3873 static void DiagnoseUninitializedFields( 3874 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 3875 3876 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 3877 Constructor->getLocation())) { 3878 return; 3879 } 3880 3881 if (Constructor->isInvalidDecl()) 3882 return; 3883 3884 const CXXRecordDecl *RD = Constructor->getParent(); 3885 3886 if (RD->isDependentContext()) 3887 return; 3888 3889 // Holds fields that are uninitialized. 3890 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 3891 3892 // At the beginning, all fields are uninitialized. 3893 for (auto *I : RD->decls()) { 3894 if (auto *FD = dyn_cast<FieldDecl>(I)) { 3895 UninitializedFields.insert(FD); 3896 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 3897 UninitializedFields.insert(IFD->getAnonField()); 3898 } 3899 } 3900 3901 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; 3902 for (auto I : RD->bases()) 3903 UninitializedBaseClasses.insert(I.getType().getCanonicalType()); 3904 3905 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3906 return; 3907 3908 UninitializedFieldVisitor UninitializedChecker(SemaRef, 3909 UninitializedFields, 3910 UninitializedBaseClasses); 3911 3912 for (const auto *FieldInit : Constructor->inits()) { 3913 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3914 break; 3915 3916 Expr *InitExpr = FieldInit->getInit(); 3917 if (!InitExpr) 3918 continue; 3919 3920 if (CXXDefaultInitExpr *Default = 3921 dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 3922 InitExpr = Default->getExpr(); 3923 if (!InitExpr) 3924 continue; 3925 // In class initializers will point to the constructor. 3926 UninitializedChecker.CheckInitializer(InitExpr, Constructor, 3927 FieldInit->getAnyMember(), 3928 FieldInit->getBaseClass()); 3929 } else { 3930 UninitializedChecker.CheckInitializer(InitExpr, nullptr, 3931 FieldInit->getAnyMember(), 3932 FieldInit->getBaseClass()); 3933 } 3934 } 3935 } 3936 } // namespace 3937 3938 /// Enter a new C++ default initializer scope. After calling this, the 3939 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 3940 /// parsing or instantiating the initializer failed. 3941 void Sema::ActOnStartCXXInClassMemberInitializer() { 3942 // Create a synthetic function scope to represent the call to the constructor 3943 // that notionally surrounds a use of this initializer. 3944 PushFunctionScope(); 3945 } 3946 3947 void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) { 3948 if (!D.isFunctionDeclarator()) 3949 return; 3950 auto &FTI = D.getFunctionTypeInfo(); 3951 if (!FTI.Params) 3952 return; 3953 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params, 3954 FTI.NumParams)) { 3955 auto *ParamDecl = cast<NamedDecl>(Param.Param); 3956 if (ParamDecl->getDeclName()) 3957 PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false); 3958 } 3959 } 3960 3961 ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) { 3962 return ActOnRequiresClause(ConstraintExpr); 3963 } 3964 3965 ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) { 3966 if (ConstraintExpr.isInvalid()) 3967 return ExprError(); 3968 3969 ConstraintExpr = CorrectDelayedTyposInExpr(ConstraintExpr); 3970 if (ConstraintExpr.isInvalid()) 3971 return ExprError(); 3972 3973 if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(), 3974 UPPC_RequiresClause)) 3975 return ExprError(); 3976 3977 return ConstraintExpr; 3978 } 3979 3980 /// This is invoked after parsing an in-class initializer for a 3981 /// non-static C++ class member, and after instantiating an in-class initializer 3982 /// in a class template. Such actions are deferred until the class is complete. 3983 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 3984 SourceLocation InitLoc, 3985 Expr *InitExpr) { 3986 // Pop the notional constructor scope we created earlier. 3987 PopFunctionScopeInfo(nullptr, D); 3988 3989 FieldDecl *FD = dyn_cast<FieldDecl>(D); 3990 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && 3991 "must set init style when field is created"); 3992 3993 if (!InitExpr) { 3994 D->setInvalidDecl(); 3995 if (FD) 3996 FD->removeInClassInitializer(); 3997 return; 3998 } 3999 4000 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 4001 FD->setInvalidDecl(); 4002 FD->removeInClassInitializer(); 4003 return; 4004 } 4005 4006 ExprResult Init = InitExpr; 4007 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 4008 InitializedEntity Entity = 4009 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD); 4010 InitializationKind Kind = 4011 FD->getInClassInitStyle() == ICIS_ListInit 4012 ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(), 4013 InitExpr->getBeginLoc(), 4014 InitExpr->getEndLoc()) 4015 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc); 4016 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 4017 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 4018 if (Init.isInvalid()) { 4019 FD->setInvalidDecl(); 4020 return; 4021 } 4022 } 4023 4024 // C++11 [class.base.init]p7: 4025 // The initialization of each base and member constitutes a 4026 // full-expression. 4027 Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false); 4028 if (Init.isInvalid()) { 4029 FD->setInvalidDecl(); 4030 return; 4031 } 4032 4033 InitExpr = Init.get(); 4034 4035 FD->setInClassInitializer(InitExpr); 4036 } 4037 4038 /// Find the direct and/or virtual base specifiers that 4039 /// correspond to the given base type, for use in base initialization 4040 /// within a constructor. 4041 static bool FindBaseInitializer(Sema &SemaRef, 4042 CXXRecordDecl *ClassDecl, 4043 QualType BaseType, 4044 const CXXBaseSpecifier *&DirectBaseSpec, 4045 const CXXBaseSpecifier *&VirtualBaseSpec) { 4046 // First, check for a direct base class. 4047 DirectBaseSpec = nullptr; 4048 for (const auto &Base : ClassDecl->bases()) { 4049 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 4050 // We found a direct base of this type. That's what we're 4051 // initializing. 4052 DirectBaseSpec = &Base; 4053 break; 4054 } 4055 } 4056 4057 // Check for a virtual base class. 4058 // FIXME: We might be able to short-circuit this if we know in advance that 4059 // there are no virtual bases. 4060 VirtualBaseSpec = nullptr; 4061 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 4062 // We haven't found a base yet; search the class hierarchy for a 4063 // virtual base class. 4064 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 4065 /*DetectVirtual=*/false); 4066 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(), 4067 SemaRef.Context.getTypeDeclType(ClassDecl), 4068 BaseType, Paths)) { 4069 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 4070 Path != Paths.end(); ++Path) { 4071 if (Path->back().Base->isVirtual()) { 4072 VirtualBaseSpec = Path->back().Base; 4073 break; 4074 } 4075 } 4076 } 4077 } 4078 4079 return DirectBaseSpec || VirtualBaseSpec; 4080 } 4081 4082 /// Handle a C++ member initializer using braced-init-list syntax. 4083 MemInitResult 4084 Sema::ActOnMemInitializer(Decl *ConstructorD, 4085 Scope *S, 4086 CXXScopeSpec &SS, 4087 IdentifierInfo *MemberOrBase, 4088 ParsedType TemplateTypeTy, 4089 const DeclSpec &DS, 4090 SourceLocation IdLoc, 4091 Expr *InitList, 4092 SourceLocation EllipsisLoc) { 4093 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 4094 DS, IdLoc, InitList, 4095 EllipsisLoc); 4096 } 4097 4098 /// Handle a C++ member initializer using parentheses syntax. 4099 MemInitResult 4100 Sema::ActOnMemInitializer(Decl *ConstructorD, 4101 Scope *S, 4102 CXXScopeSpec &SS, 4103 IdentifierInfo *MemberOrBase, 4104 ParsedType TemplateTypeTy, 4105 const DeclSpec &DS, 4106 SourceLocation IdLoc, 4107 SourceLocation LParenLoc, 4108 ArrayRef<Expr *> Args, 4109 SourceLocation RParenLoc, 4110 SourceLocation EllipsisLoc) { 4111 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc); 4112 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 4113 DS, IdLoc, List, EllipsisLoc); 4114 } 4115 4116 namespace { 4117 4118 // Callback to only accept typo corrections that can be a valid C++ member 4119 // initializer: either a non-static field member or a base class. 4120 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback { 4121 public: 4122 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 4123 : ClassDecl(ClassDecl) {} 4124 4125 bool ValidateCandidate(const TypoCorrection &candidate) override { 4126 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 4127 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 4128 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 4129 return isa<TypeDecl>(ND); 4130 } 4131 return false; 4132 } 4133 4134 std::unique_ptr<CorrectionCandidateCallback> clone() override { 4135 return std::make_unique<MemInitializerValidatorCCC>(*this); 4136 } 4137 4138 private: 4139 CXXRecordDecl *ClassDecl; 4140 }; 4141 4142 } 4143 4144 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, 4145 CXXScopeSpec &SS, 4146 ParsedType TemplateTypeTy, 4147 IdentifierInfo *MemberOrBase) { 4148 if (SS.getScopeRep() || TemplateTypeTy) 4149 return nullptr; 4150 for (auto *D : ClassDecl->lookup(MemberOrBase)) 4151 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) 4152 return cast<ValueDecl>(D); 4153 return nullptr; 4154 } 4155 4156 /// Handle a C++ member initializer. 4157 MemInitResult 4158 Sema::BuildMemInitializer(Decl *ConstructorD, 4159 Scope *S, 4160 CXXScopeSpec &SS, 4161 IdentifierInfo *MemberOrBase, 4162 ParsedType TemplateTypeTy, 4163 const DeclSpec &DS, 4164 SourceLocation IdLoc, 4165 Expr *Init, 4166 SourceLocation EllipsisLoc) { 4167 ExprResult Res = CorrectDelayedTyposInExpr(Init, /*InitDecl=*/nullptr, 4168 /*RecoverUncorrectedTypos=*/true); 4169 if (!Res.isUsable()) 4170 return true; 4171 Init = Res.get(); 4172 4173 if (!ConstructorD) 4174 return true; 4175 4176 AdjustDeclIfTemplate(ConstructorD); 4177 4178 CXXConstructorDecl *Constructor 4179 = dyn_cast<CXXConstructorDecl>(ConstructorD); 4180 if (!Constructor) { 4181 // The user wrote a constructor initializer on a function that is 4182 // not a C++ constructor. Ignore the error for now, because we may 4183 // have more member initializers coming; we'll diagnose it just 4184 // once in ActOnMemInitializers. 4185 return true; 4186 } 4187 4188 CXXRecordDecl *ClassDecl = Constructor->getParent(); 4189 4190 // C++ [class.base.init]p2: 4191 // Names in a mem-initializer-id are looked up in the scope of the 4192 // constructor's class and, if not found in that scope, are looked 4193 // up in the scope containing the constructor's definition. 4194 // [Note: if the constructor's class contains a member with the 4195 // same name as a direct or virtual base class of the class, a 4196 // mem-initializer-id naming the member or base class and composed 4197 // of a single identifier refers to the class member. A 4198 // mem-initializer-id for the hidden base class may be specified 4199 // using a qualified name. ] 4200 4201 // Look for a member, first. 4202 if (ValueDecl *Member = tryLookupCtorInitMemberDecl( 4203 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) { 4204 if (EllipsisLoc.isValid()) 4205 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 4206 << MemberOrBase 4207 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 4208 4209 return BuildMemberInitializer(Member, Init, IdLoc); 4210 } 4211 // It didn't name a member, so see if it names a class. 4212 QualType BaseType; 4213 TypeSourceInfo *TInfo = nullptr; 4214 4215 if (TemplateTypeTy) { 4216 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 4217 if (BaseType.isNull()) 4218 return true; 4219 } else if (DS.getTypeSpecType() == TST_decltype) { 4220 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 4221 } else if (DS.getTypeSpecType() == TST_decltype_auto) { 4222 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); 4223 return true; 4224 } else { 4225 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 4226 LookupParsedName(R, S, &SS); 4227 4228 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 4229 if (!TyD) { 4230 if (R.isAmbiguous()) return true; 4231 4232 // We don't want access-control diagnostics here. 4233 R.suppressDiagnostics(); 4234 4235 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 4236 bool NotUnknownSpecialization = false; 4237 DeclContext *DC = computeDeclContext(SS, false); 4238 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 4239 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 4240 4241 if (!NotUnknownSpecialization) { 4242 // When the scope specifier can refer to a member of an unknown 4243 // specialization, we take it as a type name. 4244 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 4245 SS.getWithLocInContext(Context), 4246 *MemberOrBase, IdLoc); 4247 if (BaseType.isNull()) 4248 return true; 4249 4250 TInfo = Context.CreateTypeSourceInfo(BaseType); 4251 DependentNameTypeLoc TL = 4252 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>(); 4253 if (!TL.isNull()) { 4254 TL.setNameLoc(IdLoc); 4255 TL.setElaboratedKeywordLoc(SourceLocation()); 4256 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4257 } 4258 4259 R.clear(); 4260 R.setLookupName(MemberOrBase); 4261 } 4262 } 4263 4264 // If no results were found, try to correct typos. 4265 TypoCorrection Corr; 4266 MemInitializerValidatorCCC CCC(ClassDecl); 4267 if (R.empty() && BaseType.isNull() && 4268 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 4269 CCC, CTK_ErrorRecovery, ClassDecl))) { 4270 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 4271 // We have found a non-static data member with a similar 4272 // name to what was typed; complain and initialize that 4273 // member. 4274 diagnoseTypo(Corr, 4275 PDiag(diag::err_mem_init_not_member_or_class_suggest) 4276 << MemberOrBase << true); 4277 return BuildMemberInitializer(Member, Init, IdLoc); 4278 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 4279 const CXXBaseSpecifier *DirectBaseSpec; 4280 const CXXBaseSpecifier *VirtualBaseSpec; 4281 if (FindBaseInitializer(*this, ClassDecl, 4282 Context.getTypeDeclType(Type), 4283 DirectBaseSpec, VirtualBaseSpec)) { 4284 // We have found a direct or virtual base class with a 4285 // similar name to what was typed; complain and initialize 4286 // that base class. 4287 diagnoseTypo(Corr, 4288 PDiag(diag::err_mem_init_not_member_or_class_suggest) 4289 << MemberOrBase << false, 4290 PDiag() /*Suppress note, we provide our own.*/); 4291 4292 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 4293 : VirtualBaseSpec; 4294 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here) 4295 << BaseSpec->getType() << BaseSpec->getSourceRange(); 4296 4297 TyD = Type; 4298 } 4299 } 4300 } 4301 4302 if (!TyD && BaseType.isNull()) { 4303 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 4304 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 4305 return true; 4306 } 4307 } 4308 4309 if (BaseType.isNull()) { 4310 BaseType = Context.getTypeDeclType(TyD); 4311 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); 4312 if (SS.isSet()) { 4313 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 4314 BaseType); 4315 TInfo = Context.CreateTypeSourceInfo(BaseType); 4316 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>(); 4317 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc); 4318 TL.setElaboratedKeywordLoc(SourceLocation()); 4319 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4320 } 4321 } 4322 } 4323 4324 if (!TInfo) 4325 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 4326 4327 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 4328 } 4329 4330 MemInitResult 4331 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 4332 SourceLocation IdLoc) { 4333 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 4334 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 4335 assert((DirectMember || IndirectMember) && 4336 "Member must be a FieldDecl or IndirectFieldDecl"); 4337 4338 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4339 return true; 4340 4341 if (Member->isInvalidDecl()) 4342 return true; 4343 4344 MultiExprArg Args; 4345 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4346 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4347 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 4348 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 4349 } else { 4350 // Template instantiation doesn't reconstruct ParenListExprs for us. 4351 Args = Init; 4352 } 4353 4354 SourceRange InitRange = Init->getSourceRange(); 4355 4356 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 4357 // Can't check initialization for a member of dependent type or when 4358 // any of the arguments are type-dependent expressions. 4359 DiscardCleanupsInEvaluationContext(); 4360 } else { 4361 bool InitList = false; 4362 if (isa<InitListExpr>(Init)) { 4363 InitList = true; 4364 Args = Init; 4365 } 4366 4367 // Initialize the member. 4368 InitializedEntity MemberEntity = 4369 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 4370 : InitializedEntity::InitializeMember(IndirectMember, 4371 nullptr); 4372 InitializationKind Kind = 4373 InitList ? InitializationKind::CreateDirectList( 4374 IdLoc, Init->getBeginLoc(), Init->getEndLoc()) 4375 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 4376 InitRange.getEnd()); 4377 4378 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 4379 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 4380 nullptr); 4381 if (!MemberInit.isInvalid()) { 4382 // C++11 [class.base.init]p7: 4383 // The initialization of each base and member constitutes a 4384 // full-expression. 4385 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(), 4386 /*DiscardedValue*/ false); 4387 } 4388 4389 if (MemberInit.isInvalid()) { 4390 // Args were sensible expressions but we couldn't initialize the member 4391 // from them. Preserve them in a RecoveryExpr instead. 4392 Init = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args, 4393 Member->getType()) 4394 .get(); 4395 if (!Init) 4396 return true; 4397 } else { 4398 Init = MemberInit.get(); 4399 } 4400 } 4401 4402 if (DirectMember) { 4403 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 4404 InitRange.getBegin(), Init, 4405 InitRange.getEnd()); 4406 } else { 4407 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 4408 InitRange.getBegin(), Init, 4409 InitRange.getEnd()); 4410 } 4411 } 4412 4413 MemInitResult 4414 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 4415 CXXRecordDecl *ClassDecl) { 4416 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4417 if (!LangOpts.CPlusPlus11) 4418 return Diag(NameLoc, diag::err_delegating_ctor) 4419 << TInfo->getTypeLoc().getLocalSourceRange(); 4420 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 4421 4422 bool InitList = true; 4423 MultiExprArg Args = Init; 4424 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4425 InitList = false; 4426 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4427 } 4428 4429 SourceRange InitRange = Init->getSourceRange(); 4430 // Initialize the object. 4431 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 4432 QualType(ClassDecl->getTypeForDecl(), 0)); 4433 InitializationKind Kind = 4434 InitList ? InitializationKind::CreateDirectList( 4435 NameLoc, Init->getBeginLoc(), Init->getEndLoc()) 4436 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 4437 InitRange.getEnd()); 4438 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 4439 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 4440 Args, nullptr); 4441 if (!DelegationInit.isInvalid()) { 4442 assert((DelegationInit.get()->containsErrors() || 4443 cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) && 4444 "Delegating constructor with no target?"); 4445 4446 // C++11 [class.base.init]p7: 4447 // The initialization of each base and member constitutes a 4448 // full-expression. 4449 DelegationInit = ActOnFinishFullExpr( 4450 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false); 4451 } 4452 4453 if (DelegationInit.isInvalid()) { 4454 DelegationInit = 4455 CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args, 4456 QualType(ClassDecl->getTypeForDecl(), 0)); 4457 if (DelegationInit.isInvalid()) 4458 return true; 4459 } else { 4460 // If we are in a dependent context, template instantiation will 4461 // perform this type-checking again. Just save the arguments that we 4462 // received in a ParenListExpr. 4463 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4464 // of the information that we have about the base 4465 // initializer. However, deconstructing the ASTs is a dicey process, 4466 // and this approach is far more likely to get the corner cases right. 4467 if (CurContext->isDependentContext()) 4468 DelegationInit = Init; 4469 } 4470 4471 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 4472 DelegationInit.getAs<Expr>(), 4473 InitRange.getEnd()); 4474 } 4475 4476 MemInitResult 4477 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 4478 Expr *Init, CXXRecordDecl *ClassDecl, 4479 SourceLocation EllipsisLoc) { 4480 SourceLocation BaseLoc 4481 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4482 4483 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 4484 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 4485 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4486 4487 // C++ [class.base.init]p2: 4488 // [...] Unless the mem-initializer-id names a nonstatic data 4489 // member of the constructor's class or a direct or virtual base 4490 // of that class, the mem-initializer is ill-formed. A 4491 // mem-initializer-list can initialize a base class using any 4492 // name that denotes that base class type. 4493 4494 // We can store the initializers in "as-written" form and delay analysis until 4495 // instantiation if the constructor is dependent. But not for dependent 4496 // (broken) code in a non-template! SetCtorInitializers does not expect this. 4497 bool Dependent = CurContext->isDependentContext() && 4498 (BaseType->isDependentType() || Init->isTypeDependent()); 4499 4500 SourceRange InitRange = Init->getSourceRange(); 4501 if (EllipsisLoc.isValid()) { 4502 // This is a pack expansion. 4503 if (!BaseType->containsUnexpandedParameterPack()) { 4504 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 4505 << SourceRange(BaseLoc, InitRange.getEnd()); 4506 4507 EllipsisLoc = SourceLocation(); 4508 } 4509 } else { 4510 // Check for any unexpanded parameter packs. 4511 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 4512 return true; 4513 4514 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4515 return true; 4516 } 4517 4518 // Check for direct and virtual base classes. 4519 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 4520 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 4521 if (!Dependent) { 4522 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 4523 BaseType)) 4524 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 4525 4526 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 4527 VirtualBaseSpec); 4528 4529 // C++ [base.class.init]p2: 4530 // Unless the mem-initializer-id names a nonstatic data member of the 4531 // constructor's class or a direct or virtual base of that class, the 4532 // mem-initializer is ill-formed. 4533 if (!DirectBaseSpec && !VirtualBaseSpec) { 4534 // If the class has any dependent bases, then it's possible that 4535 // one of those types will resolve to the same type as 4536 // BaseType. Therefore, just treat this as a dependent base 4537 // class initialization. FIXME: Should we try to check the 4538 // initialization anyway? It seems odd. 4539 if (ClassDecl->hasAnyDependentBases()) 4540 Dependent = true; 4541 else 4542 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 4543 << BaseType << Context.getTypeDeclType(ClassDecl) 4544 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4545 } 4546 } 4547 4548 if (Dependent) { 4549 DiscardCleanupsInEvaluationContext(); 4550 4551 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4552 /*IsVirtual=*/false, 4553 InitRange.getBegin(), Init, 4554 InitRange.getEnd(), EllipsisLoc); 4555 } 4556 4557 // C++ [base.class.init]p2: 4558 // If a mem-initializer-id is ambiguous because it designates both 4559 // a direct non-virtual base class and an inherited virtual base 4560 // class, the mem-initializer is ill-formed. 4561 if (DirectBaseSpec && VirtualBaseSpec) 4562 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 4563 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4564 4565 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 4566 if (!BaseSpec) 4567 BaseSpec = VirtualBaseSpec; 4568 4569 // Initialize the base. 4570 bool InitList = true; 4571 MultiExprArg Args = Init; 4572 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4573 InitList = false; 4574 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4575 } 4576 4577 InitializedEntity BaseEntity = 4578 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 4579 InitializationKind Kind = 4580 InitList ? InitializationKind::CreateDirectList(BaseLoc) 4581 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 4582 InitRange.getEnd()); 4583 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 4584 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 4585 if (!BaseInit.isInvalid()) { 4586 // C++11 [class.base.init]p7: 4587 // The initialization of each base and member constitutes a 4588 // full-expression. 4589 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(), 4590 /*DiscardedValue*/ false); 4591 } 4592 4593 if (BaseInit.isInvalid()) { 4594 BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), 4595 Args, BaseType); 4596 if (BaseInit.isInvalid()) 4597 return true; 4598 } else { 4599 // If we are in a dependent context, template instantiation will 4600 // perform this type-checking again. Just save the arguments that we 4601 // received in a ParenListExpr. 4602 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4603 // of the information that we have about the base 4604 // initializer. However, deconstructing the ASTs is a dicey process, 4605 // and this approach is far more likely to get the corner cases right. 4606 if (CurContext->isDependentContext()) 4607 BaseInit = Init; 4608 } 4609 4610 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4611 BaseSpec->isVirtual(), 4612 InitRange.getBegin(), 4613 BaseInit.getAs<Expr>(), 4614 InitRange.getEnd(), EllipsisLoc); 4615 } 4616 4617 // Create a static_cast\<T&&>(expr). 4618 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 4619 if (T.isNull()) T = E->getType(); 4620 QualType TargetType = SemaRef.BuildReferenceType( 4621 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 4622 SourceLocation ExprLoc = E->getBeginLoc(); 4623 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 4624 TargetType, ExprLoc); 4625 4626 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 4627 SourceRange(ExprLoc, ExprLoc), 4628 E->getSourceRange()).get(); 4629 } 4630 4631 /// ImplicitInitializerKind - How an implicit base or member initializer should 4632 /// initialize its base or member. 4633 enum ImplicitInitializerKind { 4634 IIK_Default, 4635 IIK_Copy, 4636 IIK_Move, 4637 IIK_Inherit 4638 }; 4639 4640 static bool 4641 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4642 ImplicitInitializerKind ImplicitInitKind, 4643 CXXBaseSpecifier *BaseSpec, 4644 bool IsInheritedVirtualBase, 4645 CXXCtorInitializer *&CXXBaseInit) { 4646 InitializedEntity InitEntity 4647 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 4648 IsInheritedVirtualBase); 4649 4650 ExprResult BaseInit; 4651 4652 switch (ImplicitInitKind) { 4653 case IIK_Inherit: 4654 case IIK_Default: { 4655 InitializationKind InitKind 4656 = InitializationKind::CreateDefault(Constructor->getLocation()); 4657 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4658 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4659 break; 4660 } 4661 4662 case IIK_Move: 4663 case IIK_Copy: { 4664 bool Moving = ImplicitInitKind == IIK_Move; 4665 ParmVarDecl *Param = Constructor->getParamDecl(0); 4666 QualType ParamType = Param->getType().getNonReferenceType(); 4667 4668 Expr *CopyCtorArg = 4669 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4670 SourceLocation(), Param, false, 4671 Constructor->getLocation(), ParamType, 4672 VK_LValue, nullptr); 4673 4674 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 4675 4676 // Cast to the base class to avoid ambiguities. 4677 QualType ArgTy = 4678 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 4679 ParamType.getQualifiers()); 4680 4681 if (Moving) { 4682 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 4683 } 4684 4685 CXXCastPath BasePath; 4686 BasePath.push_back(BaseSpec); 4687 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 4688 CK_UncheckedDerivedToBase, 4689 Moving ? VK_XValue : VK_LValue, 4690 &BasePath).get(); 4691 4692 InitializationKind InitKind 4693 = InitializationKind::CreateDirect(Constructor->getLocation(), 4694 SourceLocation(), SourceLocation()); 4695 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 4696 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 4697 break; 4698 } 4699 } 4700 4701 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 4702 if (BaseInit.isInvalid()) 4703 return true; 4704 4705 CXXBaseInit = 4706 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4707 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 4708 SourceLocation()), 4709 BaseSpec->isVirtual(), 4710 SourceLocation(), 4711 BaseInit.getAs<Expr>(), 4712 SourceLocation(), 4713 SourceLocation()); 4714 4715 return false; 4716 } 4717 4718 static bool RefersToRValueRef(Expr *MemRef) { 4719 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 4720 return Referenced->getType()->isRValueReferenceType(); 4721 } 4722 4723 static bool 4724 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4725 ImplicitInitializerKind ImplicitInitKind, 4726 FieldDecl *Field, IndirectFieldDecl *Indirect, 4727 CXXCtorInitializer *&CXXMemberInit) { 4728 if (Field->isInvalidDecl()) 4729 return true; 4730 4731 SourceLocation Loc = Constructor->getLocation(); 4732 4733 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 4734 bool Moving = ImplicitInitKind == IIK_Move; 4735 ParmVarDecl *Param = Constructor->getParamDecl(0); 4736 QualType ParamType = Param->getType().getNonReferenceType(); 4737 4738 // Suppress copying zero-width bitfields. 4739 if (Field->isZeroLengthBitField(SemaRef.Context)) 4740 return false; 4741 4742 Expr *MemberExprBase = 4743 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4744 SourceLocation(), Param, false, 4745 Loc, ParamType, VK_LValue, nullptr); 4746 4747 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 4748 4749 if (Moving) { 4750 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 4751 } 4752 4753 // Build a reference to this field within the parameter. 4754 CXXScopeSpec SS; 4755 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 4756 Sema::LookupMemberName); 4757 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 4758 : cast<ValueDecl>(Field), AS_public); 4759 MemberLookup.resolveKind(); 4760 ExprResult CtorArg 4761 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 4762 ParamType, Loc, 4763 /*IsArrow=*/false, 4764 SS, 4765 /*TemplateKWLoc=*/SourceLocation(), 4766 /*FirstQualifierInScope=*/nullptr, 4767 MemberLookup, 4768 /*TemplateArgs=*/nullptr, 4769 /*S*/nullptr); 4770 if (CtorArg.isInvalid()) 4771 return true; 4772 4773 // C++11 [class.copy]p15: 4774 // - if a member m has rvalue reference type T&&, it is direct-initialized 4775 // with static_cast<T&&>(x.m); 4776 if (RefersToRValueRef(CtorArg.get())) { 4777 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 4778 } 4779 4780 InitializedEntity Entity = 4781 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4782 /*Implicit*/ true) 4783 : InitializedEntity::InitializeMember(Field, nullptr, 4784 /*Implicit*/ true); 4785 4786 // Direct-initialize to use the copy constructor. 4787 InitializationKind InitKind = 4788 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 4789 4790 Expr *CtorArgE = CtorArg.getAs<Expr>(); 4791 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE); 4792 ExprResult MemberInit = 4793 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1)); 4794 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4795 if (MemberInit.isInvalid()) 4796 return true; 4797 4798 if (Indirect) 4799 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4800 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4801 else 4802 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4803 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4804 return false; 4805 } 4806 4807 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 4808 "Unhandled implicit init kind!"); 4809 4810 QualType FieldBaseElementType = 4811 SemaRef.Context.getBaseElementType(Field->getType()); 4812 4813 if (FieldBaseElementType->isRecordType()) { 4814 InitializedEntity InitEntity = 4815 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4816 /*Implicit*/ true) 4817 : InitializedEntity::InitializeMember(Field, nullptr, 4818 /*Implicit*/ true); 4819 InitializationKind InitKind = 4820 InitializationKind::CreateDefault(Loc); 4821 4822 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4823 ExprResult MemberInit = 4824 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4825 4826 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4827 if (MemberInit.isInvalid()) 4828 return true; 4829 4830 if (Indirect) 4831 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4832 Indirect, Loc, 4833 Loc, 4834 MemberInit.get(), 4835 Loc); 4836 else 4837 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4838 Field, Loc, Loc, 4839 MemberInit.get(), 4840 Loc); 4841 return false; 4842 } 4843 4844 if (!Field->getParent()->isUnion()) { 4845 if (FieldBaseElementType->isReferenceType()) { 4846 SemaRef.Diag(Constructor->getLocation(), 4847 diag::err_uninitialized_member_in_ctor) 4848 << (int)Constructor->isImplicit() 4849 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4850 << 0 << Field->getDeclName(); 4851 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4852 return true; 4853 } 4854 4855 if (FieldBaseElementType.isConstQualified()) { 4856 SemaRef.Diag(Constructor->getLocation(), 4857 diag::err_uninitialized_member_in_ctor) 4858 << (int)Constructor->isImplicit() 4859 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4860 << 1 << Field->getDeclName(); 4861 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4862 return true; 4863 } 4864 } 4865 4866 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) { 4867 // ARC and Weak: 4868 // Default-initialize Objective-C pointers to NULL. 4869 CXXMemberInit 4870 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 4871 Loc, Loc, 4872 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 4873 Loc); 4874 return false; 4875 } 4876 4877 // Nothing to initialize. 4878 CXXMemberInit = nullptr; 4879 return false; 4880 } 4881 4882 namespace { 4883 struct BaseAndFieldInfo { 4884 Sema &S; 4885 CXXConstructorDecl *Ctor; 4886 bool AnyErrorsInInits; 4887 ImplicitInitializerKind IIK; 4888 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 4889 SmallVector<CXXCtorInitializer*, 8> AllToInit; 4890 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 4891 4892 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 4893 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 4894 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 4895 if (Ctor->getInheritedConstructor()) 4896 IIK = IIK_Inherit; 4897 else if (Generated && Ctor->isCopyConstructor()) 4898 IIK = IIK_Copy; 4899 else if (Generated && Ctor->isMoveConstructor()) 4900 IIK = IIK_Move; 4901 else 4902 IIK = IIK_Default; 4903 } 4904 4905 bool isImplicitCopyOrMove() const { 4906 switch (IIK) { 4907 case IIK_Copy: 4908 case IIK_Move: 4909 return true; 4910 4911 case IIK_Default: 4912 case IIK_Inherit: 4913 return false; 4914 } 4915 4916 llvm_unreachable("Invalid ImplicitInitializerKind!"); 4917 } 4918 4919 bool addFieldInitializer(CXXCtorInitializer *Init) { 4920 AllToInit.push_back(Init); 4921 4922 // Check whether this initializer makes the field "used". 4923 if (Init->getInit()->HasSideEffects(S.Context)) 4924 S.UnusedPrivateFields.remove(Init->getAnyMember()); 4925 4926 return false; 4927 } 4928 4929 bool isInactiveUnionMember(FieldDecl *Field) { 4930 RecordDecl *Record = Field->getParent(); 4931 if (!Record->isUnion()) 4932 return false; 4933 4934 if (FieldDecl *Active = 4935 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 4936 return Active != Field->getCanonicalDecl(); 4937 4938 // In an implicit copy or move constructor, ignore any in-class initializer. 4939 if (isImplicitCopyOrMove()) 4940 return true; 4941 4942 // If there's no explicit initialization, the field is active only if it 4943 // has an in-class initializer... 4944 if (Field->hasInClassInitializer()) 4945 return false; 4946 // ... or it's an anonymous struct or union whose class has an in-class 4947 // initializer. 4948 if (!Field->isAnonymousStructOrUnion()) 4949 return true; 4950 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 4951 return !FieldRD->hasInClassInitializer(); 4952 } 4953 4954 /// Determine whether the given field is, or is within, a union member 4955 /// that is inactive (because there was an initializer given for a different 4956 /// member of the union, or because the union was not initialized at all). 4957 bool isWithinInactiveUnionMember(FieldDecl *Field, 4958 IndirectFieldDecl *Indirect) { 4959 if (!Indirect) 4960 return isInactiveUnionMember(Field); 4961 4962 for (auto *C : Indirect->chain()) { 4963 FieldDecl *Field = dyn_cast<FieldDecl>(C); 4964 if (Field && isInactiveUnionMember(Field)) 4965 return true; 4966 } 4967 return false; 4968 } 4969 }; 4970 } 4971 4972 /// Determine whether the given type is an incomplete or zero-lenfgth 4973 /// array type. 4974 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 4975 if (T->isIncompleteArrayType()) 4976 return true; 4977 4978 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 4979 if (!ArrayT->getSize()) 4980 return true; 4981 4982 T = ArrayT->getElementType(); 4983 } 4984 4985 return false; 4986 } 4987 4988 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 4989 FieldDecl *Field, 4990 IndirectFieldDecl *Indirect = nullptr) { 4991 if (Field->isInvalidDecl()) 4992 return false; 4993 4994 // Overwhelmingly common case: we have a direct initializer for this field. 4995 if (CXXCtorInitializer *Init = 4996 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 4997 return Info.addFieldInitializer(Init); 4998 4999 // C++11 [class.base.init]p8: 5000 // if the entity is a non-static data member that has a 5001 // brace-or-equal-initializer and either 5002 // -- the constructor's class is a union and no other variant member of that 5003 // union is designated by a mem-initializer-id or 5004 // -- the constructor's class is not a union, and, if the entity is a member 5005 // of an anonymous union, no other member of that union is designated by 5006 // a mem-initializer-id, 5007 // the entity is initialized as specified in [dcl.init]. 5008 // 5009 // We also apply the same rules to handle anonymous structs within anonymous 5010 // unions. 5011 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 5012 return false; 5013 5014 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 5015 ExprResult DIE = 5016 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); 5017 if (DIE.isInvalid()) 5018 return true; 5019 5020 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true); 5021 SemaRef.checkInitializerLifetime(Entity, DIE.get()); 5022 5023 CXXCtorInitializer *Init; 5024 if (Indirect) 5025 Init = new (SemaRef.Context) 5026 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), 5027 SourceLocation(), DIE.get(), SourceLocation()); 5028 else 5029 Init = new (SemaRef.Context) 5030 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), 5031 SourceLocation(), DIE.get(), SourceLocation()); 5032 return Info.addFieldInitializer(Init); 5033 } 5034 5035 // Don't initialize incomplete or zero-length arrays. 5036 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 5037 return false; 5038 5039 // Don't try to build an implicit initializer if there were semantic 5040 // errors in any of the initializers (and therefore we might be 5041 // missing some that the user actually wrote). 5042 if (Info.AnyErrorsInInits) 5043 return false; 5044 5045 CXXCtorInitializer *Init = nullptr; 5046 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 5047 Indirect, Init)) 5048 return true; 5049 5050 if (!Init) 5051 return false; 5052 5053 return Info.addFieldInitializer(Init); 5054 } 5055 5056 bool 5057 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 5058 CXXCtorInitializer *Initializer) { 5059 assert(Initializer->isDelegatingInitializer()); 5060 Constructor->setNumCtorInitializers(1); 5061 CXXCtorInitializer **initializer = 5062 new (Context) CXXCtorInitializer*[1]; 5063 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 5064 Constructor->setCtorInitializers(initializer); 5065 5066 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 5067 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 5068 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 5069 } 5070 5071 DelegatingCtorDecls.push_back(Constructor); 5072 5073 DiagnoseUninitializedFields(*this, Constructor); 5074 5075 return false; 5076 } 5077 5078 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 5079 ArrayRef<CXXCtorInitializer *> Initializers) { 5080 if (Constructor->isDependentContext()) { 5081 // Just store the initializers as written, they will be checked during 5082 // instantiation. 5083 if (!Initializers.empty()) { 5084 Constructor->setNumCtorInitializers(Initializers.size()); 5085 CXXCtorInitializer **baseOrMemberInitializers = 5086 new (Context) CXXCtorInitializer*[Initializers.size()]; 5087 memcpy(baseOrMemberInitializers, Initializers.data(), 5088 Initializers.size() * sizeof(CXXCtorInitializer*)); 5089 Constructor->setCtorInitializers(baseOrMemberInitializers); 5090 } 5091 5092 // Let template instantiation know whether we had errors. 5093 if (AnyErrors) 5094 Constructor->setInvalidDecl(); 5095 5096 return false; 5097 } 5098 5099 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 5100 5101 // We need to build the initializer AST according to order of construction 5102 // and not what user specified in the Initializers list. 5103 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 5104 if (!ClassDecl) 5105 return true; 5106 5107 bool HadError = false; 5108 5109 for (unsigned i = 0; i < Initializers.size(); i++) { 5110 CXXCtorInitializer *Member = Initializers[i]; 5111 5112 if (Member->isBaseInitializer()) 5113 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 5114 else { 5115 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 5116 5117 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 5118 for (auto *C : F->chain()) { 5119 FieldDecl *FD = dyn_cast<FieldDecl>(C); 5120 if (FD && FD->getParent()->isUnion()) 5121 Info.ActiveUnionMember.insert(std::make_pair( 5122 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 5123 } 5124 } else if (FieldDecl *FD = Member->getMember()) { 5125 if (FD->getParent()->isUnion()) 5126 Info.ActiveUnionMember.insert(std::make_pair( 5127 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 5128 } 5129 } 5130 } 5131 5132 // Keep track of the direct virtual bases. 5133 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 5134 for (auto &I : ClassDecl->bases()) { 5135 if (I.isVirtual()) 5136 DirectVBases.insert(&I); 5137 } 5138 5139 // Push virtual bases before others. 5140 for (auto &VBase : ClassDecl->vbases()) { 5141 if (CXXCtorInitializer *Value 5142 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 5143 // [class.base.init]p7, per DR257: 5144 // A mem-initializer where the mem-initializer-id names a virtual base 5145 // class is ignored during execution of a constructor of any class that 5146 // is not the most derived class. 5147 if (ClassDecl->isAbstract()) { 5148 // FIXME: Provide a fixit to remove the base specifier. This requires 5149 // tracking the location of the associated comma for a base specifier. 5150 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 5151 << VBase.getType() << ClassDecl; 5152 DiagnoseAbstractType(ClassDecl); 5153 } 5154 5155 Info.AllToInit.push_back(Value); 5156 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 5157 // [class.base.init]p8, per DR257: 5158 // If a given [...] base class is not named by a mem-initializer-id 5159 // [...] and the entity is not a virtual base class of an abstract 5160 // class, then [...] the entity is default-initialized. 5161 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 5162 CXXCtorInitializer *CXXBaseInit; 5163 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 5164 &VBase, IsInheritedVirtualBase, 5165 CXXBaseInit)) { 5166 HadError = true; 5167 continue; 5168 } 5169 5170 Info.AllToInit.push_back(CXXBaseInit); 5171 } 5172 } 5173 5174 // Non-virtual bases. 5175 for (auto &Base : ClassDecl->bases()) { 5176 // Virtuals are in the virtual base list and already constructed. 5177 if (Base.isVirtual()) 5178 continue; 5179 5180 if (CXXCtorInitializer *Value 5181 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 5182 Info.AllToInit.push_back(Value); 5183 } else if (!AnyErrors) { 5184 CXXCtorInitializer *CXXBaseInit; 5185 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 5186 &Base, /*IsInheritedVirtualBase=*/false, 5187 CXXBaseInit)) { 5188 HadError = true; 5189 continue; 5190 } 5191 5192 Info.AllToInit.push_back(CXXBaseInit); 5193 } 5194 } 5195 5196 // Fields. 5197 for (auto *Mem : ClassDecl->decls()) { 5198 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 5199 // C++ [class.bit]p2: 5200 // A declaration for a bit-field that omits the identifier declares an 5201 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 5202 // initialized. 5203 if (F->isUnnamedBitfield()) 5204 continue; 5205 5206 // If we're not generating the implicit copy/move constructor, then we'll 5207 // handle anonymous struct/union fields based on their individual 5208 // indirect fields. 5209 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 5210 continue; 5211 5212 if (CollectFieldInitializer(*this, Info, F)) 5213 HadError = true; 5214 continue; 5215 } 5216 5217 // Beyond this point, we only consider default initialization. 5218 if (Info.isImplicitCopyOrMove()) 5219 continue; 5220 5221 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 5222 if (F->getType()->isIncompleteArrayType()) { 5223 assert(ClassDecl->hasFlexibleArrayMember() && 5224 "Incomplete array type is not valid"); 5225 continue; 5226 } 5227 5228 // Initialize each field of an anonymous struct individually. 5229 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 5230 HadError = true; 5231 5232 continue; 5233 } 5234 } 5235 5236 unsigned NumInitializers = Info.AllToInit.size(); 5237 if (NumInitializers > 0) { 5238 Constructor->setNumCtorInitializers(NumInitializers); 5239 CXXCtorInitializer **baseOrMemberInitializers = 5240 new (Context) CXXCtorInitializer*[NumInitializers]; 5241 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 5242 NumInitializers * sizeof(CXXCtorInitializer*)); 5243 Constructor->setCtorInitializers(baseOrMemberInitializers); 5244 5245 // Constructors implicitly reference the base and member 5246 // destructors. 5247 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 5248 Constructor->getParent()); 5249 } 5250 5251 return HadError; 5252 } 5253 5254 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 5255 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 5256 const RecordDecl *RD = RT->getDecl(); 5257 if (RD->isAnonymousStructOrUnion()) { 5258 for (auto *Field : RD->fields()) 5259 PopulateKeysForFields(Field, IdealInits); 5260 return; 5261 } 5262 } 5263 IdealInits.push_back(Field->getCanonicalDecl()); 5264 } 5265 5266 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 5267 return Context.getCanonicalType(BaseType).getTypePtr(); 5268 } 5269 5270 static const void *GetKeyForMember(ASTContext &Context, 5271 CXXCtorInitializer *Member) { 5272 if (!Member->isAnyMemberInitializer()) 5273 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 5274 5275 return Member->getAnyMember()->getCanonicalDecl(); 5276 } 5277 5278 static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag, 5279 const CXXCtorInitializer *Previous, 5280 const CXXCtorInitializer *Current) { 5281 if (Previous->isAnyMemberInitializer()) 5282 Diag << 0 << Previous->getAnyMember(); 5283 else 5284 Diag << 1 << Previous->getTypeSourceInfo()->getType(); 5285 5286 if (Current->isAnyMemberInitializer()) 5287 Diag << 0 << Current->getAnyMember(); 5288 else 5289 Diag << 1 << Current->getTypeSourceInfo()->getType(); 5290 } 5291 5292 static void DiagnoseBaseOrMemInitializerOrder( 5293 Sema &SemaRef, const CXXConstructorDecl *Constructor, 5294 ArrayRef<CXXCtorInitializer *> Inits) { 5295 if (Constructor->getDeclContext()->isDependentContext()) 5296 return; 5297 5298 // Don't check initializers order unless the warning is enabled at the 5299 // location of at least one initializer. 5300 bool ShouldCheckOrder = false; 5301 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 5302 CXXCtorInitializer *Init = Inits[InitIndex]; 5303 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 5304 Init->getSourceLocation())) { 5305 ShouldCheckOrder = true; 5306 break; 5307 } 5308 } 5309 if (!ShouldCheckOrder) 5310 return; 5311 5312 // Build the list of bases and members in the order that they'll 5313 // actually be initialized. The explicit initializers should be in 5314 // this same order but may be missing things. 5315 SmallVector<const void*, 32> IdealInitKeys; 5316 5317 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 5318 5319 // 1. Virtual bases. 5320 for (const auto &VBase : ClassDecl->vbases()) 5321 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 5322 5323 // 2. Non-virtual bases. 5324 for (const auto &Base : ClassDecl->bases()) { 5325 if (Base.isVirtual()) 5326 continue; 5327 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 5328 } 5329 5330 // 3. Direct fields. 5331 for (auto *Field : ClassDecl->fields()) { 5332 if (Field->isUnnamedBitfield()) 5333 continue; 5334 5335 PopulateKeysForFields(Field, IdealInitKeys); 5336 } 5337 5338 unsigned NumIdealInits = IdealInitKeys.size(); 5339 unsigned IdealIndex = 0; 5340 5341 // Track initializers that are in an incorrect order for either a warning or 5342 // note if multiple ones occur. 5343 SmallVector<unsigned> WarnIndexes; 5344 // Correlates the index of an initializer in the init-list to the index of 5345 // the field/base in the class. 5346 SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder; 5347 5348 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 5349 const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]); 5350 5351 // Scan forward to try to find this initializer in the idealized 5352 // initializers list. 5353 for (; IdealIndex != NumIdealInits; ++IdealIndex) 5354 if (InitKey == IdealInitKeys[IdealIndex]) 5355 break; 5356 5357 // If we didn't find this initializer, it must be because we 5358 // scanned past it on a previous iteration. That can only 5359 // happen if we're out of order; emit a warning. 5360 if (IdealIndex == NumIdealInits && InitIndex) { 5361 WarnIndexes.push_back(InitIndex); 5362 5363 // Move back to the initializer's location in the ideal list. 5364 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 5365 if (InitKey == IdealInitKeys[IdealIndex]) 5366 break; 5367 5368 assert(IdealIndex < NumIdealInits && 5369 "initializer not found in initializer list"); 5370 } 5371 CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex); 5372 } 5373 5374 if (WarnIndexes.empty()) 5375 return; 5376 5377 // Sort based on the ideal order, first in the pair. 5378 llvm::sort(CorrelatedInitOrder, 5379 [](auto &LHS, auto &RHS) { return LHS.first < RHS.first; }); 5380 5381 // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to 5382 // emit the diagnostic before we can try adding notes. 5383 { 5384 Sema::SemaDiagnosticBuilder D = SemaRef.Diag( 5385 Inits[WarnIndexes.front() - 1]->getSourceLocation(), 5386 WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order 5387 : diag::warn_some_initializers_out_of_order); 5388 5389 for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) { 5390 if (CorrelatedInitOrder[I].second == I) 5391 continue; 5392 // Ideally we would be using InsertFromRange here, but clang doesn't 5393 // appear to handle InsertFromRange correctly when the source range is 5394 // modified by another fix-it. 5395 D << FixItHint::CreateReplacement( 5396 Inits[I]->getSourceRange(), 5397 Lexer::getSourceText( 5398 CharSourceRange::getTokenRange( 5399 Inits[CorrelatedInitOrder[I].second]->getSourceRange()), 5400 SemaRef.getSourceManager(), SemaRef.getLangOpts())); 5401 } 5402 5403 // If there is only 1 item out of order, the warning expects the name and 5404 // type of each being added to it. 5405 if (WarnIndexes.size() == 1) { 5406 AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1], 5407 Inits[WarnIndexes.front()]); 5408 return; 5409 } 5410 } 5411 // More than 1 item to warn, create notes letting the user know which ones 5412 // are bad. 5413 for (unsigned WarnIndex : WarnIndexes) { 5414 const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1]; 5415 auto D = SemaRef.Diag(PrevInit->getSourceLocation(), 5416 diag::note_initializer_out_of_order); 5417 AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]); 5418 D << PrevInit->getSourceRange(); 5419 } 5420 } 5421 5422 namespace { 5423 bool CheckRedundantInit(Sema &S, 5424 CXXCtorInitializer *Init, 5425 CXXCtorInitializer *&PrevInit) { 5426 if (!PrevInit) { 5427 PrevInit = Init; 5428 return false; 5429 } 5430 5431 if (FieldDecl *Field = Init->getAnyMember()) 5432 S.Diag(Init->getSourceLocation(), 5433 diag::err_multiple_mem_initialization) 5434 << Field->getDeclName() 5435 << Init->getSourceRange(); 5436 else { 5437 const Type *BaseClass = Init->getBaseClass(); 5438 assert(BaseClass && "neither field nor base"); 5439 S.Diag(Init->getSourceLocation(), 5440 diag::err_multiple_base_initialization) 5441 << QualType(BaseClass, 0) 5442 << Init->getSourceRange(); 5443 } 5444 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 5445 << 0 << PrevInit->getSourceRange(); 5446 5447 return true; 5448 } 5449 5450 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 5451 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 5452 5453 bool CheckRedundantUnionInit(Sema &S, 5454 CXXCtorInitializer *Init, 5455 RedundantUnionMap &Unions) { 5456 FieldDecl *Field = Init->getAnyMember(); 5457 RecordDecl *Parent = Field->getParent(); 5458 NamedDecl *Child = Field; 5459 5460 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 5461 if (Parent->isUnion()) { 5462 UnionEntry &En = Unions[Parent]; 5463 if (En.first && En.first != Child) { 5464 S.Diag(Init->getSourceLocation(), 5465 diag::err_multiple_mem_union_initialization) 5466 << Field->getDeclName() 5467 << Init->getSourceRange(); 5468 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 5469 << 0 << En.second->getSourceRange(); 5470 return true; 5471 } 5472 if (!En.first) { 5473 En.first = Child; 5474 En.second = Init; 5475 } 5476 if (!Parent->isAnonymousStructOrUnion()) 5477 return false; 5478 } 5479 5480 Child = Parent; 5481 Parent = cast<RecordDecl>(Parent->getDeclContext()); 5482 } 5483 5484 return false; 5485 } 5486 } // namespace 5487 5488 /// ActOnMemInitializers - Handle the member initializers for a constructor. 5489 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 5490 SourceLocation ColonLoc, 5491 ArrayRef<CXXCtorInitializer*> MemInits, 5492 bool AnyErrors) { 5493 if (!ConstructorDecl) 5494 return; 5495 5496 AdjustDeclIfTemplate(ConstructorDecl); 5497 5498 CXXConstructorDecl *Constructor 5499 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 5500 5501 if (!Constructor) { 5502 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 5503 return; 5504 } 5505 5506 // Mapping for the duplicate initializers check. 5507 // For member initializers, this is keyed with a FieldDecl*. 5508 // For base initializers, this is keyed with a Type*. 5509 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 5510 5511 // Mapping for the inconsistent anonymous-union initializers check. 5512 RedundantUnionMap MemberUnions; 5513 5514 bool HadError = false; 5515 for (unsigned i = 0; i < MemInits.size(); i++) { 5516 CXXCtorInitializer *Init = MemInits[i]; 5517 5518 // Set the source order index. 5519 Init->setSourceOrder(i); 5520 5521 if (Init->isAnyMemberInitializer()) { 5522 const void *Key = GetKeyForMember(Context, Init); 5523 if (CheckRedundantInit(*this, Init, Members[Key]) || 5524 CheckRedundantUnionInit(*this, Init, MemberUnions)) 5525 HadError = true; 5526 } else if (Init->isBaseInitializer()) { 5527 const void *Key = GetKeyForMember(Context, Init); 5528 if (CheckRedundantInit(*this, Init, Members[Key])) 5529 HadError = true; 5530 } else { 5531 assert(Init->isDelegatingInitializer()); 5532 // This must be the only initializer 5533 if (MemInits.size() != 1) { 5534 Diag(Init->getSourceLocation(), 5535 diag::err_delegating_initializer_alone) 5536 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 5537 // We will treat this as being the only initializer. 5538 } 5539 SetDelegatingInitializer(Constructor, MemInits[i]); 5540 // Return immediately as the initializer is set. 5541 return; 5542 } 5543 } 5544 5545 if (HadError) 5546 return; 5547 5548 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 5549 5550 SetCtorInitializers(Constructor, AnyErrors, MemInits); 5551 5552 DiagnoseUninitializedFields(*this, Constructor); 5553 } 5554 5555 void 5556 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 5557 CXXRecordDecl *ClassDecl) { 5558 // Ignore dependent contexts. Also ignore unions, since their members never 5559 // have destructors implicitly called. 5560 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 5561 return; 5562 5563 // FIXME: all the access-control diagnostics are positioned on the 5564 // field/base declaration. That's probably good; that said, the 5565 // user might reasonably want to know why the destructor is being 5566 // emitted, and we currently don't say. 5567 5568 // Non-static data members. 5569 for (auto *Field : ClassDecl->fields()) { 5570 if (Field->isInvalidDecl()) 5571 continue; 5572 5573 // Don't destroy incomplete or zero-length arrays. 5574 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 5575 continue; 5576 5577 QualType FieldType = Context.getBaseElementType(Field->getType()); 5578 5579 const RecordType* RT = FieldType->getAs<RecordType>(); 5580 if (!RT) 5581 continue; 5582 5583 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5584 if (FieldClassDecl->isInvalidDecl()) 5585 continue; 5586 if (FieldClassDecl->hasIrrelevantDestructor()) 5587 continue; 5588 // The destructor for an implicit anonymous union member is never invoked. 5589 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 5590 continue; 5591 5592 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 5593 assert(Dtor && "No dtor found for FieldClassDecl!"); 5594 CheckDestructorAccess(Field->getLocation(), Dtor, 5595 PDiag(diag::err_access_dtor_field) 5596 << Field->getDeclName() 5597 << FieldType); 5598 5599 MarkFunctionReferenced(Location, Dtor); 5600 DiagnoseUseOfDecl(Dtor, Location); 5601 } 5602 5603 // We only potentially invoke the destructors of potentially constructed 5604 // subobjects. 5605 bool VisitVirtualBases = !ClassDecl->isAbstract(); 5606 5607 // If the destructor exists and has already been marked used in the MS ABI, 5608 // then virtual base destructors have already been checked and marked used. 5609 // Skip checking them again to avoid duplicate diagnostics. 5610 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 5611 CXXDestructorDecl *Dtor = ClassDecl->getDestructor(); 5612 if (Dtor && Dtor->isUsed()) 5613 VisitVirtualBases = false; 5614 } 5615 5616 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 5617 5618 // Bases. 5619 for (const auto &Base : ClassDecl->bases()) { 5620 const RecordType *RT = Base.getType()->getAs<RecordType>(); 5621 if (!RT) 5622 continue; 5623 5624 // Remember direct virtual bases. 5625 if (Base.isVirtual()) { 5626 if (!VisitVirtualBases) 5627 continue; 5628 DirectVirtualBases.insert(RT); 5629 } 5630 5631 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5632 // If our base class is invalid, we probably can't get its dtor anyway. 5633 if (BaseClassDecl->isInvalidDecl()) 5634 continue; 5635 if (BaseClassDecl->hasIrrelevantDestructor()) 5636 continue; 5637 5638 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5639 assert(Dtor && "No dtor found for BaseClassDecl!"); 5640 5641 // FIXME: caret should be on the start of the class name 5642 CheckDestructorAccess(Base.getBeginLoc(), Dtor, 5643 PDiag(diag::err_access_dtor_base) 5644 << Base.getType() << Base.getSourceRange(), 5645 Context.getTypeDeclType(ClassDecl)); 5646 5647 MarkFunctionReferenced(Location, Dtor); 5648 DiagnoseUseOfDecl(Dtor, Location); 5649 } 5650 5651 if (VisitVirtualBases) 5652 MarkVirtualBaseDestructorsReferenced(Location, ClassDecl, 5653 &DirectVirtualBases); 5654 } 5655 5656 void Sema::MarkVirtualBaseDestructorsReferenced( 5657 SourceLocation Location, CXXRecordDecl *ClassDecl, 5658 llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) { 5659 // Virtual bases. 5660 for (const auto &VBase : ClassDecl->vbases()) { 5661 // Bases are always records in a well-formed non-dependent class. 5662 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 5663 5664 // Ignore already visited direct virtual bases. 5665 if (DirectVirtualBases && DirectVirtualBases->count(RT)) 5666 continue; 5667 5668 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5669 // If our base class is invalid, we probably can't get its dtor anyway. 5670 if (BaseClassDecl->isInvalidDecl()) 5671 continue; 5672 if (BaseClassDecl->hasIrrelevantDestructor()) 5673 continue; 5674 5675 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5676 assert(Dtor && "No dtor found for BaseClassDecl!"); 5677 if (CheckDestructorAccess( 5678 ClassDecl->getLocation(), Dtor, 5679 PDiag(diag::err_access_dtor_vbase) 5680 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 5681 Context.getTypeDeclType(ClassDecl)) == 5682 AR_accessible) { 5683 CheckDerivedToBaseConversion( 5684 Context.getTypeDeclType(ClassDecl), VBase.getType(), 5685 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 5686 SourceRange(), DeclarationName(), nullptr); 5687 } 5688 5689 MarkFunctionReferenced(Location, Dtor); 5690 DiagnoseUseOfDecl(Dtor, Location); 5691 } 5692 } 5693 5694 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 5695 if (!CDtorDecl) 5696 return; 5697 5698 if (CXXConstructorDecl *Constructor 5699 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 5700 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 5701 DiagnoseUninitializedFields(*this, Constructor); 5702 } 5703 } 5704 5705 bool Sema::isAbstractType(SourceLocation Loc, QualType T) { 5706 if (!getLangOpts().CPlusPlus) 5707 return false; 5708 5709 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl(); 5710 if (!RD) 5711 return false; 5712 5713 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a 5714 // class template specialization here, but doing so breaks a lot of code. 5715 5716 // We can't answer whether something is abstract until it has a 5717 // definition. If it's currently being defined, we'll walk back 5718 // over all the declarations when we have a full definition. 5719 const CXXRecordDecl *Def = RD->getDefinition(); 5720 if (!Def || Def->isBeingDefined()) 5721 return false; 5722 5723 return RD->isAbstract(); 5724 } 5725 5726 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 5727 TypeDiagnoser &Diagnoser) { 5728 if (!isAbstractType(Loc, T)) 5729 return false; 5730 5731 T = Context.getBaseElementType(T); 5732 Diagnoser.diagnose(*this, Loc, T); 5733 DiagnoseAbstractType(T->getAsCXXRecordDecl()); 5734 return true; 5735 } 5736 5737 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 5738 // Check if we've already emitted the list of pure virtual functions 5739 // for this class. 5740 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 5741 return; 5742 5743 // If the diagnostic is suppressed, don't emit the notes. We're only 5744 // going to emit them once, so try to attach them to a diagnostic we're 5745 // actually going to show. 5746 if (Diags.isLastDiagnosticIgnored()) 5747 return; 5748 5749 CXXFinalOverriderMap FinalOverriders; 5750 RD->getFinalOverriders(FinalOverriders); 5751 5752 // Keep a set of seen pure methods so we won't diagnose the same method 5753 // more than once. 5754 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 5755 5756 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 5757 MEnd = FinalOverriders.end(); 5758 M != MEnd; 5759 ++M) { 5760 for (OverridingMethods::iterator SO = M->second.begin(), 5761 SOEnd = M->second.end(); 5762 SO != SOEnd; ++SO) { 5763 // C++ [class.abstract]p4: 5764 // A class is abstract if it contains or inherits at least one 5765 // pure virtual function for which the final overrider is pure 5766 // virtual. 5767 5768 // 5769 if (SO->second.size() != 1) 5770 continue; 5771 5772 if (!SO->second.front().Method->isPure()) 5773 continue; 5774 5775 if (!SeenPureMethods.insert(SO->second.front().Method).second) 5776 continue; 5777 5778 Diag(SO->second.front().Method->getLocation(), 5779 diag::note_pure_virtual_function) 5780 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 5781 } 5782 } 5783 5784 if (!PureVirtualClassDiagSet) 5785 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 5786 PureVirtualClassDiagSet->insert(RD); 5787 } 5788 5789 namespace { 5790 struct AbstractUsageInfo { 5791 Sema &S; 5792 CXXRecordDecl *Record; 5793 CanQualType AbstractType; 5794 bool Invalid; 5795 5796 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 5797 : S(S), Record(Record), 5798 AbstractType(S.Context.getCanonicalType( 5799 S.Context.getTypeDeclType(Record))), 5800 Invalid(false) {} 5801 5802 void DiagnoseAbstractType() { 5803 if (Invalid) return; 5804 S.DiagnoseAbstractType(Record); 5805 Invalid = true; 5806 } 5807 5808 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 5809 }; 5810 5811 struct CheckAbstractUsage { 5812 AbstractUsageInfo &Info; 5813 const NamedDecl *Ctx; 5814 5815 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 5816 : Info(Info), Ctx(Ctx) {} 5817 5818 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5819 switch (TL.getTypeLocClass()) { 5820 #define ABSTRACT_TYPELOC(CLASS, PARENT) 5821 #define TYPELOC(CLASS, PARENT) \ 5822 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 5823 #include "clang/AST/TypeLocNodes.def" 5824 } 5825 } 5826 5827 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5828 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 5829 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 5830 if (!TL.getParam(I)) 5831 continue; 5832 5833 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 5834 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 5835 } 5836 } 5837 5838 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5839 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 5840 } 5841 5842 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5843 // Visit the type parameters from a permissive context. 5844 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 5845 TemplateArgumentLoc TAL = TL.getArgLoc(I); 5846 if (TAL.getArgument().getKind() == TemplateArgument::Type) 5847 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 5848 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 5849 // TODO: other template argument types? 5850 } 5851 } 5852 5853 // Visit pointee types from a permissive context. 5854 #define CheckPolymorphic(Type) \ 5855 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 5856 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 5857 } 5858 CheckPolymorphic(PointerTypeLoc) 5859 CheckPolymorphic(ReferenceTypeLoc) 5860 CheckPolymorphic(MemberPointerTypeLoc) 5861 CheckPolymorphic(BlockPointerTypeLoc) 5862 CheckPolymorphic(AtomicTypeLoc) 5863 5864 /// Handle all the types we haven't given a more specific 5865 /// implementation for above. 5866 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5867 // Every other kind of type that we haven't called out already 5868 // that has an inner type is either (1) sugar or (2) contains that 5869 // inner type in some way as a subobject. 5870 if (TypeLoc Next = TL.getNextTypeLoc()) 5871 return Visit(Next, Sel); 5872 5873 // If there's no inner type and we're in a permissive context, 5874 // don't diagnose. 5875 if (Sel == Sema::AbstractNone) return; 5876 5877 // Check whether the type matches the abstract type. 5878 QualType T = TL.getType(); 5879 if (T->isArrayType()) { 5880 Sel = Sema::AbstractArrayType; 5881 T = Info.S.Context.getBaseElementType(T); 5882 } 5883 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 5884 if (CT != Info.AbstractType) return; 5885 5886 // It matched; do some magic. 5887 // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646. 5888 if (Sel == Sema::AbstractArrayType) { 5889 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 5890 << T << TL.getSourceRange(); 5891 } else { 5892 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 5893 << Sel << T << TL.getSourceRange(); 5894 } 5895 Info.DiagnoseAbstractType(); 5896 } 5897 }; 5898 5899 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 5900 Sema::AbstractDiagSelID Sel) { 5901 CheckAbstractUsage(*this, D).Visit(TL, Sel); 5902 } 5903 5904 } 5905 5906 /// Check for invalid uses of an abstract type in a function declaration. 5907 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5908 FunctionDecl *FD) { 5909 // No need to do the check on definitions, which require that 5910 // the return/param types be complete. 5911 if (FD->doesThisDeclarationHaveABody()) 5912 return; 5913 5914 // For safety's sake, just ignore it if we don't have type source 5915 // information. This should never happen for non-implicit methods, 5916 // but... 5917 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 5918 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractNone); 5919 } 5920 5921 /// Check for invalid uses of an abstract type in a variable0 declaration. 5922 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5923 VarDecl *VD) { 5924 // No need to do the check on definitions, which require that 5925 // the type is complete. 5926 if (VD->isThisDeclarationADefinition()) 5927 return; 5928 5929 Info.CheckType(VD, VD->getTypeSourceInfo()->getTypeLoc(), 5930 Sema::AbstractVariableType); 5931 } 5932 5933 /// Check for invalid uses of an abstract type within a class definition. 5934 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5935 CXXRecordDecl *RD) { 5936 for (auto *D : RD->decls()) { 5937 if (D->isImplicit()) continue; 5938 5939 // Step through friends to the befriended declaration. 5940 if (auto *FD = dyn_cast<FriendDecl>(D)) { 5941 D = FD->getFriendDecl(); 5942 if (!D) continue; 5943 } 5944 5945 // Functions and function templates. 5946 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 5947 CheckAbstractClassUsage(Info, FD); 5948 } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) { 5949 CheckAbstractClassUsage(Info, FTD->getTemplatedDecl()); 5950 5951 // Fields and static variables. 5952 } else if (auto *FD = dyn_cast<FieldDecl>(D)) { 5953 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 5954 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 5955 } else if (auto *VD = dyn_cast<VarDecl>(D)) { 5956 CheckAbstractClassUsage(Info, VD); 5957 } else if (auto *VTD = dyn_cast<VarTemplateDecl>(D)) { 5958 CheckAbstractClassUsage(Info, VTD->getTemplatedDecl()); 5959 5960 // Nested classes and class templates. 5961 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 5962 CheckAbstractClassUsage(Info, RD); 5963 } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(D)) { 5964 CheckAbstractClassUsage(Info, CTD->getTemplatedDecl()); 5965 } 5966 } 5967 } 5968 5969 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) { 5970 Attr *ClassAttr = getDLLAttr(Class); 5971 if (!ClassAttr) 5972 return; 5973 5974 assert(ClassAttr->getKind() == attr::DLLExport); 5975 5976 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5977 5978 if (TSK == TSK_ExplicitInstantiationDeclaration) 5979 // Don't go any further if this is just an explicit instantiation 5980 // declaration. 5981 return; 5982 5983 // Add a context note to explain how we got to any diagnostics produced below. 5984 struct MarkingClassDllexported { 5985 Sema &S; 5986 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class, 5987 SourceLocation AttrLoc) 5988 : S(S) { 5989 Sema::CodeSynthesisContext Ctx; 5990 Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported; 5991 Ctx.PointOfInstantiation = AttrLoc; 5992 Ctx.Entity = Class; 5993 S.pushCodeSynthesisContext(Ctx); 5994 } 5995 ~MarkingClassDllexported() { 5996 S.popCodeSynthesisContext(); 5997 } 5998 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation()); 5999 6000 if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) 6001 S.MarkVTableUsed(Class->getLocation(), Class, true); 6002 6003 for (Decl *Member : Class->decls()) { 6004 // Skip members that were not marked exported. 6005 if (!Member->hasAttr<DLLExportAttr>()) 6006 continue; 6007 6008 // Defined static variables that are members of an exported base 6009 // class must be marked export too. 6010 auto *VD = dyn_cast<VarDecl>(Member); 6011 if (VD && VD->getStorageClass() == SC_Static && 6012 TSK == TSK_ImplicitInstantiation) 6013 S.MarkVariableReferenced(VD->getLocation(), VD); 6014 6015 auto *MD = dyn_cast<CXXMethodDecl>(Member); 6016 if (!MD) 6017 continue; 6018 6019 if (MD->isUserProvided()) { 6020 // Instantiate non-default class member functions ... 6021 6022 // .. except for certain kinds of template specializations. 6023 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 6024 continue; 6025 6026 // If this is an MS ABI dllexport default constructor, instantiate any 6027 // default arguments. 6028 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) { 6029 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 6030 if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) { 6031 S.InstantiateDefaultCtorDefaultArgs(CD); 6032 } 6033 } 6034 6035 S.MarkFunctionReferenced(Class->getLocation(), MD); 6036 6037 // The function will be passed to the consumer when its definition is 6038 // encountered. 6039 } else if (MD->isExplicitlyDefaulted()) { 6040 // Synthesize and instantiate explicitly defaulted methods. 6041 S.MarkFunctionReferenced(Class->getLocation(), MD); 6042 6043 if (TSK != TSK_ExplicitInstantiationDefinition) { 6044 // Except for explicit instantiation defs, we will not see the 6045 // definition again later, so pass it to the consumer now. 6046 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 6047 } 6048 } else if (!MD->isTrivial() || 6049 MD->isCopyAssignmentOperator() || 6050 MD->isMoveAssignmentOperator()) { 6051 // Synthesize and instantiate non-trivial implicit methods, and the copy 6052 // and move assignment operators. The latter are exported even if they 6053 // are trivial, because the address of an operator can be taken and 6054 // should compare equal across libraries. 6055 S.MarkFunctionReferenced(Class->getLocation(), MD); 6056 6057 // There is no later point when we will see the definition of this 6058 // function, so pass it to the consumer now. 6059 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 6060 } 6061 } 6062 } 6063 6064 static void checkForMultipleExportedDefaultConstructors(Sema &S, 6065 CXXRecordDecl *Class) { 6066 // Only the MS ABI has default constructor closures, so we don't need to do 6067 // this semantic checking anywhere else. 6068 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft()) 6069 return; 6070 6071 CXXConstructorDecl *LastExportedDefaultCtor = nullptr; 6072 for (Decl *Member : Class->decls()) { 6073 // Look for exported default constructors. 6074 auto *CD = dyn_cast<CXXConstructorDecl>(Member); 6075 if (!CD || !CD->isDefaultConstructor()) 6076 continue; 6077 auto *Attr = CD->getAttr<DLLExportAttr>(); 6078 if (!Attr) 6079 continue; 6080 6081 // If the class is non-dependent, mark the default arguments as ODR-used so 6082 // that we can properly codegen the constructor closure. 6083 if (!Class->isDependentContext()) { 6084 for (ParmVarDecl *PD : CD->parameters()) { 6085 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD); 6086 S.DiscardCleanupsInEvaluationContext(); 6087 } 6088 } 6089 6090 if (LastExportedDefaultCtor) { 6091 S.Diag(LastExportedDefaultCtor->getLocation(), 6092 diag::err_attribute_dll_ambiguous_default_ctor) 6093 << Class; 6094 S.Diag(CD->getLocation(), diag::note_entity_declared_at) 6095 << CD->getDeclName(); 6096 return; 6097 } 6098 LastExportedDefaultCtor = CD; 6099 } 6100 } 6101 6102 static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S, 6103 CXXRecordDecl *Class) { 6104 bool ErrorReported = false; 6105 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S, 6106 ClassTemplateDecl *TD) { 6107 if (ErrorReported) 6108 return; 6109 S.Diag(TD->getLocation(), 6110 diag::err_cuda_device_builtin_surftex_cls_template) 6111 << /*surface*/ 0 << TD; 6112 ErrorReported = true; 6113 }; 6114 6115 ClassTemplateDecl *TD = Class->getDescribedClassTemplate(); 6116 if (!TD) { 6117 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class); 6118 if (!SD) { 6119 S.Diag(Class->getLocation(), 6120 diag::err_cuda_device_builtin_surftex_ref_decl) 6121 << /*surface*/ 0 << Class; 6122 S.Diag(Class->getLocation(), 6123 diag::note_cuda_device_builtin_surftex_should_be_template_class) 6124 << Class; 6125 return; 6126 } 6127 TD = SD->getSpecializedTemplate(); 6128 } 6129 6130 TemplateParameterList *Params = TD->getTemplateParameters(); 6131 unsigned N = Params->size(); 6132 6133 if (N != 2) { 6134 reportIllegalClassTemplate(S, TD); 6135 S.Diag(TD->getLocation(), 6136 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args) 6137 << TD << 2; 6138 } 6139 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 6140 reportIllegalClassTemplate(S, TD); 6141 S.Diag(TD->getLocation(), 6142 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6143 << TD << /*1st*/ 0 << /*type*/ 0; 6144 } 6145 if (N > 1) { 6146 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 6147 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 6148 reportIllegalClassTemplate(S, TD); 6149 S.Diag(TD->getLocation(), 6150 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6151 << TD << /*2nd*/ 1 << /*integer*/ 1; 6152 } 6153 } 6154 } 6155 6156 static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S, 6157 CXXRecordDecl *Class) { 6158 bool ErrorReported = false; 6159 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S, 6160 ClassTemplateDecl *TD) { 6161 if (ErrorReported) 6162 return; 6163 S.Diag(TD->getLocation(), 6164 diag::err_cuda_device_builtin_surftex_cls_template) 6165 << /*texture*/ 1 << TD; 6166 ErrorReported = true; 6167 }; 6168 6169 ClassTemplateDecl *TD = Class->getDescribedClassTemplate(); 6170 if (!TD) { 6171 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class); 6172 if (!SD) { 6173 S.Diag(Class->getLocation(), 6174 diag::err_cuda_device_builtin_surftex_ref_decl) 6175 << /*texture*/ 1 << Class; 6176 S.Diag(Class->getLocation(), 6177 diag::note_cuda_device_builtin_surftex_should_be_template_class) 6178 << Class; 6179 return; 6180 } 6181 TD = SD->getSpecializedTemplate(); 6182 } 6183 6184 TemplateParameterList *Params = TD->getTemplateParameters(); 6185 unsigned N = Params->size(); 6186 6187 if (N != 3) { 6188 reportIllegalClassTemplate(S, TD); 6189 S.Diag(TD->getLocation(), 6190 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args) 6191 << TD << 3; 6192 } 6193 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 6194 reportIllegalClassTemplate(S, TD); 6195 S.Diag(TD->getLocation(), 6196 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6197 << TD << /*1st*/ 0 << /*type*/ 0; 6198 } 6199 if (N > 1) { 6200 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 6201 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 6202 reportIllegalClassTemplate(S, TD); 6203 S.Diag(TD->getLocation(), 6204 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6205 << TD << /*2nd*/ 1 << /*integer*/ 1; 6206 } 6207 } 6208 if (N > 2) { 6209 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2)); 6210 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 6211 reportIllegalClassTemplate(S, TD); 6212 S.Diag(TD->getLocation(), 6213 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6214 << TD << /*3rd*/ 2 << /*integer*/ 1; 6215 } 6216 } 6217 } 6218 6219 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) { 6220 // Mark any compiler-generated routines with the implicit code_seg attribute. 6221 for (auto *Method : Class->methods()) { 6222 if (Method->isUserProvided()) 6223 continue; 6224 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true)) 6225 Method->addAttr(A); 6226 } 6227 } 6228 6229 /// Check class-level dllimport/dllexport attribute. 6230 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) { 6231 Attr *ClassAttr = getDLLAttr(Class); 6232 6233 // MSVC inherits DLL attributes to partial class template specializations. 6234 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) { 6235 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 6236 if (Attr *TemplateAttr = 6237 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 6238 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext())); 6239 A->setInherited(true); 6240 ClassAttr = A; 6241 } 6242 } 6243 } 6244 6245 if (!ClassAttr) 6246 return; 6247 6248 if (!Class->isExternallyVisible()) { 6249 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) 6250 << Class << ClassAttr; 6251 return; 6252 } 6253 6254 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && 6255 !ClassAttr->isInherited()) { 6256 // Diagnose dll attributes on members of class with dll attribute. 6257 for (Decl *Member : Class->decls()) { 6258 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 6259 continue; 6260 InheritableAttr *MemberAttr = getDLLAttr(Member); 6261 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 6262 continue; 6263 6264 Diag(MemberAttr->getLocation(), 6265 diag::err_attribute_dll_member_of_dll_class) 6266 << MemberAttr << ClassAttr; 6267 Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 6268 Member->setInvalidDecl(); 6269 } 6270 } 6271 6272 if (Class->getDescribedClassTemplate()) 6273 // Don't inherit dll attribute until the template is instantiated. 6274 return; 6275 6276 // The class is either imported or exported. 6277 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 6278 6279 // Check if this was a dllimport attribute propagated from a derived class to 6280 // a base class template specialization. We don't apply these attributes to 6281 // static data members. 6282 const bool PropagatedImport = 6283 !ClassExported && 6284 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate(); 6285 6286 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 6287 6288 // Ignore explicit dllexport on explicit class template instantiation 6289 // declarations, except in MinGW mode. 6290 if (ClassExported && !ClassAttr->isInherited() && 6291 TSK == TSK_ExplicitInstantiationDeclaration && 6292 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) { 6293 Class->dropAttr<DLLExportAttr>(); 6294 return; 6295 } 6296 6297 // Force declaration of implicit members so they can inherit the attribute. 6298 ForceDeclarationOfImplicitMembers(Class); 6299 6300 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 6301 // seem to be true in practice? 6302 6303 for (Decl *Member : Class->decls()) { 6304 VarDecl *VD = dyn_cast<VarDecl>(Member); 6305 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 6306 6307 // Only methods and static fields inherit the attributes. 6308 if (!VD && !MD) 6309 continue; 6310 6311 if (MD) { 6312 // Don't process deleted methods. 6313 if (MD->isDeleted()) 6314 continue; 6315 6316 if (MD->isInlined()) { 6317 // MinGW does not import or export inline methods. But do it for 6318 // template instantiations. 6319 if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() && 6320 TSK != TSK_ExplicitInstantiationDeclaration && 6321 TSK != TSK_ExplicitInstantiationDefinition) 6322 continue; 6323 6324 // MSVC versions before 2015 don't export the move assignment operators 6325 // and move constructor, so don't attempt to import/export them if 6326 // we have a definition. 6327 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD); 6328 if ((MD->isMoveAssignmentOperator() || 6329 (Ctor && Ctor->isMoveConstructor())) && 6330 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015)) 6331 continue; 6332 6333 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign 6334 // operator is exported anyway. 6335 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 6336 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial()) 6337 continue; 6338 } 6339 } 6340 6341 // Don't apply dllimport attributes to static data members of class template 6342 // instantiations when the attribute is propagated from a derived class. 6343 if (VD && PropagatedImport) 6344 continue; 6345 6346 if (!cast<NamedDecl>(Member)->isExternallyVisible()) 6347 continue; 6348 6349 if (!getDLLAttr(Member)) { 6350 InheritableAttr *NewAttr = nullptr; 6351 6352 // Do not export/import inline function when -fno-dllexport-inlines is 6353 // passed. But add attribute for later local static var check. 6354 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() && 6355 TSK != TSK_ExplicitInstantiationDeclaration && 6356 TSK != TSK_ExplicitInstantiationDefinition) { 6357 if (ClassExported) { 6358 NewAttr = ::new (getASTContext()) 6359 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr); 6360 } else { 6361 NewAttr = ::new (getASTContext()) 6362 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr); 6363 } 6364 } else { 6365 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6366 } 6367 6368 NewAttr->setInherited(true); 6369 Member->addAttr(NewAttr); 6370 6371 if (MD) { 6372 // Propagate DLLAttr to friend re-declarations of MD that have already 6373 // been constructed. 6374 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD; 6375 FD = FD->getPreviousDecl()) { 6376 if (FD->getFriendObjectKind() == Decl::FOK_None) 6377 continue; 6378 assert(!getDLLAttr(FD) && 6379 "friend re-decl should not already have a DLLAttr"); 6380 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6381 NewAttr->setInherited(true); 6382 FD->addAttr(NewAttr); 6383 } 6384 } 6385 } 6386 } 6387 6388 if (ClassExported) 6389 DelayedDllExportClasses.push_back(Class); 6390 } 6391 6392 /// Perform propagation of DLL attributes from a derived class to a 6393 /// templated base class for MS compatibility. 6394 void Sema::propagateDLLAttrToBaseClassTemplate( 6395 CXXRecordDecl *Class, Attr *ClassAttr, 6396 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 6397 if (getDLLAttr( 6398 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 6399 // If the base class template has a DLL attribute, don't try to change it. 6400 return; 6401 } 6402 6403 auto TSK = BaseTemplateSpec->getSpecializationKind(); 6404 if (!getDLLAttr(BaseTemplateSpec) && 6405 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration || 6406 TSK == TSK_ImplicitInstantiation)) { 6407 // The template hasn't been instantiated yet (or it has, but only as an 6408 // explicit instantiation declaration or implicit instantiation, which means 6409 // we haven't codegenned any members yet), so propagate the attribute. 6410 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6411 NewAttr->setInherited(true); 6412 BaseTemplateSpec->addAttr(NewAttr); 6413 6414 // If this was an import, mark that we propagated it from a derived class to 6415 // a base class template specialization. 6416 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr)) 6417 ImportAttr->setPropagatedToBaseTemplate(); 6418 6419 // If the template is already instantiated, checkDLLAttributeRedeclaration() 6420 // needs to be run again to work see the new attribute. Otherwise this will 6421 // get run whenever the template is instantiated. 6422 if (TSK != TSK_Undeclared) 6423 checkClassLevelDLLAttribute(BaseTemplateSpec); 6424 6425 return; 6426 } 6427 6428 if (getDLLAttr(BaseTemplateSpec)) { 6429 // The template has already been specialized or instantiated with an 6430 // attribute, explicitly or through propagation. We should not try to change 6431 // it. 6432 return; 6433 } 6434 6435 // The template was previously instantiated or explicitly specialized without 6436 // a dll attribute, It's too late for us to add an attribute, so warn that 6437 // this is unsupported. 6438 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 6439 << BaseTemplateSpec->isExplicitSpecialization(); 6440 Diag(ClassAttr->getLocation(), diag::note_attribute); 6441 if (BaseTemplateSpec->isExplicitSpecialization()) { 6442 Diag(BaseTemplateSpec->getLocation(), 6443 diag::note_template_class_explicit_specialization_was_here) 6444 << BaseTemplateSpec; 6445 } else { 6446 Diag(BaseTemplateSpec->getPointOfInstantiation(), 6447 diag::note_template_class_instantiation_was_here) 6448 << BaseTemplateSpec; 6449 } 6450 } 6451 6452 /// Determine the kind of defaulting that would be done for a given function. 6453 /// 6454 /// If the function is both a default constructor and a copy / move constructor 6455 /// (due to having a default argument for the first parameter), this picks 6456 /// CXXDefaultConstructor. 6457 /// 6458 /// FIXME: Check that case is properly handled by all callers. 6459 Sema::DefaultedFunctionKind 6460 Sema::getDefaultedFunctionKind(const FunctionDecl *FD) { 6461 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 6462 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 6463 if (Ctor->isDefaultConstructor()) 6464 return Sema::CXXDefaultConstructor; 6465 6466 if (Ctor->isCopyConstructor()) 6467 return Sema::CXXCopyConstructor; 6468 6469 if (Ctor->isMoveConstructor()) 6470 return Sema::CXXMoveConstructor; 6471 } 6472 6473 if (MD->isCopyAssignmentOperator()) 6474 return Sema::CXXCopyAssignment; 6475 6476 if (MD->isMoveAssignmentOperator()) 6477 return Sema::CXXMoveAssignment; 6478 6479 if (isa<CXXDestructorDecl>(FD)) 6480 return Sema::CXXDestructor; 6481 } 6482 6483 switch (FD->getDeclName().getCXXOverloadedOperator()) { 6484 case OO_EqualEqual: 6485 return DefaultedComparisonKind::Equal; 6486 6487 case OO_ExclaimEqual: 6488 return DefaultedComparisonKind::NotEqual; 6489 6490 case OO_Spaceship: 6491 // No point allowing this if <=> doesn't exist in the current language mode. 6492 if (!getLangOpts().CPlusPlus20) 6493 break; 6494 return DefaultedComparisonKind::ThreeWay; 6495 6496 case OO_Less: 6497 case OO_LessEqual: 6498 case OO_Greater: 6499 case OO_GreaterEqual: 6500 // No point allowing this if <=> doesn't exist in the current language mode. 6501 if (!getLangOpts().CPlusPlus20) 6502 break; 6503 return DefaultedComparisonKind::Relational; 6504 6505 default: 6506 break; 6507 } 6508 6509 // Not defaultable. 6510 return DefaultedFunctionKind(); 6511 } 6512 6513 static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD, 6514 SourceLocation DefaultLoc) { 6515 Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD); 6516 if (DFK.isComparison()) 6517 return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison()); 6518 6519 switch (DFK.asSpecialMember()) { 6520 case Sema::CXXDefaultConstructor: 6521 S.DefineImplicitDefaultConstructor(DefaultLoc, 6522 cast<CXXConstructorDecl>(FD)); 6523 break; 6524 case Sema::CXXCopyConstructor: 6525 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD)); 6526 break; 6527 case Sema::CXXCopyAssignment: 6528 S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD)); 6529 break; 6530 case Sema::CXXDestructor: 6531 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD)); 6532 break; 6533 case Sema::CXXMoveConstructor: 6534 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD)); 6535 break; 6536 case Sema::CXXMoveAssignment: 6537 S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD)); 6538 break; 6539 case Sema::CXXInvalid: 6540 llvm_unreachable("Invalid special member."); 6541 } 6542 } 6543 6544 /// Determine whether a type is permitted to be passed or returned in 6545 /// registers, per C++ [class.temporary]p3. 6546 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D, 6547 TargetInfo::CallingConvKind CCK) { 6548 if (D->isDependentType() || D->isInvalidDecl()) 6549 return false; 6550 6551 // Clang <= 4 used the pre-C++11 rule, which ignores move operations. 6552 // The PS4 platform ABI follows the behavior of Clang 3.2. 6553 if (CCK == TargetInfo::CCK_ClangABI4OrPS4) 6554 return !D->hasNonTrivialDestructorForCall() && 6555 !D->hasNonTrivialCopyConstructorForCall(); 6556 6557 if (CCK == TargetInfo::CCK_MicrosoftWin64) { 6558 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false; 6559 bool DtorIsTrivialForCall = false; 6560 6561 // If a class has at least one non-deleted, trivial copy constructor, it 6562 // is passed according to the C ABI. Otherwise, it is passed indirectly. 6563 // 6564 // Note: This permits classes with non-trivial copy or move ctors to be 6565 // passed in registers, so long as they *also* have a trivial copy ctor, 6566 // which is non-conforming. 6567 if (D->needsImplicitCopyConstructor()) { 6568 if (!D->defaultedCopyConstructorIsDeleted()) { 6569 if (D->hasTrivialCopyConstructor()) 6570 CopyCtorIsTrivial = true; 6571 if (D->hasTrivialCopyConstructorForCall()) 6572 CopyCtorIsTrivialForCall = true; 6573 } 6574 } else { 6575 for (const CXXConstructorDecl *CD : D->ctors()) { 6576 if (CD->isCopyConstructor() && !CD->isDeleted()) { 6577 if (CD->isTrivial()) 6578 CopyCtorIsTrivial = true; 6579 if (CD->isTrivialForCall()) 6580 CopyCtorIsTrivialForCall = true; 6581 } 6582 } 6583 } 6584 6585 if (D->needsImplicitDestructor()) { 6586 if (!D->defaultedDestructorIsDeleted() && 6587 D->hasTrivialDestructorForCall()) 6588 DtorIsTrivialForCall = true; 6589 } else if (const auto *DD = D->getDestructor()) { 6590 if (!DD->isDeleted() && DD->isTrivialForCall()) 6591 DtorIsTrivialForCall = true; 6592 } 6593 6594 // If the copy ctor and dtor are both trivial-for-calls, pass direct. 6595 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall) 6596 return true; 6597 6598 // If a class has a destructor, we'd really like to pass it indirectly 6599 // because it allows us to elide copies. Unfortunately, MSVC makes that 6600 // impossible for small types, which it will pass in a single register or 6601 // stack slot. Most objects with dtors are large-ish, so handle that early. 6602 // We can't call out all large objects as being indirect because there are 6603 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate 6604 // how we pass large POD types. 6605 6606 // Note: This permits small classes with nontrivial destructors to be 6607 // passed in registers, which is non-conforming. 6608 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64(); 6609 uint64_t TypeSize = isAArch64 ? 128 : 64; 6610 6611 if (CopyCtorIsTrivial && 6612 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize) 6613 return true; 6614 return false; 6615 } 6616 6617 // Per C++ [class.temporary]p3, the relevant condition is: 6618 // each copy constructor, move constructor, and destructor of X is 6619 // either trivial or deleted, and X has at least one non-deleted copy 6620 // or move constructor 6621 bool HasNonDeletedCopyOrMove = false; 6622 6623 if (D->needsImplicitCopyConstructor() && 6624 !D->defaultedCopyConstructorIsDeleted()) { 6625 if (!D->hasTrivialCopyConstructorForCall()) 6626 return false; 6627 HasNonDeletedCopyOrMove = true; 6628 } 6629 6630 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() && 6631 !D->defaultedMoveConstructorIsDeleted()) { 6632 if (!D->hasTrivialMoveConstructorForCall()) 6633 return false; 6634 HasNonDeletedCopyOrMove = true; 6635 } 6636 6637 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() && 6638 !D->hasTrivialDestructorForCall()) 6639 return false; 6640 6641 for (const CXXMethodDecl *MD : D->methods()) { 6642 if (MD->isDeleted()) 6643 continue; 6644 6645 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 6646 if (CD && CD->isCopyOrMoveConstructor()) 6647 HasNonDeletedCopyOrMove = true; 6648 else if (!isa<CXXDestructorDecl>(MD)) 6649 continue; 6650 6651 if (!MD->isTrivialForCall()) 6652 return false; 6653 } 6654 6655 return HasNonDeletedCopyOrMove; 6656 } 6657 6658 /// Report an error regarding overriding, along with any relevant 6659 /// overridden methods. 6660 /// 6661 /// \param DiagID the primary error to report. 6662 /// \param MD the overriding method. 6663 static bool 6664 ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD, 6665 llvm::function_ref<bool(const CXXMethodDecl *)> Report) { 6666 bool IssuedDiagnostic = false; 6667 for (const CXXMethodDecl *O : MD->overridden_methods()) { 6668 if (Report(O)) { 6669 if (!IssuedDiagnostic) { 6670 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 6671 IssuedDiagnostic = true; 6672 } 6673 S.Diag(O->getLocation(), diag::note_overridden_virtual_function); 6674 } 6675 } 6676 return IssuedDiagnostic; 6677 } 6678 6679 /// Perform semantic checks on a class definition that has been 6680 /// completing, introducing implicitly-declared members, checking for 6681 /// abstract types, etc. 6682 /// 6683 /// \param S The scope in which the class was parsed. Null if we didn't just 6684 /// parse a class definition. 6685 /// \param Record The completed class. 6686 void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) { 6687 if (!Record) 6688 return; 6689 6690 if (Record->isAbstract() && !Record->isInvalidDecl()) { 6691 AbstractUsageInfo Info(*this, Record); 6692 CheckAbstractClassUsage(Info, Record); 6693 } 6694 6695 // If this is not an aggregate type and has no user-declared constructor, 6696 // complain about any non-static data members of reference or const scalar 6697 // type, since they will never get initializers. 6698 if (!Record->isInvalidDecl() && !Record->isDependentType() && 6699 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 6700 !Record->isLambda()) { 6701 bool Complained = false; 6702 for (const auto *F : Record->fields()) { 6703 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 6704 continue; 6705 6706 if (F->getType()->isReferenceType() || 6707 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 6708 if (!Complained) { 6709 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 6710 << Record->getTagKind() << Record; 6711 Complained = true; 6712 } 6713 6714 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 6715 << F->getType()->isReferenceType() 6716 << F->getDeclName(); 6717 } 6718 } 6719 } 6720 6721 if (Record->getIdentifier()) { 6722 // C++ [class.mem]p13: 6723 // If T is the name of a class, then each of the following shall have a 6724 // name different from T: 6725 // - every member of every anonymous union that is a member of class T. 6726 // 6727 // C++ [class.mem]p14: 6728 // In addition, if class T has a user-declared constructor (12.1), every 6729 // non-static data member of class T shall have a name different from T. 6730 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 6731 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 6732 ++I) { 6733 NamedDecl *D = (*I)->getUnderlyingDecl(); 6734 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) && 6735 Record->hasUserDeclaredConstructor()) || 6736 isa<IndirectFieldDecl>(D)) { 6737 Diag((*I)->getLocation(), diag::err_member_name_of_class) 6738 << D->getDeclName(); 6739 break; 6740 } 6741 } 6742 } 6743 6744 // Warn if the class has virtual methods but non-virtual public destructor. 6745 if (Record->isPolymorphic() && !Record->isDependentType()) { 6746 CXXDestructorDecl *dtor = Record->getDestructor(); 6747 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 6748 !Record->hasAttr<FinalAttr>()) 6749 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 6750 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 6751 } 6752 6753 if (Record->isAbstract()) { 6754 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 6755 Diag(Record->getLocation(), diag::warn_abstract_final_class) 6756 << FA->isSpelledAsSealed(); 6757 DiagnoseAbstractType(Record); 6758 } 6759 } 6760 6761 // Warn if the class has a final destructor but is not itself marked final. 6762 if (!Record->hasAttr<FinalAttr>()) { 6763 if (const CXXDestructorDecl *dtor = Record->getDestructor()) { 6764 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) { 6765 Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class) 6766 << FA->isSpelledAsSealed() 6767 << FixItHint::CreateInsertion( 6768 getLocForEndOfToken(Record->getLocation()), 6769 (FA->isSpelledAsSealed() ? " sealed" : " final")); 6770 Diag(Record->getLocation(), 6771 diag::note_final_dtor_non_final_class_silence) 6772 << Context.getRecordType(Record) << FA->isSpelledAsSealed(); 6773 } 6774 } 6775 } 6776 6777 // See if trivial_abi has to be dropped. 6778 if (Record->hasAttr<TrivialABIAttr>()) 6779 checkIllFormedTrivialABIStruct(*Record); 6780 6781 // Set HasTrivialSpecialMemberForCall if the record has attribute 6782 // "trivial_abi". 6783 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>(); 6784 6785 if (HasTrivialABI) 6786 Record->setHasTrivialSpecialMemberForCall(); 6787 6788 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=). 6789 // We check these last because they can depend on the properties of the 6790 // primary comparison functions (==, <=>). 6791 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons; 6792 6793 // Perform checks that can't be done until we know all the properties of a 6794 // member function (whether it's defaulted, deleted, virtual, overriding, 6795 // ...). 6796 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) { 6797 // A static function cannot override anything. 6798 if (MD->getStorageClass() == SC_Static) { 6799 if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD, 6800 [](const CXXMethodDecl *) { return true; })) 6801 return; 6802 } 6803 6804 // A deleted function cannot override a non-deleted function and vice 6805 // versa. 6806 if (ReportOverrides(*this, 6807 MD->isDeleted() ? diag::err_deleted_override 6808 : diag::err_non_deleted_override, 6809 MD, [&](const CXXMethodDecl *V) { 6810 return MD->isDeleted() != V->isDeleted(); 6811 })) { 6812 if (MD->isDefaulted() && MD->isDeleted()) 6813 // Explain why this defaulted function was deleted. 6814 DiagnoseDeletedDefaultedFunction(MD); 6815 return; 6816 } 6817 6818 // A consteval function cannot override a non-consteval function and vice 6819 // versa. 6820 if (ReportOverrides(*this, 6821 MD->isConsteval() ? diag::err_consteval_override 6822 : diag::err_non_consteval_override, 6823 MD, [&](const CXXMethodDecl *V) { 6824 return MD->isConsteval() != V->isConsteval(); 6825 })) { 6826 if (MD->isDefaulted() && MD->isDeleted()) 6827 // Explain why this defaulted function was deleted. 6828 DiagnoseDeletedDefaultedFunction(MD); 6829 return; 6830 } 6831 }; 6832 6833 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool { 6834 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted()) 6835 return false; 6836 6837 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD); 6838 if (DFK.asComparison() == DefaultedComparisonKind::NotEqual || 6839 DFK.asComparison() == DefaultedComparisonKind::Relational) { 6840 DefaultedSecondaryComparisons.push_back(FD); 6841 return true; 6842 } 6843 6844 CheckExplicitlyDefaultedFunction(S, FD); 6845 return false; 6846 }; 6847 6848 auto CompleteMemberFunction = [&](CXXMethodDecl *M) { 6849 // Check whether the explicitly-defaulted members are valid. 6850 bool Incomplete = CheckForDefaultedFunction(M); 6851 6852 // Skip the rest of the checks for a member of a dependent class. 6853 if (Record->isDependentType()) 6854 return; 6855 6856 // For an explicitly defaulted or deleted special member, we defer 6857 // determining triviality until the class is complete. That time is now! 6858 CXXSpecialMember CSM = getSpecialMember(M); 6859 if (!M->isImplicit() && !M->isUserProvided()) { 6860 if (CSM != CXXInvalid) { 6861 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 6862 // Inform the class that we've finished declaring this member. 6863 Record->finishedDefaultedOrDeletedMember(M); 6864 M->setTrivialForCall( 6865 HasTrivialABI || 6866 SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI)); 6867 Record->setTrivialForCallFlags(M); 6868 } 6869 } 6870 6871 // Set triviality for the purpose of calls if this is a user-provided 6872 // copy/move constructor or destructor. 6873 if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor || 6874 CSM == CXXDestructor) && M->isUserProvided()) { 6875 M->setTrivialForCall(HasTrivialABI); 6876 Record->setTrivialForCallFlags(M); 6877 } 6878 6879 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() && 6880 M->hasAttr<DLLExportAttr>()) { 6881 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 6882 M->isTrivial() && 6883 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor || 6884 CSM == CXXDestructor)) 6885 M->dropAttr<DLLExportAttr>(); 6886 6887 if (M->hasAttr<DLLExportAttr>()) { 6888 // Define after any fields with in-class initializers have been parsed. 6889 DelayedDllExportMemberFunctions.push_back(M); 6890 } 6891 } 6892 6893 // Define defaulted constexpr virtual functions that override a base class 6894 // function right away. 6895 // FIXME: We can defer doing this until the vtable is marked as used. 6896 if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods()) 6897 DefineDefaultedFunction(*this, M, M->getLocation()); 6898 6899 if (!Incomplete) 6900 CheckCompletedMemberFunction(M); 6901 }; 6902 6903 // Check the destructor before any other member function. We need to 6904 // determine whether it's trivial in order to determine whether the claas 6905 // type is a literal type, which is a prerequisite for determining whether 6906 // other special member functions are valid and whether they're implicitly 6907 // 'constexpr'. 6908 if (CXXDestructorDecl *Dtor = Record->getDestructor()) 6909 CompleteMemberFunction(Dtor); 6910 6911 bool HasMethodWithOverrideControl = false, 6912 HasOverridingMethodWithoutOverrideControl = false; 6913 for (auto *D : Record->decls()) { 6914 if (auto *M = dyn_cast<CXXMethodDecl>(D)) { 6915 // FIXME: We could do this check for dependent types with non-dependent 6916 // bases. 6917 if (!Record->isDependentType()) { 6918 // See if a method overloads virtual methods in a base 6919 // class without overriding any. 6920 if (!M->isStatic()) 6921 DiagnoseHiddenVirtualMethods(M); 6922 if (M->hasAttr<OverrideAttr>()) 6923 HasMethodWithOverrideControl = true; 6924 else if (M->size_overridden_methods() > 0) 6925 HasOverridingMethodWithoutOverrideControl = true; 6926 } 6927 6928 if (!isa<CXXDestructorDecl>(M)) 6929 CompleteMemberFunction(M); 6930 } else if (auto *F = dyn_cast<FriendDecl>(D)) { 6931 CheckForDefaultedFunction( 6932 dyn_cast_or_null<FunctionDecl>(F->getFriendDecl())); 6933 } 6934 } 6935 6936 if (HasOverridingMethodWithoutOverrideControl) { 6937 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl; 6938 for (auto *M : Record->methods()) 6939 DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl); 6940 } 6941 6942 // Check the defaulted secondary comparisons after any other member functions. 6943 for (FunctionDecl *FD : DefaultedSecondaryComparisons) { 6944 CheckExplicitlyDefaultedFunction(S, FD); 6945 6946 // If this is a member function, we deferred checking it until now. 6947 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) 6948 CheckCompletedMemberFunction(MD); 6949 } 6950 6951 // ms_struct is a request to use the same ABI rules as MSVC. Check 6952 // whether this class uses any C++ features that are implemented 6953 // completely differently in MSVC, and if so, emit a diagnostic. 6954 // That diagnostic defaults to an error, but we allow projects to 6955 // map it down to a warning (or ignore it). It's a fairly common 6956 // practice among users of the ms_struct pragma to mass-annotate 6957 // headers, sweeping up a bunch of types that the project doesn't 6958 // really rely on MSVC-compatible layout for. We must therefore 6959 // support "ms_struct except for C++ stuff" as a secondary ABI. 6960 // Don't emit this diagnostic if the feature was enabled as a 6961 // language option (as opposed to via a pragma or attribute), as 6962 // the option -mms-bitfields otherwise essentially makes it impossible 6963 // to build C++ code, unless this diagnostic is turned off. 6964 if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields && 6965 (Record->isPolymorphic() || Record->getNumBases())) { 6966 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 6967 } 6968 6969 checkClassLevelDLLAttribute(Record); 6970 checkClassLevelCodeSegAttribute(Record); 6971 6972 bool ClangABICompat4 = 6973 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4; 6974 TargetInfo::CallingConvKind CCK = 6975 Context.getTargetInfo().getCallingConvKind(ClangABICompat4); 6976 bool CanPass = canPassInRegisters(*this, Record, CCK); 6977 6978 // Do not change ArgPassingRestrictions if it has already been set to 6979 // APK_CanNeverPassInRegs. 6980 if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs) 6981 Record->setArgPassingRestrictions(CanPass 6982 ? RecordDecl::APK_CanPassInRegs 6983 : RecordDecl::APK_CannotPassInRegs); 6984 6985 // If canPassInRegisters returns true despite the record having a non-trivial 6986 // destructor, the record is destructed in the callee. This happens only when 6987 // the record or one of its subobjects has a field annotated with trivial_abi 6988 // or a field qualified with ObjC __strong/__weak. 6989 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee()) 6990 Record->setParamDestroyedInCallee(true); 6991 else if (Record->hasNonTrivialDestructor()) 6992 Record->setParamDestroyedInCallee(CanPass); 6993 6994 if (getLangOpts().ForceEmitVTables) { 6995 // If we want to emit all the vtables, we need to mark it as used. This 6996 // is especially required for cases like vtable assumption loads. 6997 MarkVTableUsed(Record->getInnerLocStart(), Record); 6998 } 6999 7000 if (getLangOpts().CUDA) { 7001 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>()) 7002 checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record); 7003 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>()) 7004 checkCUDADeviceBuiltinTextureClassTemplate(*this, Record); 7005 } 7006 } 7007 7008 /// Look up the special member function that would be called by a special 7009 /// member function for a subobject of class type. 7010 /// 7011 /// \param Class The class type of the subobject. 7012 /// \param CSM The kind of special member function. 7013 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 7014 /// \param ConstRHS True if this is a copy operation with a const object 7015 /// on its RHS, that is, if the argument to the outer special member 7016 /// function is 'const' and this is not a field marked 'mutable'. 7017 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember( 7018 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 7019 unsigned FieldQuals, bool ConstRHS) { 7020 unsigned LHSQuals = 0; 7021 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 7022 LHSQuals = FieldQuals; 7023 7024 unsigned RHSQuals = FieldQuals; 7025 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 7026 RHSQuals = 0; 7027 else if (ConstRHS) 7028 RHSQuals |= Qualifiers::Const; 7029 7030 return S.LookupSpecialMember(Class, CSM, 7031 RHSQuals & Qualifiers::Const, 7032 RHSQuals & Qualifiers::Volatile, 7033 false, 7034 LHSQuals & Qualifiers::Const, 7035 LHSQuals & Qualifiers::Volatile); 7036 } 7037 7038 class Sema::InheritedConstructorInfo { 7039 Sema &S; 7040 SourceLocation UseLoc; 7041 7042 /// A mapping from the base classes through which the constructor was 7043 /// inherited to the using shadow declaration in that base class (or a null 7044 /// pointer if the constructor was declared in that base class). 7045 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *> 7046 InheritedFromBases; 7047 7048 public: 7049 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, 7050 ConstructorUsingShadowDecl *Shadow) 7051 : S(S), UseLoc(UseLoc) { 7052 bool DiagnosedMultipleConstructedBases = false; 7053 CXXRecordDecl *ConstructedBase = nullptr; 7054 BaseUsingDecl *ConstructedBaseIntroducer = nullptr; 7055 7056 // Find the set of such base class subobjects and check that there's a 7057 // unique constructed subobject. 7058 for (auto *D : Shadow->redecls()) { 7059 auto *DShadow = cast<ConstructorUsingShadowDecl>(D); 7060 auto *DNominatedBase = DShadow->getNominatedBaseClass(); 7061 auto *DConstructedBase = DShadow->getConstructedBaseClass(); 7062 7063 InheritedFromBases.insert( 7064 std::make_pair(DNominatedBase->getCanonicalDecl(), 7065 DShadow->getNominatedBaseClassShadowDecl())); 7066 if (DShadow->constructsVirtualBase()) 7067 InheritedFromBases.insert( 7068 std::make_pair(DConstructedBase->getCanonicalDecl(), 7069 DShadow->getConstructedBaseClassShadowDecl())); 7070 else 7071 assert(DNominatedBase == DConstructedBase); 7072 7073 // [class.inhctor.init]p2: 7074 // If the constructor was inherited from multiple base class subobjects 7075 // of type B, the program is ill-formed. 7076 if (!ConstructedBase) { 7077 ConstructedBase = DConstructedBase; 7078 ConstructedBaseIntroducer = D->getIntroducer(); 7079 } else if (ConstructedBase != DConstructedBase && 7080 !Shadow->isInvalidDecl()) { 7081 if (!DiagnosedMultipleConstructedBases) { 7082 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor) 7083 << Shadow->getTargetDecl(); 7084 S.Diag(ConstructedBaseIntroducer->getLocation(), 7085 diag::note_ambiguous_inherited_constructor_using) 7086 << ConstructedBase; 7087 DiagnosedMultipleConstructedBases = true; 7088 } 7089 S.Diag(D->getIntroducer()->getLocation(), 7090 diag::note_ambiguous_inherited_constructor_using) 7091 << DConstructedBase; 7092 } 7093 } 7094 7095 if (DiagnosedMultipleConstructedBases) 7096 Shadow->setInvalidDecl(); 7097 } 7098 7099 /// Find the constructor to use for inherited construction of a base class, 7100 /// and whether that base class constructor inherits the constructor from a 7101 /// virtual base class (in which case it won't actually invoke it). 7102 std::pair<CXXConstructorDecl *, bool> 7103 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const { 7104 auto It = InheritedFromBases.find(Base->getCanonicalDecl()); 7105 if (It == InheritedFromBases.end()) 7106 return std::make_pair(nullptr, false); 7107 7108 // This is an intermediary class. 7109 if (It->second) 7110 return std::make_pair( 7111 S.findInheritingConstructor(UseLoc, Ctor, It->second), 7112 It->second->constructsVirtualBase()); 7113 7114 // This is the base class from which the constructor was inherited. 7115 return std::make_pair(Ctor, false); 7116 } 7117 }; 7118 7119 /// Is the special member function which would be selected to perform the 7120 /// specified operation on the specified class type a constexpr constructor? 7121 static bool 7122 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 7123 Sema::CXXSpecialMember CSM, unsigned Quals, 7124 bool ConstRHS, 7125 CXXConstructorDecl *InheritedCtor = nullptr, 7126 Sema::InheritedConstructorInfo *Inherited = nullptr) { 7127 // If we're inheriting a constructor, see if we need to call it for this base 7128 // class. 7129 if (InheritedCtor) { 7130 assert(CSM == Sema::CXXDefaultConstructor); 7131 auto BaseCtor = 7132 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first; 7133 if (BaseCtor) 7134 return BaseCtor->isConstexpr(); 7135 } 7136 7137 if (CSM == Sema::CXXDefaultConstructor) 7138 return ClassDecl->hasConstexprDefaultConstructor(); 7139 if (CSM == Sema::CXXDestructor) 7140 return ClassDecl->hasConstexprDestructor(); 7141 7142 Sema::SpecialMemberOverloadResult SMOR = 7143 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 7144 if (!SMOR.getMethod()) 7145 // A constructor we wouldn't select can't be "involved in initializing" 7146 // anything. 7147 return true; 7148 return SMOR.getMethod()->isConstexpr(); 7149 } 7150 7151 /// Determine whether the specified special member function would be constexpr 7152 /// if it were implicitly defined. 7153 static bool defaultedSpecialMemberIsConstexpr( 7154 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, 7155 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr, 7156 Sema::InheritedConstructorInfo *Inherited = nullptr) { 7157 if (!S.getLangOpts().CPlusPlus11) 7158 return false; 7159 7160 // C++11 [dcl.constexpr]p4: 7161 // In the definition of a constexpr constructor [...] 7162 bool Ctor = true; 7163 switch (CSM) { 7164 case Sema::CXXDefaultConstructor: 7165 if (Inherited) 7166 break; 7167 // Since default constructor lookup is essentially trivial (and cannot 7168 // involve, for instance, template instantiation), we compute whether a 7169 // defaulted default constructor is constexpr directly within CXXRecordDecl. 7170 // 7171 // This is important for performance; we need to know whether the default 7172 // constructor is constexpr to determine whether the type is a literal type. 7173 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 7174 7175 case Sema::CXXCopyConstructor: 7176 case Sema::CXXMoveConstructor: 7177 // For copy or move constructors, we need to perform overload resolution. 7178 break; 7179 7180 case Sema::CXXCopyAssignment: 7181 case Sema::CXXMoveAssignment: 7182 if (!S.getLangOpts().CPlusPlus14) 7183 return false; 7184 // In C++1y, we need to perform overload resolution. 7185 Ctor = false; 7186 break; 7187 7188 case Sema::CXXDestructor: 7189 return ClassDecl->defaultedDestructorIsConstexpr(); 7190 7191 case Sema::CXXInvalid: 7192 return false; 7193 } 7194 7195 // -- if the class is a non-empty union, or for each non-empty anonymous 7196 // union member of a non-union class, exactly one non-static data member 7197 // shall be initialized; [DR1359] 7198 // 7199 // If we squint, this is guaranteed, since exactly one non-static data member 7200 // will be initialized (if the constructor isn't deleted), we just don't know 7201 // which one. 7202 if (Ctor && ClassDecl->isUnion()) 7203 return CSM == Sema::CXXDefaultConstructor 7204 ? ClassDecl->hasInClassInitializer() || 7205 !ClassDecl->hasVariantMembers() 7206 : true; 7207 7208 // -- the class shall not have any virtual base classes; 7209 if (Ctor && ClassDecl->getNumVBases()) 7210 return false; 7211 7212 // C++1y [class.copy]p26: 7213 // -- [the class] is a literal type, and 7214 if (!Ctor && !ClassDecl->isLiteral()) 7215 return false; 7216 7217 // -- every constructor involved in initializing [...] base class 7218 // sub-objects shall be a constexpr constructor; 7219 // -- the assignment operator selected to copy/move each direct base 7220 // class is a constexpr function, and 7221 for (const auto &B : ClassDecl->bases()) { 7222 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 7223 if (!BaseType) continue; 7224 7225 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7226 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg, 7227 InheritedCtor, Inherited)) 7228 return false; 7229 } 7230 7231 // -- every constructor involved in initializing non-static data members 7232 // [...] shall be a constexpr constructor; 7233 // -- every non-static data member and base class sub-object shall be 7234 // initialized 7235 // -- for each non-static data member of X that is of class type (or array 7236 // thereof), the assignment operator selected to copy/move that member is 7237 // a constexpr function 7238 for (const auto *F : ClassDecl->fields()) { 7239 if (F->isInvalidDecl()) 7240 continue; 7241 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer()) 7242 continue; 7243 QualType BaseType = S.Context.getBaseElementType(F->getType()); 7244 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 7245 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 7246 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 7247 BaseType.getCVRQualifiers(), 7248 ConstArg && !F->isMutable())) 7249 return false; 7250 } else if (CSM == Sema::CXXDefaultConstructor) { 7251 return false; 7252 } 7253 } 7254 7255 // All OK, it's constexpr! 7256 return true; 7257 } 7258 7259 namespace { 7260 /// RAII object to register a defaulted function as having its exception 7261 /// specification computed. 7262 struct ComputingExceptionSpec { 7263 Sema &S; 7264 7265 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc) 7266 : S(S) { 7267 Sema::CodeSynthesisContext Ctx; 7268 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation; 7269 Ctx.PointOfInstantiation = Loc; 7270 Ctx.Entity = FD; 7271 S.pushCodeSynthesisContext(Ctx); 7272 } 7273 ~ComputingExceptionSpec() { 7274 S.popCodeSynthesisContext(); 7275 } 7276 }; 7277 } 7278 7279 static Sema::ImplicitExceptionSpecification 7280 ComputeDefaultedSpecialMemberExceptionSpec( 7281 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 7282 Sema::InheritedConstructorInfo *ICI); 7283 7284 static Sema::ImplicitExceptionSpecification 7285 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, 7286 FunctionDecl *FD, 7287 Sema::DefaultedComparisonKind DCK); 7288 7289 static Sema::ImplicitExceptionSpecification 7290 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) { 7291 auto DFK = S.getDefaultedFunctionKind(FD); 7292 if (DFK.isSpecialMember()) 7293 return ComputeDefaultedSpecialMemberExceptionSpec( 7294 S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr); 7295 if (DFK.isComparison()) 7296 return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD, 7297 DFK.asComparison()); 7298 7299 auto *CD = cast<CXXConstructorDecl>(FD); 7300 assert(CD->getInheritedConstructor() && 7301 "only defaulted functions and inherited constructors have implicit " 7302 "exception specs"); 7303 Sema::InheritedConstructorInfo ICI( 7304 S, Loc, CD->getInheritedConstructor().getShadowDecl()); 7305 return ComputeDefaultedSpecialMemberExceptionSpec( 7306 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI); 7307 } 7308 7309 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 7310 CXXMethodDecl *MD) { 7311 FunctionProtoType::ExtProtoInfo EPI; 7312 7313 // Build an exception specification pointing back at this member. 7314 EPI.ExceptionSpec.Type = EST_Unevaluated; 7315 EPI.ExceptionSpec.SourceDecl = MD; 7316 7317 // Set the calling convention to the default for C++ instance methods. 7318 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 7319 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 7320 /*IsCXXMethod=*/true)); 7321 return EPI; 7322 } 7323 7324 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) { 7325 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>(); 7326 if (FPT->getExceptionSpecType() != EST_Unevaluated) 7327 return; 7328 7329 // Evaluate the exception specification. 7330 auto IES = computeImplicitExceptionSpec(*this, Loc, FD); 7331 auto ESI = IES.getExceptionSpec(); 7332 7333 // Update the type of the special member to use it. 7334 UpdateExceptionSpec(FD, ESI); 7335 } 7336 7337 void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) { 7338 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted"); 7339 7340 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD); 7341 if (!DefKind) { 7342 assert(FD->getDeclContext()->isDependentContext()); 7343 return; 7344 } 7345 7346 if (DefKind.isComparison()) 7347 UnusedPrivateFields.clear(); 7348 7349 if (DefKind.isSpecialMember() 7350 ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD), 7351 DefKind.asSpecialMember()) 7352 : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison())) 7353 FD->setInvalidDecl(); 7354 } 7355 7356 bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD, 7357 CXXSpecialMember CSM) { 7358 CXXRecordDecl *RD = MD->getParent(); 7359 7360 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 7361 "not an explicitly-defaulted special member"); 7362 7363 // Defer all checking for special members of a dependent type. 7364 if (RD->isDependentType()) 7365 return false; 7366 7367 // Whether this was the first-declared instance of the constructor. 7368 // This affects whether we implicitly add an exception spec and constexpr. 7369 bool First = MD == MD->getCanonicalDecl(); 7370 7371 bool HadError = false; 7372 7373 // C++11 [dcl.fct.def.default]p1: 7374 // A function that is explicitly defaulted shall 7375 // -- be a special member function [...] (checked elsewhere), 7376 // -- have the same type (except for ref-qualifiers, and except that a 7377 // copy operation can take a non-const reference) as an implicit 7378 // declaration, and 7379 // -- not have default arguments. 7380 // C++2a changes the second bullet to instead delete the function if it's 7381 // defaulted on its first declaration, unless it's "an assignment operator, 7382 // and its return type differs or its parameter type is not a reference". 7383 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First; 7384 bool ShouldDeleteForTypeMismatch = false; 7385 unsigned ExpectedParams = 1; 7386 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 7387 ExpectedParams = 0; 7388 if (MD->getNumParams() != ExpectedParams) { 7389 // This checks for default arguments: a copy or move constructor with a 7390 // default argument is classified as a default constructor, and assignment 7391 // operations and destructors can't have default arguments. 7392 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 7393 << CSM << MD->getSourceRange(); 7394 HadError = true; 7395 } else if (MD->isVariadic()) { 7396 if (DeleteOnTypeMismatch) 7397 ShouldDeleteForTypeMismatch = true; 7398 else { 7399 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 7400 << CSM << MD->getSourceRange(); 7401 HadError = true; 7402 } 7403 } 7404 7405 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 7406 7407 bool CanHaveConstParam = false; 7408 if (CSM == CXXCopyConstructor) 7409 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 7410 else if (CSM == CXXCopyAssignment) 7411 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 7412 7413 QualType ReturnType = Context.VoidTy; 7414 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 7415 // Check for return type matching. 7416 ReturnType = Type->getReturnType(); 7417 7418 QualType DeclType = Context.getTypeDeclType(RD); 7419 DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace()); 7420 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType); 7421 7422 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 7423 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 7424 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 7425 HadError = true; 7426 } 7427 7428 // A defaulted special member cannot have cv-qualifiers. 7429 if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) { 7430 if (DeleteOnTypeMismatch) 7431 ShouldDeleteForTypeMismatch = true; 7432 else { 7433 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 7434 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 7435 HadError = true; 7436 } 7437 } 7438 } 7439 7440 // Check for parameter type matching. 7441 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 7442 bool HasConstParam = false; 7443 if (ExpectedParams && ArgType->isReferenceType()) { 7444 // Argument must be reference to possibly-const T. 7445 QualType ReferentType = ArgType->getPointeeType(); 7446 HasConstParam = ReferentType.isConstQualified(); 7447 7448 if (ReferentType.isVolatileQualified()) { 7449 if (DeleteOnTypeMismatch) 7450 ShouldDeleteForTypeMismatch = true; 7451 else { 7452 Diag(MD->getLocation(), 7453 diag::err_defaulted_special_member_volatile_param) << CSM; 7454 HadError = true; 7455 } 7456 } 7457 7458 if (HasConstParam && !CanHaveConstParam) { 7459 if (DeleteOnTypeMismatch) 7460 ShouldDeleteForTypeMismatch = true; 7461 else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 7462 Diag(MD->getLocation(), 7463 diag::err_defaulted_special_member_copy_const_param) 7464 << (CSM == CXXCopyAssignment); 7465 // FIXME: Explain why this special member can't be const. 7466 HadError = true; 7467 } else { 7468 Diag(MD->getLocation(), 7469 diag::err_defaulted_special_member_move_const_param) 7470 << (CSM == CXXMoveAssignment); 7471 HadError = true; 7472 } 7473 } 7474 } else if (ExpectedParams) { 7475 // A copy assignment operator can take its argument by value, but a 7476 // defaulted one cannot. 7477 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 7478 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 7479 HadError = true; 7480 } 7481 7482 // C++11 [dcl.fct.def.default]p2: 7483 // An explicitly-defaulted function may be declared constexpr only if it 7484 // would have been implicitly declared as constexpr, 7485 // Do not apply this rule to members of class templates, since core issue 1358 7486 // makes such functions always instantiate to constexpr functions. For 7487 // functions which cannot be constexpr (for non-constructors in C++11 and for 7488 // destructors in C++14 and C++17), this is checked elsewhere. 7489 // 7490 // FIXME: This should not apply if the member is deleted. 7491 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 7492 HasConstParam); 7493 if ((getLangOpts().CPlusPlus20 || 7494 (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 7495 : isa<CXXConstructorDecl>(MD))) && 7496 MD->isConstexpr() && !Constexpr && 7497 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 7498 Diag(MD->getBeginLoc(), MD->isConsteval() 7499 ? diag::err_incorrect_defaulted_consteval 7500 : diag::err_incorrect_defaulted_constexpr) 7501 << CSM; 7502 // FIXME: Explain why the special member can't be constexpr. 7503 HadError = true; 7504 } 7505 7506 if (First) { 7507 // C++2a [dcl.fct.def.default]p3: 7508 // If a function is explicitly defaulted on its first declaration, it is 7509 // implicitly considered to be constexpr if the implicit declaration 7510 // would be. 7511 MD->setConstexprKind(Constexpr ? (MD->isConsteval() 7512 ? ConstexprSpecKind::Consteval 7513 : ConstexprSpecKind::Constexpr) 7514 : ConstexprSpecKind::Unspecified); 7515 7516 if (!Type->hasExceptionSpec()) { 7517 // C++2a [except.spec]p3: 7518 // If a declaration of a function does not have a noexcept-specifier 7519 // [and] is defaulted on its first declaration, [...] the exception 7520 // specification is as specified below 7521 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 7522 EPI.ExceptionSpec.Type = EST_Unevaluated; 7523 EPI.ExceptionSpec.SourceDecl = MD; 7524 MD->setType(Context.getFunctionType(ReturnType, 7525 llvm::makeArrayRef(&ArgType, 7526 ExpectedParams), 7527 EPI)); 7528 } 7529 } 7530 7531 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) { 7532 if (First) { 7533 SetDeclDeleted(MD, MD->getLocation()); 7534 if (!inTemplateInstantiation() && !HadError) { 7535 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM; 7536 if (ShouldDeleteForTypeMismatch) { 7537 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM; 7538 } else { 7539 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 7540 } 7541 } 7542 if (ShouldDeleteForTypeMismatch && !HadError) { 7543 Diag(MD->getLocation(), 7544 diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM; 7545 } 7546 } else { 7547 // C++11 [dcl.fct.def.default]p4: 7548 // [For a] user-provided explicitly-defaulted function [...] if such a 7549 // function is implicitly defined as deleted, the program is ill-formed. 7550 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 7551 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl"); 7552 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 7553 HadError = true; 7554 } 7555 } 7556 7557 return HadError; 7558 } 7559 7560 namespace { 7561 /// Helper class for building and checking a defaulted comparison. 7562 /// 7563 /// Defaulted functions are built in two phases: 7564 /// 7565 /// * First, the set of operations that the function will perform are 7566 /// identified, and some of them are checked. If any of the checked 7567 /// operations is invalid in certain ways, the comparison function is 7568 /// defined as deleted and no body is built. 7569 /// * Then, if the function is not defined as deleted, the body is built. 7570 /// 7571 /// This is accomplished by performing two visitation steps over the eventual 7572 /// body of the function. 7573 template<typename Derived, typename ResultList, typename Result, 7574 typename Subobject> 7575 class DefaultedComparisonVisitor { 7576 public: 7577 using DefaultedComparisonKind = Sema::DefaultedComparisonKind; 7578 7579 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7580 DefaultedComparisonKind DCK) 7581 : S(S), RD(RD), FD(FD), DCK(DCK) { 7582 if (auto *Info = FD->getDefaultedFunctionInfo()) { 7583 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an 7584 // UnresolvedSet to avoid this copy. 7585 Fns.assign(Info->getUnqualifiedLookups().begin(), 7586 Info->getUnqualifiedLookups().end()); 7587 } 7588 } 7589 7590 ResultList visit() { 7591 // The type of an lvalue naming a parameter of this function. 7592 QualType ParamLvalType = 7593 FD->getParamDecl(0)->getType().getNonReferenceType(); 7594 7595 ResultList Results; 7596 7597 switch (DCK) { 7598 case DefaultedComparisonKind::None: 7599 llvm_unreachable("not a defaulted comparison"); 7600 7601 case DefaultedComparisonKind::Equal: 7602 case DefaultedComparisonKind::ThreeWay: 7603 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers()); 7604 return Results; 7605 7606 case DefaultedComparisonKind::NotEqual: 7607 case DefaultedComparisonKind::Relational: 7608 Results.add(getDerived().visitExpandedSubobject( 7609 ParamLvalType, getDerived().getCompleteObject())); 7610 return Results; 7611 } 7612 llvm_unreachable(""); 7613 } 7614 7615 protected: 7616 Derived &getDerived() { return static_cast<Derived&>(*this); } 7617 7618 /// Visit the expanded list of subobjects of the given type, as specified in 7619 /// C++2a [class.compare.default]. 7620 /// 7621 /// \return \c true if the ResultList object said we're done, \c false if not. 7622 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record, 7623 Qualifiers Quals) { 7624 // C++2a [class.compare.default]p4: 7625 // The direct base class subobjects of C 7626 for (CXXBaseSpecifier &Base : Record->bases()) 7627 if (Results.add(getDerived().visitSubobject( 7628 S.Context.getQualifiedType(Base.getType(), Quals), 7629 getDerived().getBase(&Base)))) 7630 return true; 7631 7632 // followed by the non-static data members of C 7633 for (FieldDecl *Field : Record->fields()) { 7634 // Recursively expand anonymous structs. 7635 if (Field->isAnonymousStructOrUnion()) { 7636 if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(), 7637 Quals)) 7638 return true; 7639 continue; 7640 } 7641 7642 // Figure out the type of an lvalue denoting this field. 7643 Qualifiers FieldQuals = Quals; 7644 if (Field->isMutable()) 7645 FieldQuals.removeConst(); 7646 QualType FieldType = 7647 S.Context.getQualifiedType(Field->getType(), FieldQuals); 7648 7649 if (Results.add(getDerived().visitSubobject( 7650 FieldType, getDerived().getField(Field)))) 7651 return true; 7652 } 7653 7654 // form a list of subobjects. 7655 return false; 7656 } 7657 7658 Result visitSubobject(QualType Type, Subobject Subobj) { 7659 // In that list, any subobject of array type is recursively expanded 7660 const ArrayType *AT = S.Context.getAsArrayType(Type); 7661 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT)) 7662 return getDerived().visitSubobjectArray(CAT->getElementType(), 7663 CAT->getSize(), Subobj); 7664 return getDerived().visitExpandedSubobject(Type, Subobj); 7665 } 7666 7667 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size, 7668 Subobject Subobj) { 7669 return getDerived().visitSubobject(Type, Subobj); 7670 } 7671 7672 protected: 7673 Sema &S; 7674 CXXRecordDecl *RD; 7675 FunctionDecl *FD; 7676 DefaultedComparisonKind DCK; 7677 UnresolvedSet<16> Fns; 7678 }; 7679 7680 /// Information about a defaulted comparison, as determined by 7681 /// DefaultedComparisonAnalyzer. 7682 struct DefaultedComparisonInfo { 7683 bool Deleted = false; 7684 bool Constexpr = true; 7685 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering; 7686 7687 static DefaultedComparisonInfo deleted() { 7688 DefaultedComparisonInfo Deleted; 7689 Deleted.Deleted = true; 7690 return Deleted; 7691 } 7692 7693 bool add(const DefaultedComparisonInfo &R) { 7694 Deleted |= R.Deleted; 7695 Constexpr &= R.Constexpr; 7696 Category = commonComparisonType(Category, R.Category); 7697 return Deleted; 7698 } 7699 }; 7700 7701 /// An element in the expanded list of subobjects of a defaulted comparison, as 7702 /// specified in C++2a [class.compare.default]p4. 7703 struct DefaultedComparisonSubobject { 7704 enum { CompleteObject, Member, Base } Kind; 7705 NamedDecl *Decl; 7706 SourceLocation Loc; 7707 }; 7708 7709 /// A visitor over the notional body of a defaulted comparison that determines 7710 /// whether that body would be deleted or constexpr. 7711 class DefaultedComparisonAnalyzer 7712 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer, 7713 DefaultedComparisonInfo, 7714 DefaultedComparisonInfo, 7715 DefaultedComparisonSubobject> { 7716 public: 7717 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr }; 7718 7719 private: 7720 DiagnosticKind Diagnose; 7721 7722 public: 7723 using Base = DefaultedComparisonVisitor; 7724 using Result = DefaultedComparisonInfo; 7725 using Subobject = DefaultedComparisonSubobject; 7726 7727 friend Base; 7728 7729 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7730 DefaultedComparisonKind DCK, 7731 DiagnosticKind Diagnose = NoDiagnostics) 7732 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {} 7733 7734 Result visit() { 7735 if ((DCK == DefaultedComparisonKind::Equal || 7736 DCK == DefaultedComparisonKind::ThreeWay) && 7737 RD->hasVariantMembers()) { 7738 // C++2a [class.compare.default]p2 [P2002R0]: 7739 // A defaulted comparison operator function for class C is defined as 7740 // deleted if [...] C has variant members. 7741 if (Diagnose == ExplainDeleted) { 7742 S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union) 7743 << FD << RD->isUnion() << RD; 7744 } 7745 return Result::deleted(); 7746 } 7747 7748 return Base::visit(); 7749 } 7750 7751 private: 7752 Subobject getCompleteObject() { 7753 return Subobject{Subobject::CompleteObject, RD, FD->getLocation()}; 7754 } 7755 7756 Subobject getBase(CXXBaseSpecifier *Base) { 7757 return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(), 7758 Base->getBaseTypeLoc()}; 7759 } 7760 7761 Subobject getField(FieldDecl *Field) { 7762 return Subobject{Subobject::Member, Field, Field->getLocation()}; 7763 } 7764 7765 Result visitExpandedSubobject(QualType Type, Subobject Subobj) { 7766 // C++2a [class.compare.default]p2 [P2002R0]: 7767 // A defaulted <=> or == operator function for class C is defined as 7768 // deleted if any non-static data member of C is of reference type 7769 if (Type->isReferenceType()) { 7770 if (Diagnose == ExplainDeleted) { 7771 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member) 7772 << FD << RD; 7773 } 7774 return Result::deleted(); 7775 } 7776 7777 // [...] Let xi be an lvalue denoting the ith element [...] 7778 OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue); 7779 Expr *Args[] = {&Xi, &Xi}; 7780 7781 // All operators start by trying to apply that same operator recursively. 7782 OverloadedOperatorKind OO = FD->getOverloadedOperator(); 7783 assert(OO != OO_None && "not an overloaded operator!"); 7784 return visitBinaryOperator(OO, Args, Subobj); 7785 } 7786 7787 Result 7788 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args, 7789 Subobject Subobj, 7790 OverloadCandidateSet *SpaceshipCandidates = nullptr) { 7791 // Note that there is no need to consider rewritten candidates here if 7792 // we've already found there is no viable 'operator<=>' candidate (and are 7793 // considering synthesizing a '<=>' from '==' and '<'). 7794 OverloadCandidateSet CandidateSet( 7795 FD->getLocation(), OverloadCandidateSet::CSK_Operator, 7796 OverloadCandidateSet::OperatorRewriteInfo( 7797 OO, /*AllowRewrittenCandidates=*/!SpaceshipCandidates)); 7798 7799 /// C++2a [class.compare.default]p1 [P2002R0]: 7800 /// [...] the defaulted function itself is never a candidate for overload 7801 /// resolution [...] 7802 CandidateSet.exclude(FD); 7803 7804 if (Args[0]->getType()->isOverloadableType()) 7805 S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args); 7806 else 7807 // FIXME: We determine whether this is a valid expression by checking to 7808 // see if there's a viable builtin operator candidate for it. That isn't 7809 // really what the rules ask us to do, but should give the right results. 7810 S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet); 7811 7812 Result R; 7813 7814 OverloadCandidateSet::iterator Best; 7815 switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) { 7816 case OR_Success: { 7817 // C++2a [class.compare.secondary]p2 [P2002R0]: 7818 // The operator function [...] is defined as deleted if [...] the 7819 // candidate selected by overload resolution is not a rewritten 7820 // candidate. 7821 if ((DCK == DefaultedComparisonKind::NotEqual || 7822 DCK == DefaultedComparisonKind::Relational) && 7823 !Best->RewriteKind) { 7824 if (Diagnose == ExplainDeleted) { 7825 if (Best->Function) { 7826 S.Diag(Best->Function->getLocation(), 7827 diag::note_defaulted_comparison_not_rewritten_callee) 7828 << FD; 7829 } else { 7830 assert(Best->Conversions.size() == 2 && 7831 Best->Conversions[0].isUserDefined() && 7832 "non-user-defined conversion from class to built-in " 7833 "comparison"); 7834 S.Diag(Best->Conversions[0] 7835 .UserDefined.FoundConversionFunction.getDecl() 7836 ->getLocation(), 7837 diag::note_defaulted_comparison_not_rewritten_conversion) 7838 << FD; 7839 } 7840 } 7841 return Result::deleted(); 7842 } 7843 7844 // Throughout C++2a [class.compare]: if overload resolution does not 7845 // result in a usable function, the candidate function is defined as 7846 // deleted. This requires that we selected an accessible function. 7847 // 7848 // Note that this only considers the access of the function when named 7849 // within the type of the subobject, and not the access path for any 7850 // derived-to-base conversion. 7851 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl(); 7852 if (ArgClass && Best->FoundDecl.getDecl() && 7853 Best->FoundDecl.getDecl()->isCXXClassMember()) { 7854 QualType ObjectType = Subobj.Kind == Subobject::Member 7855 ? Args[0]->getType() 7856 : S.Context.getRecordType(RD); 7857 if (!S.isMemberAccessibleForDeletion( 7858 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc, 7859 Diagnose == ExplainDeleted 7860 ? S.PDiag(diag::note_defaulted_comparison_inaccessible) 7861 << FD << Subobj.Kind << Subobj.Decl 7862 : S.PDiag())) 7863 return Result::deleted(); 7864 } 7865 7866 bool NeedsDeducing = 7867 OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType(); 7868 7869 if (FunctionDecl *BestFD = Best->Function) { 7870 // C++2a [class.compare.default]p3 [P2002R0]: 7871 // A defaulted comparison function is constexpr-compatible if 7872 // [...] no overlod resolution performed [...] results in a 7873 // non-constexpr function. 7874 assert(!BestFD->isDeleted() && "wrong overload resolution result"); 7875 // If it's not constexpr, explain why not. 7876 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) { 7877 if (Subobj.Kind != Subobject::CompleteObject) 7878 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr) 7879 << Subobj.Kind << Subobj.Decl; 7880 S.Diag(BestFD->getLocation(), 7881 diag::note_defaulted_comparison_not_constexpr_here); 7882 // Bail out after explaining; we don't want any more notes. 7883 return Result::deleted(); 7884 } 7885 R.Constexpr &= BestFD->isConstexpr(); 7886 7887 if (NeedsDeducing) { 7888 // If any callee has an undeduced return type, deduce it now. 7889 // FIXME: It's not clear how a failure here should be handled. For 7890 // now, we produce an eager diagnostic, because that is forward 7891 // compatible with most (all?) other reasonable options. 7892 if (BestFD->getReturnType()->isUndeducedType() && 7893 S.DeduceReturnType(BestFD, FD->getLocation(), 7894 /*Diagnose=*/false)) { 7895 // Don't produce a duplicate error when asked to explain why the 7896 // comparison is deleted: we diagnosed that when initially checking 7897 // the defaulted operator. 7898 if (Diagnose == NoDiagnostics) { 7899 S.Diag( 7900 FD->getLocation(), 7901 diag::err_defaulted_comparison_cannot_deduce_undeduced_auto) 7902 << Subobj.Kind << Subobj.Decl; 7903 S.Diag( 7904 Subobj.Loc, 7905 diag::note_defaulted_comparison_cannot_deduce_undeduced_auto) 7906 << Subobj.Kind << Subobj.Decl; 7907 S.Diag(BestFD->getLocation(), 7908 diag::note_defaulted_comparison_cannot_deduce_callee) 7909 << Subobj.Kind << Subobj.Decl; 7910 } 7911 return Result::deleted(); 7912 } 7913 auto *Info = S.Context.CompCategories.lookupInfoForType( 7914 BestFD->getCallResultType()); 7915 if (!Info) { 7916 if (Diagnose == ExplainDeleted) { 7917 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce) 7918 << Subobj.Kind << Subobj.Decl 7919 << BestFD->getCallResultType().withoutLocalFastQualifiers(); 7920 S.Diag(BestFD->getLocation(), 7921 diag::note_defaulted_comparison_cannot_deduce_callee) 7922 << Subobj.Kind << Subobj.Decl; 7923 } 7924 return Result::deleted(); 7925 } 7926 R.Category = Info->Kind; 7927 } 7928 } else { 7929 QualType T = Best->BuiltinParamTypes[0]; 7930 assert(T == Best->BuiltinParamTypes[1] && 7931 "builtin comparison for different types?"); 7932 assert(Best->BuiltinParamTypes[2].isNull() && 7933 "invalid builtin comparison"); 7934 7935 if (NeedsDeducing) { 7936 Optional<ComparisonCategoryType> Cat = 7937 getComparisonCategoryForBuiltinCmp(T); 7938 assert(Cat && "no category for builtin comparison?"); 7939 R.Category = *Cat; 7940 } 7941 } 7942 7943 // Note that we might be rewriting to a different operator. That call is 7944 // not considered until we come to actually build the comparison function. 7945 break; 7946 } 7947 7948 case OR_Ambiguous: 7949 if (Diagnose == ExplainDeleted) { 7950 unsigned Kind = 0; 7951 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship) 7952 Kind = OO == OO_EqualEqual ? 1 : 2; 7953 CandidateSet.NoteCandidates( 7954 PartialDiagnosticAt( 7955 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous) 7956 << FD << Kind << Subobj.Kind << Subobj.Decl), 7957 S, OCD_AmbiguousCandidates, Args); 7958 } 7959 R = Result::deleted(); 7960 break; 7961 7962 case OR_Deleted: 7963 if (Diagnose == ExplainDeleted) { 7964 if ((DCK == DefaultedComparisonKind::NotEqual || 7965 DCK == DefaultedComparisonKind::Relational) && 7966 !Best->RewriteKind) { 7967 S.Diag(Best->Function->getLocation(), 7968 diag::note_defaulted_comparison_not_rewritten_callee) 7969 << FD; 7970 } else { 7971 S.Diag(Subobj.Loc, 7972 diag::note_defaulted_comparison_calls_deleted) 7973 << FD << Subobj.Kind << Subobj.Decl; 7974 S.NoteDeletedFunction(Best->Function); 7975 } 7976 } 7977 R = Result::deleted(); 7978 break; 7979 7980 case OR_No_Viable_Function: 7981 // If there's no usable candidate, we're done unless we can rewrite a 7982 // '<=>' in terms of '==' and '<'. 7983 if (OO == OO_Spaceship && 7984 S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) { 7985 // For any kind of comparison category return type, we need a usable 7986 // '==' and a usable '<'. 7987 if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj, 7988 &CandidateSet))) 7989 R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet)); 7990 break; 7991 } 7992 7993 if (Diagnose == ExplainDeleted) { 7994 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function) 7995 << FD << (OO == OO_ExclaimEqual) << Subobj.Kind << Subobj.Decl; 7996 7997 // For a three-way comparison, list both the candidates for the 7998 // original operator and the candidates for the synthesized operator. 7999 if (SpaceshipCandidates) { 8000 SpaceshipCandidates->NoteCandidates( 8001 S, Args, 8002 SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates, 8003 Args, FD->getLocation())); 8004 S.Diag(Subobj.Loc, 8005 diag::note_defaulted_comparison_no_viable_function_synthesized) 8006 << (OO == OO_EqualEqual ? 0 : 1); 8007 } 8008 8009 CandidateSet.NoteCandidates( 8010 S, Args, 8011 CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args, 8012 FD->getLocation())); 8013 } 8014 R = Result::deleted(); 8015 break; 8016 } 8017 8018 return R; 8019 } 8020 }; 8021 8022 /// A list of statements. 8023 struct StmtListResult { 8024 bool IsInvalid = false; 8025 llvm::SmallVector<Stmt*, 16> Stmts; 8026 8027 bool add(const StmtResult &S) { 8028 IsInvalid |= S.isInvalid(); 8029 if (IsInvalid) 8030 return true; 8031 Stmts.push_back(S.get()); 8032 return false; 8033 } 8034 }; 8035 8036 /// A visitor over the notional body of a defaulted comparison that synthesizes 8037 /// the actual body. 8038 class DefaultedComparisonSynthesizer 8039 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer, 8040 StmtListResult, StmtResult, 8041 std::pair<ExprResult, ExprResult>> { 8042 SourceLocation Loc; 8043 unsigned ArrayDepth = 0; 8044 8045 public: 8046 using Base = DefaultedComparisonVisitor; 8047 using ExprPair = std::pair<ExprResult, ExprResult>; 8048 8049 friend Base; 8050 8051 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 8052 DefaultedComparisonKind DCK, 8053 SourceLocation BodyLoc) 8054 : Base(S, RD, FD, DCK), Loc(BodyLoc) {} 8055 8056 /// Build a suitable function body for this defaulted comparison operator. 8057 StmtResult build() { 8058 Sema::CompoundScopeRAII CompoundScope(S); 8059 8060 StmtListResult Stmts = visit(); 8061 if (Stmts.IsInvalid) 8062 return StmtError(); 8063 8064 ExprResult RetVal; 8065 switch (DCK) { 8066 case DefaultedComparisonKind::None: 8067 llvm_unreachable("not a defaulted comparison"); 8068 8069 case DefaultedComparisonKind::Equal: { 8070 // C++2a [class.eq]p3: 8071 // [...] compar[e] the corresponding elements [...] until the first 8072 // index i where xi == yi yields [...] false. If no such index exists, 8073 // V is true. Otherwise, V is false. 8074 // 8075 // Join the comparisons with '&&'s and return the result. Use a right 8076 // fold (traversing the conditions right-to-left), because that 8077 // short-circuits more naturally. 8078 auto OldStmts = std::move(Stmts.Stmts); 8079 Stmts.Stmts.clear(); 8080 ExprResult CmpSoFar; 8081 // Finish a particular comparison chain. 8082 auto FinishCmp = [&] { 8083 if (Expr *Prior = CmpSoFar.get()) { 8084 // Convert the last expression to 'return ...;' 8085 if (RetVal.isUnset() && Stmts.Stmts.empty()) 8086 RetVal = CmpSoFar; 8087 // Convert any prior comparison to 'if (!(...)) return false;' 8088 else if (Stmts.add(buildIfNotCondReturnFalse(Prior))) 8089 return true; 8090 CmpSoFar = ExprResult(); 8091 } 8092 return false; 8093 }; 8094 for (Stmt *EAsStmt : llvm::reverse(OldStmts)) { 8095 Expr *E = dyn_cast<Expr>(EAsStmt); 8096 if (!E) { 8097 // Found an array comparison. 8098 if (FinishCmp() || Stmts.add(EAsStmt)) 8099 return StmtError(); 8100 continue; 8101 } 8102 8103 if (CmpSoFar.isUnset()) { 8104 CmpSoFar = E; 8105 continue; 8106 } 8107 CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get()); 8108 if (CmpSoFar.isInvalid()) 8109 return StmtError(); 8110 } 8111 if (FinishCmp()) 8112 return StmtError(); 8113 std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end()); 8114 // If no such index exists, V is true. 8115 if (RetVal.isUnset()) 8116 RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true); 8117 break; 8118 } 8119 8120 case DefaultedComparisonKind::ThreeWay: { 8121 // Per C++2a [class.spaceship]p3, as a fallback add: 8122 // return static_cast<R>(std::strong_ordering::equal); 8123 QualType StrongOrdering = S.CheckComparisonCategoryType( 8124 ComparisonCategoryType::StrongOrdering, Loc, 8125 Sema::ComparisonCategoryUsage::DefaultedOperator); 8126 if (StrongOrdering.isNull()) 8127 return StmtError(); 8128 VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering) 8129 .getValueInfo(ComparisonCategoryResult::Equal) 8130 ->VD; 8131 RetVal = getDecl(EqualVD); 8132 if (RetVal.isInvalid()) 8133 return StmtError(); 8134 RetVal = buildStaticCastToR(RetVal.get()); 8135 break; 8136 } 8137 8138 case DefaultedComparisonKind::NotEqual: 8139 case DefaultedComparisonKind::Relational: 8140 RetVal = cast<Expr>(Stmts.Stmts.pop_back_val()); 8141 break; 8142 } 8143 8144 // Build the final return statement. 8145 if (RetVal.isInvalid()) 8146 return StmtError(); 8147 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get()); 8148 if (ReturnStmt.isInvalid()) 8149 return StmtError(); 8150 Stmts.Stmts.push_back(ReturnStmt.get()); 8151 8152 return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false); 8153 } 8154 8155 private: 8156 ExprResult getDecl(ValueDecl *VD) { 8157 return S.BuildDeclarationNameExpr( 8158 CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD); 8159 } 8160 8161 ExprResult getParam(unsigned I) { 8162 ParmVarDecl *PD = FD->getParamDecl(I); 8163 return getDecl(PD); 8164 } 8165 8166 ExprPair getCompleteObject() { 8167 unsigned Param = 0; 8168 ExprResult LHS; 8169 if (isa<CXXMethodDecl>(FD)) { 8170 // LHS is '*this'. 8171 LHS = S.ActOnCXXThis(Loc); 8172 if (!LHS.isInvalid()) 8173 LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get()); 8174 } else { 8175 LHS = getParam(Param++); 8176 } 8177 ExprResult RHS = getParam(Param++); 8178 assert(Param == FD->getNumParams()); 8179 return {LHS, RHS}; 8180 } 8181 8182 ExprPair getBase(CXXBaseSpecifier *Base) { 8183 ExprPair Obj = getCompleteObject(); 8184 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 8185 return {ExprError(), ExprError()}; 8186 CXXCastPath Path = {Base}; 8187 return {S.ImpCastExprToType(Obj.first.get(), Base->getType(), 8188 CK_DerivedToBase, VK_LValue, &Path), 8189 S.ImpCastExprToType(Obj.second.get(), Base->getType(), 8190 CK_DerivedToBase, VK_LValue, &Path)}; 8191 } 8192 8193 ExprPair getField(FieldDecl *Field) { 8194 ExprPair Obj = getCompleteObject(); 8195 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 8196 return {ExprError(), ExprError()}; 8197 8198 DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess()); 8199 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc); 8200 return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc, 8201 CXXScopeSpec(), Field, Found, NameInfo), 8202 S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc, 8203 CXXScopeSpec(), Field, Found, NameInfo)}; 8204 } 8205 8206 // FIXME: When expanding a subobject, register a note in the code synthesis 8207 // stack to say which subobject we're comparing. 8208 8209 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) { 8210 if (Cond.isInvalid()) 8211 return StmtError(); 8212 8213 ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get()); 8214 if (NotCond.isInvalid()) 8215 return StmtError(); 8216 8217 ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false); 8218 assert(!False.isInvalid() && "should never fail"); 8219 StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get()); 8220 if (ReturnFalse.isInvalid()) 8221 return StmtError(); 8222 8223 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, nullptr, 8224 S.ActOnCondition(nullptr, Loc, NotCond.get(), 8225 Sema::ConditionKind::Boolean), 8226 Loc, ReturnFalse.get(), SourceLocation(), nullptr); 8227 } 8228 8229 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size, 8230 ExprPair Subobj) { 8231 QualType SizeType = S.Context.getSizeType(); 8232 Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType)); 8233 8234 // Build 'size_t i$n = 0'. 8235 IdentifierInfo *IterationVarName = nullptr; 8236 { 8237 SmallString<8> Str; 8238 llvm::raw_svector_ostream OS(Str); 8239 OS << "i" << ArrayDepth; 8240 IterationVarName = &S.Context.Idents.get(OS.str()); 8241 } 8242 VarDecl *IterationVar = VarDecl::Create( 8243 S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType, 8244 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None); 8245 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 8246 IterationVar->setInit( 8247 IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 8248 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc); 8249 8250 auto IterRef = [&] { 8251 ExprResult Ref = S.BuildDeclarationNameExpr( 8252 CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc), 8253 IterationVar); 8254 assert(!Ref.isInvalid() && "can't reference our own variable?"); 8255 return Ref.get(); 8256 }; 8257 8258 // Build 'i$n != Size'. 8259 ExprResult Cond = S.CreateBuiltinBinOp( 8260 Loc, BO_NE, IterRef(), 8261 IntegerLiteral::Create(S.Context, Size, SizeType, Loc)); 8262 assert(!Cond.isInvalid() && "should never fail"); 8263 8264 // Build '++i$n'. 8265 ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef()); 8266 assert(!Inc.isInvalid() && "should never fail"); 8267 8268 // Build 'a[i$n]' and 'b[i$n]'. 8269 auto Index = [&](ExprResult E) { 8270 if (E.isInvalid()) 8271 return ExprError(); 8272 return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc); 8273 }; 8274 Subobj.first = Index(Subobj.first); 8275 Subobj.second = Index(Subobj.second); 8276 8277 // Compare the array elements. 8278 ++ArrayDepth; 8279 StmtResult Substmt = visitSubobject(Type, Subobj); 8280 --ArrayDepth; 8281 8282 if (Substmt.isInvalid()) 8283 return StmtError(); 8284 8285 // For the inner level of an 'operator==', build 'if (!cmp) return false;'. 8286 // For outer levels or for an 'operator<=>' we already have a suitable 8287 // statement that returns as necessary. 8288 if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) { 8289 assert(DCK == DefaultedComparisonKind::Equal && 8290 "should have non-expression statement"); 8291 Substmt = buildIfNotCondReturnFalse(ElemCmp); 8292 if (Substmt.isInvalid()) 8293 return StmtError(); 8294 } 8295 8296 // Build 'for (...) ...' 8297 return S.ActOnForStmt(Loc, Loc, Init, 8298 S.ActOnCondition(nullptr, Loc, Cond.get(), 8299 Sema::ConditionKind::Boolean), 8300 S.MakeFullDiscardedValueExpr(Inc.get()), Loc, 8301 Substmt.get()); 8302 } 8303 8304 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) { 8305 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 8306 return StmtError(); 8307 8308 OverloadedOperatorKind OO = FD->getOverloadedOperator(); 8309 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO); 8310 ExprResult Op; 8311 if (Type->isOverloadableType()) 8312 Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(), 8313 Obj.second.get(), /*PerformADL=*/true, 8314 /*AllowRewrittenCandidates=*/true, FD); 8315 else 8316 Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get()); 8317 if (Op.isInvalid()) 8318 return StmtError(); 8319 8320 switch (DCK) { 8321 case DefaultedComparisonKind::None: 8322 llvm_unreachable("not a defaulted comparison"); 8323 8324 case DefaultedComparisonKind::Equal: 8325 // Per C++2a [class.eq]p2, each comparison is individually contextually 8326 // converted to bool. 8327 Op = S.PerformContextuallyConvertToBool(Op.get()); 8328 if (Op.isInvalid()) 8329 return StmtError(); 8330 return Op.get(); 8331 8332 case DefaultedComparisonKind::ThreeWay: { 8333 // Per C++2a [class.spaceship]p3, form: 8334 // if (R cmp = static_cast<R>(op); cmp != 0) 8335 // return cmp; 8336 QualType R = FD->getReturnType(); 8337 Op = buildStaticCastToR(Op.get()); 8338 if (Op.isInvalid()) 8339 return StmtError(); 8340 8341 // R cmp = ...; 8342 IdentifierInfo *Name = &S.Context.Idents.get("cmp"); 8343 VarDecl *VD = 8344 VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R, 8345 S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None); 8346 S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false); 8347 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc); 8348 8349 // cmp != 0 8350 ExprResult VDRef = getDecl(VD); 8351 if (VDRef.isInvalid()) 8352 return StmtError(); 8353 llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0); 8354 Expr *Zero = 8355 IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc); 8356 ExprResult Comp; 8357 if (VDRef.get()->getType()->isOverloadableType()) 8358 Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true, 8359 true, FD); 8360 else 8361 Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero); 8362 if (Comp.isInvalid()) 8363 return StmtError(); 8364 Sema::ConditionResult Cond = S.ActOnCondition( 8365 nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean); 8366 if (Cond.isInvalid()) 8367 return StmtError(); 8368 8369 // return cmp; 8370 VDRef = getDecl(VD); 8371 if (VDRef.isInvalid()) 8372 return StmtError(); 8373 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get()); 8374 if (ReturnStmt.isInvalid()) 8375 return StmtError(); 8376 8377 // if (...) 8378 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, InitStmt, Cond, 8379 Loc, ReturnStmt.get(), 8380 /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr); 8381 } 8382 8383 case DefaultedComparisonKind::NotEqual: 8384 case DefaultedComparisonKind::Relational: 8385 // C++2a [class.compare.secondary]p2: 8386 // Otherwise, the operator function yields x @ y. 8387 return Op.get(); 8388 } 8389 llvm_unreachable(""); 8390 } 8391 8392 /// Build "static_cast<R>(E)". 8393 ExprResult buildStaticCastToR(Expr *E) { 8394 QualType R = FD->getReturnType(); 8395 assert(!R->isUndeducedType() && "type should have been deduced already"); 8396 8397 // Don't bother forming a no-op cast in the common case. 8398 if (E->isPRValue() && S.Context.hasSameType(E->getType(), R)) 8399 return E; 8400 return S.BuildCXXNamedCast(Loc, tok::kw_static_cast, 8401 S.Context.getTrivialTypeSourceInfo(R, Loc), E, 8402 SourceRange(Loc, Loc), SourceRange(Loc, Loc)); 8403 } 8404 }; 8405 } 8406 8407 /// Perform the unqualified lookups that might be needed to form a defaulted 8408 /// comparison function for the given operator. 8409 static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S, 8410 UnresolvedSetImpl &Operators, 8411 OverloadedOperatorKind Op) { 8412 auto Lookup = [&](OverloadedOperatorKind OO) { 8413 Self.LookupOverloadedOperatorName(OO, S, Operators); 8414 }; 8415 8416 // Every defaulted operator looks up itself. 8417 Lookup(Op); 8418 // ... and the rewritten form of itself, if any. 8419 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op)) 8420 Lookup(ExtraOp); 8421 8422 // For 'operator<=>', we also form a 'cmp != 0' expression, and might 8423 // synthesize a three-way comparison from '<' and '=='. In a dependent 8424 // context, we also need to look up '==' in case we implicitly declare a 8425 // defaulted 'operator=='. 8426 if (Op == OO_Spaceship) { 8427 Lookup(OO_ExclaimEqual); 8428 Lookup(OO_Less); 8429 Lookup(OO_EqualEqual); 8430 } 8431 } 8432 8433 bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD, 8434 DefaultedComparisonKind DCK) { 8435 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison"); 8436 8437 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()); 8438 assert(RD && "defaulted comparison is not defaulted in a class"); 8439 8440 // Perform any unqualified lookups we're going to need to default this 8441 // function. 8442 if (S) { 8443 UnresolvedSet<32> Operators; 8444 lookupOperatorsForDefaultedComparison(*this, S, Operators, 8445 FD->getOverloadedOperator()); 8446 FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create( 8447 Context, Operators.pairs())); 8448 } 8449 8450 // C++2a [class.compare.default]p1: 8451 // A defaulted comparison operator function for some class C shall be a 8452 // non-template function declared in the member-specification of C that is 8453 // -- a non-static const member of C having one parameter of type 8454 // const C&, or 8455 // -- a friend of C having two parameters of type const C& or two 8456 // parameters of type C. 8457 QualType ExpectedParmType1 = Context.getRecordType(RD); 8458 QualType ExpectedParmType2 = 8459 Context.getLValueReferenceType(ExpectedParmType1.withConst()); 8460 if (isa<CXXMethodDecl>(FD)) 8461 ExpectedParmType1 = ExpectedParmType2; 8462 for (const ParmVarDecl *Param : FD->parameters()) { 8463 if (!Param->getType()->isDependentType() && 8464 !Context.hasSameType(Param->getType(), ExpectedParmType1) && 8465 !Context.hasSameType(Param->getType(), ExpectedParmType2)) { 8466 // Don't diagnose an implicit 'operator=='; we will have diagnosed the 8467 // corresponding defaulted 'operator<=>' already. 8468 if (!FD->isImplicit()) { 8469 Diag(FD->getLocation(), diag::err_defaulted_comparison_param) 8470 << (int)DCK << Param->getType() << ExpectedParmType1 8471 << !isa<CXXMethodDecl>(FD) 8472 << ExpectedParmType2 << Param->getSourceRange(); 8473 } 8474 return true; 8475 } 8476 } 8477 if (FD->getNumParams() == 2 && 8478 !Context.hasSameType(FD->getParamDecl(0)->getType(), 8479 FD->getParamDecl(1)->getType())) { 8480 if (!FD->isImplicit()) { 8481 Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch) 8482 << (int)DCK 8483 << FD->getParamDecl(0)->getType() 8484 << FD->getParamDecl(0)->getSourceRange() 8485 << FD->getParamDecl(1)->getType() 8486 << FD->getParamDecl(1)->getSourceRange(); 8487 } 8488 return true; 8489 } 8490 8491 // ... non-static const member ... 8492 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 8493 assert(!MD->isStatic() && "comparison function cannot be a static member"); 8494 if (!MD->isConst()) { 8495 SourceLocation InsertLoc; 8496 if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc()) 8497 InsertLoc = getLocForEndOfToken(Loc.getRParenLoc()); 8498 // Don't diagnose an implicit 'operator=='; we will have diagnosed the 8499 // corresponding defaulted 'operator<=>' already. 8500 if (!MD->isImplicit()) { 8501 Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const) 8502 << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const"); 8503 } 8504 8505 // Add the 'const' to the type to recover. 8506 const auto *FPT = MD->getType()->castAs<FunctionProtoType>(); 8507 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8508 EPI.TypeQuals.addConst(); 8509 MD->setType(Context.getFunctionType(FPT->getReturnType(), 8510 FPT->getParamTypes(), EPI)); 8511 } 8512 } else { 8513 // A non-member function declared in a class must be a friend. 8514 assert(FD->getFriendObjectKind() && "expected a friend declaration"); 8515 } 8516 8517 // C++2a [class.eq]p1, [class.rel]p1: 8518 // A [defaulted comparison other than <=>] shall have a declared return 8519 // type bool. 8520 if (DCK != DefaultedComparisonKind::ThreeWay && 8521 !FD->getDeclaredReturnType()->isDependentType() && 8522 !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) { 8523 Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool) 8524 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy 8525 << FD->getReturnTypeSourceRange(); 8526 return true; 8527 } 8528 // C++2a [class.spaceship]p2 [P2002R0]: 8529 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise, 8530 // R shall not contain a placeholder type. 8531 if (DCK == DefaultedComparisonKind::ThreeWay && 8532 FD->getDeclaredReturnType()->getContainedDeducedType() && 8533 !Context.hasSameType(FD->getDeclaredReturnType(), 8534 Context.getAutoDeductType())) { 8535 Diag(FD->getLocation(), 8536 diag::err_defaulted_comparison_deduced_return_type_not_auto) 8537 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy 8538 << FD->getReturnTypeSourceRange(); 8539 return true; 8540 } 8541 8542 // For a defaulted function in a dependent class, defer all remaining checks 8543 // until instantiation. 8544 if (RD->isDependentType()) 8545 return false; 8546 8547 // Determine whether the function should be defined as deleted. 8548 DefaultedComparisonInfo Info = 8549 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit(); 8550 8551 bool First = FD == FD->getCanonicalDecl(); 8552 8553 // If we want to delete the function, then do so; there's nothing else to 8554 // check in that case. 8555 if (Info.Deleted) { 8556 if (!First) { 8557 // C++11 [dcl.fct.def.default]p4: 8558 // [For a] user-provided explicitly-defaulted function [...] if such a 8559 // function is implicitly defined as deleted, the program is ill-formed. 8560 // 8561 // This is really just a consequence of the general rule that you can 8562 // only delete a function on its first declaration. 8563 Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes) 8564 << FD->isImplicit() << (int)DCK; 8565 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8566 DefaultedComparisonAnalyzer::ExplainDeleted) 8567 .visit(); 8568 return true; 8569 } 8570 8571 SetDeclDeleted(FD, FD->getLocation()); 8572 if (!inTemplateInstantiation() && !FD->isImplicit()) { 8573 Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted) 8574 << (int)DCK; 8575 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8576 DefaultedComparisonAnalyzer::ExplainDeleted) 8577 .visit(); 8578 } 8579 return false; 8580 } 8581 8582 // C++2a [class.spaceship]p2: 8583 // The return type is deduced as the common comparison type of R0, R1, ... 8584 if (DCK == DefaultedComparisonKind::ThreeWay && 8585 FD->getDeclaredReturnType()->isUndeducedAutoType()) { 8586 SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin(); 8587 if (RetLoc.isInvalid()) 8588 RetLoc = FD->getBeginLoc(); 8589 // FIXME: Should we really care whether we have the complete type and the 8590 // 'enumerator' constants here? A forward declaration seems sufficient. 8591 QualType Cat = CheckComparisonCategoryType( 8592 Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator); 8593 if (Cat.isNull()) 8594 return true; 8595 Context.adjustDeducedFunctionResultType( 8596 FD, SubstAutoType(FD->getDeclaredReturnType(), Cat)); 8597 } 8598 8599 // C++2a [dcl.fct.def.default]p3 [P2002R0]: 8600 // An explicitly-defaulted function that is not defined as deleted may be 8601 // declared constexpr or consteval only if it is constexpr-compatible. 8602 // C++2a [class.compare.default]p3 [P2002R0]: 8603 // A defaulted comparison function is constexpr-compatible if it satisfies 8604 // the requirements for a constexpr function [...] 8605 // The only relevant requirements are that the parameter and return types are 8606 // literal types. The remaining conditions are checked by the analyzer. 8607 if (FD->isConstexpr()) { 8608 if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) && 8609 CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) && 8610 !Info.Constexpr) { 8611 Diag(FD->getBeginLoc(), 8612 diag::err_incorrect_defaulted_comparison_constexpr) 8613 << FD->isImplicit() << (int)DCK << FD->isConsteval(); 8614 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8615 DefaultedComparisonAnalyzer::ExplainConstexpr) 8616 .visit(); 8617 } 8618 } 8619 8620 // C++2a [dcl.fct.def.default]p3 [P2002R0]: 8621 // If a constexpr-compatible function is explicitly defaulted on its first 8622 // declaration, it is implicitly considered to be constexpr. 8623 // FIXME: Only applying this to the first declaration seems problematic, as 8624 // simple reorderings can affect the meaning of the program. 8625 if (First && !FD->isConstexpr() && Info.Constexpr) 8626 FD->setConstexprKind(ConstexprSpecKind::Constexpr); 8627 8628 // C++2a [except.spec]p3: 8629 // If a declaration of a function does not have a noexcept-specifier 8630 // [and] is defaulted on its first declaration, [...] the exception 8631 // specification is as specified below 8632 if (FD->getExceptionSpecType() == EST_None) { 8633 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 8634 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8635 EPI.ExceptionSpec.Type = EST_Unevaluated; 8636 EPI.ExceptionSpec.SourceDecl = FD; 8637 FD->setType(Context.getFunctionType(FPT->getReturnType(), 8638 FPT->getParamTypes(), EPI)); 8639 } 8640 8641 return false; 8642 } 8643 8644 void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD, 8645 FunctionDecl *Spaceship) { 8646 Sema::CodeSynthesisContext Ctx; 8647 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison; 8648 Ctx.PointOfInstantiation = Spaceship->getEndLoc(); 8649 Ctx.Entity = Spaceship; 8650 pushCodeSynthesisContext(Ctx); 8651 8652 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship)) 8653 EqualEqual->setImplicit(); 8654 8655 popCodeSynthesisContext(); 8656 } 8657 8658 void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD, 8659 DefaultedComparisonKind DCK) { 8660 assert(FD->isDefaulted() && !FD->isDeleted() && 8661 !FD->doesThisDeclarationHaveABody()); 8662 if (FD->willHaveBody() || FD->isInvalidDecl()) 8663 return; 8664 8665 SynthesizedFunctionScope Scope(*this, FD); 8666 8667 // Add a context note for diagnostics produced after this point. 8668 Scope.addContextNote(UseLoc); 8669 8670 { 8671 // Build and set up the function body. 8672 CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent()); 8673 SourceLocation BodyLoc = 8674 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation(); 8675 StmtResult Body = 8676 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build(); 8677 if (Body.isInvalid()) { 8678 FD->setInvalidDecl(); 8679 return; 8680 } 8681 FD->setBody(Body.get()); 8682 FD->markUsed(Context); 8683 } 8684 8685 // The exception specification is needed because we are defining the 8686 // function. Note that this will reuse the body we just built. 8687 ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>()); 8688 8689 if (ASTMutationListener *L = getASTMutationListener()) 8690 L->CompletedImplicitDefinition(FD); 8691 } 8692 8693 static Sema::ImplicitExceptionSpecification 8694 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, 8695 FunctionDecl *FD, 8696 Sema::DefaultedComparisonKind DCK) { 8697 ComputingExceptionSpec CES(S, FD, Loc); 8698 Sema::ImplicitExceptionSpecification ExceptSpec(S); 8699 8700 if (FD->isInvalidDecl()) 8701 return ExceptSpec; 8702 8703 // The common case is that we just defined the comparison function. In that 8704 // case, just look at whether the body can throw. 8705 if (FD->hasBody()) { 8706 ExceptSpec.CalledStmt(FD->getBody()); 8707 } else { 8708 // Otherwise, build a body so we can check it. This should ideally only 8709 // happen when we're not actually marking the function referenced. (This is 8710 // only really important for efficiency: we don't want to build and throw 8711 // away bodies for comparison functions more than we strictly need to.) 8712 8713 // Pretend to synthesize the function body in an unevaluated context. 8714 // Note that we can't actually just go ahead and define the function here: 8715 // we are not permitted to mark its callees as referenced. 8716 Sema::SynthesizedFunctionScope Scope(S, FD); 8717 EnterExpressionEvaluationContext Context( 8718 S, Sema::ExpressionEvaluationContext::Unevaluated); 8719 8720 CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent()); 8721 SourceLocation BodyLoc = 8722 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation(); 8723 StmtResult Body = 8724 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build(); 8725 if (!Body.isInvalid()) 8726 ExceptSpec.CalledStmt(Body.get()); 8727 8728 // FIXME: Can we hold onto this body and just transform it to potentially 8729 // evaluated when we're asked to define the function rather than rebuilding 8730 // it? Either that, or we should only build the bits of the body that we 8731 // need (the expressions, not the statements). 8732 } 8733 8734 return ExceptSpec; 8735 } 8736 8737 void Sema::CheckDelayedMemberExceptionSpecs() { 8738 decltype(DelayedOverridingExceptionSpecChecks) Overriding; 8739 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent; 8740 8741 std::swap(Overriding, DelayedOverridingExceptionSpecChecks); 8742 std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks); 8743 8744 // Perform any deferred checking of exception specifications for virtual 8745 // destructors. 8746 for (auto &Check : Overriding) 8747 CheckOverridingFunctionExceptionSpec(Check.first, Check.second); 8748 8749 // Perform any deferred checking of exception specifications for befriended 8750 // special members. 8751 for (auto &Check : Equivalent) 8752 CheckEquivalentExceptionSpec(Check.second, Check.first); 8753 } 8754 8755 namespace { 8756 /// CRTP base class for visiting operations performed by a special member 8757 /// function (or inherited constructor). 8758 template<typename Derived> 8759 struct SpecialMemberVisitor { 8760 Sema &S; 8761 CXXMethodDecl *MD; 8762 Sema::CXXSpecialMember CSM; 8763 Sema::InheritedConstructorInfo *ICI; 8764 8765 // Properties of the special member, computed for convenience. 8766 bool IsConstructor = false, IsAssignment = false, ConstArg = false; 8767 8768 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 8769 Sema::InheritedConstructorInfo *ICI) 8770 : S(S), MD(MD), CSM(CSM), ICI(ICI) { 8771 switch (CSM) { 8772 case Sema::CXXDefaultConstructor: 8773 case Sema::CXXCopyConstructor: 8774 case Sema::CXXMoveConstructor: 8775 IsConstructor = true; 8776 break; 8777 case Sema::CXXCopyAssignment: 8778 case Sema::CXXMoveAssignment: 8779 IsAssignment = true; 8780 break; 8781 case Sema::CXXDestructor: 8782 break; 8783 case Sema::CXXInvalid: 8784 llvm_unreachable("invalid special member kind"); 8785 } 8786 8787 if (MD->getNumParams()) { 8788 if (const ReferenceType *RT = 8789 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 8790 ConstArg = RT->getPointeeType().isConstQualified(); 8791 } 8792 } 8793 8794 Derived &getDerived() { return static_cast<Derived&>(*this); } 8795 8796 /// Is this a "move" special member? 8797 bool isMove() const { 8798 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment; 8799 } 8800 8801 /// Look up the corresponding special member in the given class. 8802 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class, 8803 unsigned Quals, bool IsMutable) { 8804 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 8805 ConstArg && !IsMutable); 8806 } 8807 8808 /// Look up the constructor for the specified base class to see if it's 8809 /// overridden due to this being an inherited constructor. 8810 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) { 8811 if (!ICI) 8812 return {}; 8813 assert(CSM == Sema::CXXDefaultConstructor); 8814 auto *BaseCtor = 8815 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor(); 8816 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first) 8817 return MD; 8818 return {}; 8819 } 8820 8821 /// A base or member subobject. 8822 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 8823 8824 /// Get the location to use for a subobject in diagnostics. 8825 static SourceLocation getSubobjectLoc(Subobject Subobj) { 8826 // FIXME: For an indirect virtual base, the direct base leading to 8827 // the indirect virtual base would be a more useful choice. 8828 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>()) 8829 return B->getBaseTypeLoc(); 8830 else 8831 return Subobj.get<FieldDecl*>()->getLocation(); 8832 } 8833 8834 enum BasesToVisit { 8835 /// Visit all non-virtual (direct) bases. 8836 VisitNonVirtualBases, 8837 /// Visit all direct bases, virtual or not. 8838 VisitDirectBases, 8839 /// Visit all non-virtual bases, and all virtual bases if the class 8840 /// is not abstract. 8841 VisitPotentiallyConstructedBases, 8842 /// Visit all direct or virtual bases. 8843 VisitAllBases 8844 }; 8845 8846 // Visit the bases and members of the class. 8847 bool visit(BasesToVisit Bases) { 8848 CXXRecordDecl *RD = MD->getParent(); 8849 8850 if (Bases == VisitPotentiallyConstructedBases) 8851 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases; 8852 8853 for (auto &B : RD->bases()) 8854 if ((Bases == VisitDirectBases || !B.isVirtual()) && 8855 getDerived().visitBase(&B)) 8856 return true; 8857 8858 if (Bases == VisitAllBases) 8859 for (auto &B : RD->vbases()) 8860 if (getDerived().visitBase(&B)) 8861 return true; 8862 8863 for (auto *F : RD->fields()) 8864 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() && 8865 getDerived().visitField(F)) 8866 return true; 8867 8868 return false; 8869 } 8870 }; 8871 } 8872 8873 namespace { 8874 struct SpecialMemberDeletionInfo 8875 : SpecialMemberVisitor<SpecialMemberDeletionInfo> { 8876 bool Diagnose; 8877 8878 SourceLocation Loc; 8879 8880 bool AllFieldsAreConst; 8881 8882 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 8883 Sema::CXXSpecialMember CSM, 8884 Sema::InheritedConstructorInfo *ICI, bool Diagnose) 8885 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose), 8886 Loc(MD->getLocation()), AllFieldsAreConst(true) {} 8887 8888 bool inUnion() const { return MD->getParent()->isUnion(); } 8889 8890 Sema::CXXSpecialMember getEffectiveCSM() { 8891 return ICI ? Sema::CXXInvalid : CSM; 8892 } 8893 8894 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType); 8895 8896 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); } 8897 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); } 8898 8899 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 8900 bool shouldDeleteForField(FieldDecl *FD); 8901 bool shouldDeleteForAllConstMembers(); 8902 8903 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 8904 unsigned Quals); 8905 bool shouldDeleteForSubobjectCall(Subobject Subobj, 8906 Sema::SpecialMemberOverloadResult SMOR, 8907 bool IsDtorCallInCtor); 8908 8909 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 8910 }; 8911 } 8912 8913 /// Is the given special member inaccessible when used on the given 8914 /// sub-object. 8915 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 8916 CXXMethodDecl *target) { 8917 /// If we're operating on a base class, the object type is the 8918 /// type of this special member. 8919 QualType objectTy; 8920 AccessSpecifier access = target->getAccess(); 8921 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 8922 objectTy = S.Context.getTypeDeclType(MD->getParent()); 8923 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 8924 8925 // If we're operating on a field, the object type is the type of the field. 8926 } else { 8927 objectTy = S.Context.getTypeDeclType(target->getParent()); 8928 } 8929 8930 return S.isMemberAccessibleForDeletion( 8931 target->getParent(), DeclAccessPair::make(target, access), objectTy); 8932 } 8933 8934 /// Check whether we should delete a special member due to the implicit 8935 /// definition containing a call to a special member of a subobject. 8936 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 8937 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR, 8938 bool IsDtorCallInCtor) { 8939 CXXMethodDecl *Decl = SMOR.getMethod(); 8940 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 8941 8942 int DiagKind = -1; 8943 8944 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 8945 DiagKind = !Decl ? 0 : 1; 8946 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 8947 DiagKind = 2; 8948 else if (!isAccessible(Subobj, Decl)) 8949 DiagKind = 3; 8950 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 8951 !Decl->isTrivial()) { 8952 // A member of a union must have a trivial corresponding special member. 8953 // As a weird special case, a destructor call from a union's constructor 8954 // must be accessible and non-deleted, but need not be trivial. Such a 8955 // destructor is never actually called, but is semantically checked as 8956 // if it were. 8957 DiagKind = 4; 8958 } 8959 8960 if (DiagKind == -1) 8961 return false; 8962 8963 if (Diagnose) { 8964 if (Field) { 8965 S.Diag(Field->getLocation(), 8966 diag::note_deleted_special_member_class_subobject) 8967 << getEffectiveCSM() << MD->getParent() << /*IsField*/true 8968 << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false; 8969 } else { 8970 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 8971 S.Diag(Base->getBeginLoc(), 8972 diag::note_deleted_special_member_class_subobject) 8973 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 8974 << Base->getType() << DiagKind << IsDtorCallInCtor 8975 << /*IsObjCPtr*/false; 8976 } 8977 8978 if (DiagKind == 1) 8979 S.NoteDeletedFunction(Decl); 8980 // FIXME: Explain inaccessibility if DiagKind == 3. 8981 } 8982 8983 return true; 8984 } 8985 8986 /// Check whether we should delete a special member function due to having a 8987 /// direct or virtual base class or non-static data member of class type M. 8988 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 8989 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 8990 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 8991 bool IsMutable = Field && Field->isMutable(); 8992 8993 // C++11 [class.ctor]p5: 8994 // -- any direct or virtual base class, or non-static data member with no 8995 // brace-or-equal-initializer, has class type M (or array thereof) and 8996 // either M has no default constructor or overload resolution as applied 8997 // to M's default constructor results in an ambiguity or in a function 8998 // that is deleted or inaccessible 8999 // C++11 [class.copy]p11, C++11 [class.copy]p23: 9000 // -- a direct or virtual base class B that cannot be copied/moved because 9001 // overload resolution, as applied to B's corresponding special member, 9002 // results in an ambiguity or a function that is deleted or inaccessible 9003 // from the defaulted special member 9004 // C++11 [class.dtor]p5: 9005 // -- any direct or virtual base class [...] has a type with a destructor 9006 // that is deleted or inaccessible 9007 if (!(CSM == Sema::CXXDefaultConstructor && 9008 Field && Field->hasInClassInitializer()) && 9009 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 9010 false)) 9011 return true; 9012 9013 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 9014 // -- any direct or virtual base class or non-static data member has a 9015 // type with a destructor that is deleted or inaccessible 9016 if (IsConstructor) { 9017 Sema::SpecialMemberOverloadResult SMOR = 9018 S.LookupSpecialMember(Class, Sema::CXXDestructor, 9019 false, false, false, false, false); 9020 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 9021 return true; 9022 } 9023 9024 return false; 9025 } 9026 9027 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember( 9028 FieldDecl *FD, QualType FieldType) { 9029 // The defaulted special functions are defined as deleted if this is a variant 9030 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak 9031 // type under ARC. 9032 if (!FieldType.hasNonTrivialObjCLifetime()) 9033 return false; 9034 9035 // Don't make the defaulted default constructor defined as deleted if the 9036 // member has an in-class initializer. 9037 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) 9038 return false; 9039 9040 if (Diagnose) { 9041 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent()); 9042 S.Diag(FD->getLocation(), 9043 diag::note_deleted_special_member_class_subobject) 9044 << getEffectiveCSM() << ParentClass << /*IsField*/true 9045 << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true; 9046 } 9047 9048 return true; 9049 } 9050 9051 /// Check whether we should delete a special member function due to the class 9052 /// having a particular direct or virtual base class. 9053 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 9054 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 9055 // If program is correct, BaseClass cannot be null, but if it is, the error 9056 // must be reported elsewhere. 9057 if (!BaseClass) 9058 return false; 9059 // If we have an inheriting constructor, check whether we're calling an 9060 // inherited constructor instead of a default constructor. 9061 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 9062 if (auto *BaseCtor = SMOR.getMethod()) { 9063 // Note that we do not check access along this path; other than that, 9064 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false); 9065 // FIXME: Check that the base has a usable destructor! Sink this into 9066 // shouldDeleteForClassSubobject. 9067 if (BaseCtor->isDeleted() && Diagnose) { 9068 S.Diag(Base->getBeginLoc(), 9069 diag::note_deleted_special_member_class_subobject) 9070 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 9071 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false 9072 << /*IsObjCPtr*/false; 9073 S.NoteDeletedFunction(BaseCtor); 9074 } 9075 return BaseCtor->isDeleted(); 9076 } 9077 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 9078 } 9079 9080 /// Check whether we should delete a special member function due to the class 9081 /// having a particular non-static data member. 9082 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 9083 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 9084 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 9085 9086 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType)) 9087 return true; 9088 9089 if (CSM == Sema::CXXDefaultConstructor) { 9090 // For a default constructor, all references must be initialized in-class 9091 // and, if a union, it must have a non-const member. 9092 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 9093 if (Diagnose) 9094 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 9095 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0; 9096 return true; 9097 } 9098 // C++11 [class.ctor]p5: any non-variant non-static data member of 9099 // const-qualified type (or array thereof) with no 9100 // brace-or-equal-initializer does not have a user-provided default 9101 // constructor. 9102 if (!inUnion() && FieldType.isConstQualified() && 9103 !FD->hasInClassInitializer() && 9104 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 9105 if (Diagnose) 9106 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 9107 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1; 9108 return true; 9109 } 9110 9111 if (inUnion() && !FieldType.isConstQualified()) 9112 AllFieldsAreConst = false; 9113 } else if (CSM == Sema::CXXCopyConstructor) { 9114 // For a copy constructor, data members must not be of rvalue reference 9115 // type. 9116 if (FieldType->isRValueReferenceType()) { 9117 if (Diagnose) 9118 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 9119 << MD->getParent() << FD << FieldType; 9120 return true; 9121 } 9122 } else if (IsAssignment) { 9123 // For an assignment operator, data members must not be of reference type. 9124 if (FieldType->isReferenceType()) { 9125 if (Diagnose) 9126 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 9127 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0; 9128 return true; 9129 } 9130 if (!FieldRecord && FieldType.isConstQualified()) { 9131 // C++11 [class.copy]p23: 9132 // -- a non-static data member of const non-class type (or array thereof) 9133 if (Diagnose) 9134 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 9135 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1; 9136 return true; 9137 } 9138 } 9139 9140 if (FieldRecord) { 9141 // Some additional restrictions exist on the variant members. 9142 if (!inUnion() && FieldRecord->isUnion() && 9143 FieldRecord->isAnonymousStructOrUnion()) { 9144 bool AllVariantFieldsAreConst = true; 9145 9146 // FIXME: Handle anonymous unions declared within anonymous unions. 9147 for (auto *UI : FieldRecord->fields()) { 9148 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 9149 9150 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType)) 9151 return true; 9152 9153 if (!UnionFieldType.isConstQualified()) 9154 AllVariantFieldsAreConst = false; 9155 9156 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 9157 if (UnionFieldRecord && 9158 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 9159 UnionFieldType.getCVRQualifiers())) 9160 return true; 9161 } 9162 9163 // At least one member in each anonymous union must be non-const 9164 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 9165 !FieldRecord->field_empty()) { 9166 if (Diagnose) 9167 S.Diag(FieldRecord->getLocation(), 9168 diag::note_deleted_default_ctor_all_const) 9169 << !!ICI << MD->getParent() << /*anonymous union*/1; 9170 return true; 9171 } 9172 9173 // Don't check the implicit member of the anonymous union type. 9174 // This is technically non-conformant, but sanity demands it. 9175 return false; 9176 } 9177 9178 if (shouldDeleteForClassSubobject(FieldRecord, FD, 9179 FieldType.getCVRQualifiers())) 9180 return true; 9181 } 9182 9183 return false; 9184 } 9185 9186 /// C++11 [class.ctor] p5: 9187 /// A defaulted default constructor for a class X is defined as deleted if 9188 /// X is a union and all of its variant members are of const-qualified type. 9189 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 9190 // This is a silly definition, because it gives an empty union a deleted 9191 // default constructor. Don't do that. 9192 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) { 9193 bool AnyFields = false; 9194 for (auto *F : MD->getParent()->fields()) 9195 if ((AnyFields = !F->isUnnamedBitfield())) 9196 break; 9197 if (!AnyFields) 9198 return false; 9199 if (Diagnose) 9200 S.Diag(MD->getParent()->getLocation(), 9201 diag::note_deleted_default_ctor_all_const) 9202 << !!ICI << MD->getParent() << /*not anonymous union*/0; 9203 return true; 9204 } 9205 return false; 9206 } 9207 9208 /// Determine whether a defaulted special member function should be defined as 9209 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 9210 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 9211 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 9212 InheritedConstructorInfo *ICI, 9213 bool Diagnose) { 9214 if (MD->isInvalidDecl()) 9215 return false; 9216 CXXRecordDecl *RD = MD->getParent(); 9217 assert(!RD->isDependentType() && "do deletion after instantiation"); 9218 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 9219 return false; 9220 9221 // C++11 [expr.lambda.prim]p19: 9222 // The closure type associated with a lambda-expression has a 9223 // deleted (8.4.3) default constructor and a deleted copy 9224 // assignment operator. 9225 // C++2a adds back these operators if the lambda has no lambda-capture. 9226 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() && 9227 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 9228 if (Diagnose) 9229 Diag(RD->getLocation(), diag::note_lambda_decl); 9230 return true; 9231 } 9232 9233 // For an anonymous struct or union, the copy and assignment special members 9234 // will never be used, so skip the check. For an anonymous union declared at 9235 // namespace scope, the constructor and destructor are used. 9236 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 9237 RD->isAnonymousStructOrUnion()) 9238 return false; 9239 9240 // C++11 [class.copy]p7, p18: 9241 // If the class definition declares a move constructor or move assignment 9242 // operator, an implicitly declared copy constructor or copy assignment 9243 // operator is defined as deleted. 9244 if (MD->isImplicit() && 9245 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 9246 CXXMethodDecl *UserDeclaredMove = nullptr; 9247 9248 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the 9249 // deletion of the corresponding copy operation, not both copy operations. 9250 // MSVC 2015 has adopted the standards conforming behavior. 9251 bool DeletesOnlyMatchingCopy = 9252 getLangOpts().MSVCCompat && 9253 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015); 9254 9255 if (RD->hasUserDeclaredMoveConstructor() && 9256 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) { 9257 if (!Diagnose) return true; 9258 9259 // Find any user-declared move constructor. 9260 for (auto *I : RD->ctors()) { 9261 if (I->isMoveConstructor()) { 9262 UserDeclaredMove = I; 9263 break; 9264 } 9265 } 9266 assert(UserDeclaredMove); 9267 } else if (RD->hasUserDeclaredMoveAssignment() && 9268 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) { 9269 if (!Diagnose) return true; 9270 9271 // Find any user-declared move assignment operator. 9272 for (auto *I : RD->methods()) { 9273 if (I->isMoveAssignmentOperator()) { 9274 UserDeclaredMove = I; 9275 break; 9276 } 9277 } 9278 assert(UserDeclaredMove); 9279 } 9280 9281 if (UserDeclaredMove) { 9282 Diag(UserDeclaredMove->getLocation(), 9283 diag::note_deleted_copy_user_declared_move) 9284 << (CSM == CXXCopyAssignment) << RD 9285 << UserDeclaredMove->isMoveAssignmentOperator(); 9286 return true; 9287 } 9288 } 9289 9290 // Do access control from the special member function 9291 ContextRAII MethodContext(*this, MD); 9292 9293 // C++11 [class.dtor]p5: 9294 // -- for a virtual destructor, lookup of the non-array deallocation function 9295 // results in an ambiguity or in a function that is deleted or inaccessible 9296 if (CSM == CXXDestructor && MD->isVirtual()) { 9297 FunctionDecl *OperatorDelete = nullptr; 9298 DeclarationName Name = 9299 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 9300 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 9301 OperatorDelete, /*Diagnose*/false)) { 9302 if (Diagnose) 9303 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 9304 return true; 9305 } 9306 } 9307 9308 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose); 9309 9310 // Per DR1611, do not consider virtual bases of constructors of abstract 9311 // classes, since we are not going to construct them. 9312 // Per DR1658, do not consider virtual bases of destructors of abstract 9313 // classes either. 9314 // Per DR2180, for assignment operators we only assign (and thus only 9315 // consider) direct bases. 9316 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases 9317 : SMI.VisitPotentiallyConstructedBases)) 9318 return true; 9319 9320 if (SMI.shouldDeleteForAllConstMembers()) 9321 return true; 9322 9323 if (getLangOpts().CUDA) { 9324 // We should delete the special member in CUDA mode if target inference 9325 // failed. 9326 // For inherited constructors (non-null ICI), CSM may be passed so that MD 9327 // is treated as certain special member, which may not reflect what special 9328 // member MD really is. However inferCUDATargetForImplicitSpecialMember 9329 // expects CSM to match MD, therefore recalculate CSM. 9330 assert(ICI || CSM == getSpecialMember(MD)); 9331 auto RealCSM = CSM; 9332 if (ICI) 9333 RealCSM = getSpecialMember(MD); 9334 9335 return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD, 9336 SMI.ConstArg, Diagnose); 9337 } 9338 9339 return false; 9340 } 9341 9342 void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) { 9343 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD); 9344 assert(DFK && "not a defaultable function"); 9345 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted"); 9346 9347 if (DFK.isSpecialMember()) { 9348 ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), 9349 nullptr, /*Diagnose=*/true); 9350 } else { 9351 DefaultedComparisonAnalyzer( 9352 *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD, 9353 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted) 9354 .visit(); 9355 } 9356 } 9357 9358 /// Perform lookup for a special member of the specified kind, and determine 9359 /// whether it is trivial. If the triviality can be determined without the 9360 /// lookup, skip it. This is intended for use when determining whether a 9361 /// special member of a containing object is trivial, and thus does not ever 9362 /// perform overload resolution for default constructors. 9363 /// 9364 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 9365 /// member that was most likely to be intended to be trivial, if any. 9366 /// 9367 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to 9368 /// determine whether the special member is trivial. 9369 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 9370 Sema::CXXSpecialMember CSM, unsigned Quals, 9371 bool ConstRHS, 9372 Sema::TrivialABIHandling TAH, 9373 CXXMethodDecl **Selected) { 9374 if (Selected) 9375 *Selected = nullptr; 9376 9377 switch (CSM) { 9378 case Sema::CXXInvalid: 9379 llvm_unreachable("not a special member"); 9380 9381 case Sema::CXXDefaultConstructor: 9382 // C++11 [class.ctor]p5: 9383 // A default constructor is trivial if: 9384 // - all the [direct subobjects] have trivial default constructors 9385 // 9386 // Note, no overload resolution is performed in this case. 9387 if (RD->hasTrivialDefaultConstructor()) 9388 return true; 9389 9390 if (Selected) { 9391 // If there's a default constructor which could have been trivial, dig it 9392 // out. Otherwise, if there's any user-provided default constructor, point 9393 // to that as an example of why there's not a trivial one. 9394 CXXConstructorDecl *DefCtor = nullptr; 9395 if (RD->needsImplicitDefaultConstructor()) 9396 S.DeclareImplicitDefaultConstructor(RD); 9397 for (auto *CI : RD->ctors()) { 9398 if (!CI->isDefaultConstructor()) 9399 continue; 9400 DefCtor = CI; 9401 if (!DefCtor->isUserProvided()) 9402 break; 9403 } 9404 9405 *Selected = DefCtor; 9406 } 9407 9408 return false; 9409 9410 case Sema::CXXDestructor: 9411 // C++11 [class.dtor]p5: 9412 // A destructor is trivial if: 9413 // - all the direct [subobjects] have trivial destructors 9414 if (RD->hasTrivialDestructor() || 9415 (TAH == Sema::TAH_ConsiderTrivialABI && 9416 RD->hasTrivialDestructorForCall())) 9417 return true; 9418 9419 if (Selected) { 9420 if (RD->needsImplicitDestructor()) 9421 S.DeclareImplicitDestructor(RD); 9422 *Selected = RD->getDestructor(); 9423 } 9424 9425 return false; 9426 9427 case Sema::CXXCopyConstructor: 9428 // C++11 [class.copy]p12: 9429 // A copy constructor is trivial if: 9430 // - the constructor selected to copy each direct [subobject] is trivial 9431 if (RD->hasTrivialCopyConstructor() || 9432 (TAH == Sema::TAH_ConsiderTrivialABI && 9433 RD->hasTrivialCopyConstructorForCall())) { 9434 if (Quals == Qualifiers::Const) 9435 // We must either select the trivial copy constructor or reach an 9436 // ambiguity; no need to actually perform overload resolution. 9437 return true; 9438 } else if (!Selected) { 9439 return false; 9440 } 9441 // In C++98, we are not supposed to perform overload resolution here, but we 9442 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 9443 // cases like B as having a non-trivial copy constructor: 9444 // struct A { template<typename T> A(T&); }; 9445 // struct B { mutable A a; }; 9446 goto NeedOverloadResolution; 9447 9448 case Sema::CXXCopyAssignment: 9449 // C++11 [class.copy]p25: 9450 // A copy assignment operator is trivial if: 9451 // - the assignment operator selected to copy each direct [subobject] is 9452 // trivial 9453 if (RD->hasTrivialCopyAssignment()) { 9454 if (Quals == Qualifiers::Const) 9455 return true; 9456 } else if (!Selected) { 9457 return false; 9458 } 9459 // In C++98, we are not supposed to perform overload resolution here, but we 9460 // treat that as a language defect. 9461 goto NeedOverloadResolution; 9462 9463 case Sema::CXXMoveConstructor: 9464 case Sema::CXXMoveAssignment: 9465 NeedOverloadResolution: 9466 Sema::SpecialMemberOverloadResult SMOR = 9467 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 9468 9469 // The standard doesn't describe how to behave if the lookup is ambiguous. 9470 // We treat it as not making the member non-trivial, just like the standard 9471 // mandates for the default constructor. This should rarely matter, because 9472 // the member will also be deleted. 9473 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 9474 return true; 9475 9476 if (!SMOR.getMethod()) { 9477 assert(SMOR.getKind() == 9478 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 9479 return false; 9480 } 9481 9482 // We deliberately don't check if we found a deleted special member. We're 9483 // not supposed to! 9484 if (Selected) 9485 *Selected = SMOR.getMethod(); 9486 9487 if (TAH == Sema::TAH_ConsiderTrivialABI && 9488 (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor)) 9489 return SMOR.getMethod()->isTrivialForCall(); 9490 return SMOR.getMethod()->isTrivial(); 9491 } 9492 9493 llvm_unreachable("unknown special method kind"); 9494 } 9495 9496 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 9497 for (auto *CI : RD->ctors()) 9498 if (!CI->isImplicit()) 9499 return CI; 9500 9501 // Look for constructor templates. 9502 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 9503 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 9504 if (CXXConstructorDecl *CD = 9505 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 9506 return CD; 9507 } 9508 9509 return nullptr; 9510 } 9511 9512 /// The kind of subobject we are checking for triviality. The values of this 9513 /// enumeration are used in diagnostics. 9514 enum TrivialSubobjectKind { 9515 /// The subobject is a base class. 9516 TSK_BaseClass, 9517 /// The subobject is a non-static data member. 9518 TSK_Field, 9519 /// The object is actually the complete object. 9520 TSK_CompleteObject 9521 }; 9522 9523 /// Check whether the special member selected for a given type would be trivial. 9524 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 9525 QualType SubType, bool ConstRHS, 9526 Sema::CXXSpecialMember CSM, 9527 TrivialSubobjectKind Kind, 9528 Sema::TrivialABIHandling TAH, bool Diagnose) { 9529 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 9530 if (!SubRD) 9531 return true; 9532 9533 CXXMethodDecl *Selected; 9534 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 9535 ConstRHS, TAH, Diagnose ? &Selected : nullptr)) 9536 return true; 9537 9538 if (Diagnose) { 9539 if (ConstRHS) 9540 SubType.addConst(); 9541 9542 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 9543 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 9544 << Kind << SubType.getUnqualifiedType(); 9545 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 9546 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 9547 } else if (!Selected) 9548 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 9549 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 9550 else if (Selected->isUserProvided()) { 9551 if (Kind == TSK_CompleteObject) 9552 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 9553 << Kind << SubType.getUnqualifiedType() << CSM; 9554 else { 9555 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 9556 << Kind << SubType.getUnqualifiedType() << CSM; 9557 S.Diag(Selected->getLocation(), diag::note_declared_at); 9558 } 9559 } else { 9560 if (Kind != TSK_CompleteObject) 9561 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 9562 << Kind << SubType.getUnqualifiedType() << CSM; 9563 9564 // Explain why the defaulted or deleted special member isn't trivial. 9565 S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI, 9566 Diagnose); 9567 } 9568 } 9569 9570 return false; 9571 } 9572 9573 /// Check whether the members of a class type allow a special member to be 9574 /// trivial. 9575 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 9576 Sema::CXXSpecialMember CSM, 9577 bool ConstArg, 9578 Sema::TrivialABIHandling TAH, 9579 bool Diagnose) { 9580 for (const auto *FI : RD->fields()) { 9581 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 9582 continue; 9583 9584 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 9585 9586 // Pretend anonymous struct or union members are members of this class. 9587 if (FI->isAnonymousStructOrUnion()) { 9588 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 9589 CSM, ConstArg, TAH, Diagnose)) 9590 return false; 9591 continue; 9592 } 9593 9594 // C++11 [class.ctor]p5: 9595 // A default constructor is trivial if [...] 9596 // -- no non-static data member of its class has a 9597 // brace-or-equal-initializer 9598 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 9599 if (Diagnose) 9600 S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init) 9601 << FI; 9602 return false; 9603 } 9604 9605 // Objective C ARC 4.3.5: 9606 // [...] nontrivally ownership-qualified types are [...] not trivially 9607 // default constructible, copy constructible, move constructible, copy 9608 // assignable, move assignable, or destructible [...] 9609 if (FieldType.hasNonTrivialObjCLifetime()) { 9610 if (Diagnose) 9611 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 9612 << RD << FieldType.getObjCLifetime(); 9613 return false; 9614 } 9615 9616 bool ConstRHS = ConstArg && !FI->isMutable(); 9617 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 9618 CSM, TSK_Field, TAH, Diagnose)) 9619 return false; 9620 } 9621 9622 return true; 9623 } 9624 9625 /// Diagnose why the specified class does not have a trivial special member of 9626 /// the given kind. 9627 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 9628 QualType Ty = Context.getRecordType(RD); 9629 9630 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 9631 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 9632 TSK_CompleteObject, TAH_IgnoreTrivialABI, 9633 /*Diagnose*/true); 9634 } 9635 9636 /// Determine whether a defaulted or deleted special member function is trivial, 9637 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 9638 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 9639 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 9640 TrivialABIHandling TAH, bool Diagnose) { 9641 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 9642 9643 CXXRecordDecl *RD = MD->getParent(); 9644 9645 bool ConstArg = false; 9646 9647 // C++11 [class.copy]p12, p25: [DR1593] 9648 // A [special member] is trivial if [...] its parameter-type-list is 9649 // equivalent to the parameter-type-list of an implicit declaration [...] 9650 switch (CSM) { 9651 case CXXDefaultConstructor: 9652 case CXXDestructor: 9653 // Trivial default constructors and destructors cannot have parameters. 9654 break; 9655 9656 case CXXCopyConstructor: 9657 case CXXCopyAssignment: { 9658 // Trivial copy operations always have const, non-volatile parameter types. 9659 ConstArg = true; 9660 const ParmVarDecl *Param0 = MD->getParamDecl(0); 9661 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 9662 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 9663 if (Diagnose) 9664 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 9665 << Param0->getSourceRange() << Param0->getType() 9666 << Context.getLValueReferenceType( 9667 Context.getRecordType(RD).withConst()); 9668 return false; 9669 } 9670 break; 9671 } 9672 9673 case CXXMoveConstructor: 9674 case CXXMoveAssignment: { 9675 // Trivial move operations always have non-cv-qualified parameters. 9676 const ParmVarDecl *Param0 = MD->getParamDecl(0); 9677 const RValueReferenceType *RT = 9678 Param0->getType()->getAs<RValueReferenceType>(); 9679 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 9680 if (Diagnose) 9681 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 9682 << Param0->getSourceRange() << Param0->getType() 9683 << Context.getRValueReferenceType(Context.getRecordType(RD)); 9684 return false; 9685 } 9686 break; 9687 } 9688 9689 case CXXInvalid: 9690 llvm_unreachable("not a special member"); 9691 } 9692 9693 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 9694 if (Diagnose) 9695 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 9696 diag::note_nontrivial_default_arg) 9697 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 9698 return false; 9699 } 9700 if (MD->isVariadic()) { 9701 if (Diagnose) 9702 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 9703 return false; 9704 } 9705 9706 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 9707 // A copy/move [constructor or assignment operator] is trivial if 9708 // -- the [member] selected to copy/move each direct base class subobject 9709 // is trivial 9710 // 9711 // C++11 [class.copy]p12, C++11 [class.copy]p25: 9712 // A [default constructor or destructor] is trivial if 9713 // -- all the direct base classes have trivial [default constructors or 9714 // destructors] 9715 for (const auto &BI : RD->bases()) 9716 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(), 9717 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose)) 9718 return false; 9719 9720 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 9721 // A copy/move [constructor or assignment operator] for a class X is 9722 // trivial if 9723 // -- for each non-static data member of X that is of class type (or array 9724 // thereof), the constructor selected to copy/move that member is 9725 // trivial 9726 // 9727 // C++11 [class.copy]p12, C++11 [class.copy]p25: 9728 // A [default constructor or destructor] is trivial if 9729 // -- for all of the non-static data members of its class that are of class 9730 // type (or array thereof), each such class has a trivial [default 9731 // constructor or destructor] 9732 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose)) 9733 return false; 9734 9735 // C++11 [class.dtor]p5: 9736 // A destructor is trivial if [...] 9737 // -- the destructor is not virtual 9738 if (CSM == CXXDestructor && MD->isVirtual()) { 9739 if (Diagnose) 9740 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 9741 return false; 9742 } 9743 9744 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 9745 // A [special member] for class X is trivial if [...] 9746 // -- class X has no virtual functions and no virtual base classes 9747 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 9748 if (!Diagnose) 9749 return false; 9750 9751 if (RD->getNumVBases()) { 9752 // Check for virtual bases. We already know that the corresponding 9753 // member in all bases is trivial, so vbases must all be direct. 9754 CXXBaseSpecifier &BS = *RD->vbases_begin(); 9755 assert(BS.isVirtual()); 9756 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1; 9757 return false; 9758 } 9759 9760 // Must have a virtual method. 9761 for (const auto *MI : RD->methods()) { 9762 if (MI->isVirtual()) { 9763 SourceLocation MLoc = MI->getBeginLoc(); 9764 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 9765 return false; 9766 } 9767 } 9768 9769 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 9770 } 9771 9772 // Looks like it's trivial! 9773 return true; 9774 } 9775 9776 namespace { 9777 struct FindHiddenVirtualMethod { 9778 Sema *S; 9779 CXXMethodDecl *Method; 9780 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 9781 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 9782 9783 private: 9784 /// Check whether any most overridden method from MD in Methods 9785 static bool CheckMostOverridenMethods( 9786 const CXXMethodDecl *MD, 9787 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) { 9788 if (MD->size_overridden_methods() == 0) 9789 return Methods.count(MD->getCanonicalDecl()); 9790 for (const CXXMethodDecl *O : MD->overridden_methods()) 9791 if (CheckMostOverridenMethods(O, Methods)) 9792 return true; 9793 return false; 9794 } 9795 9796 public: 9797 /// Member lookup function that determines whether a given C++ 9798 /// method overloads virtual methods in a base class without overriding any, 9799 /// to be used with CXXRecordDecl::lookupInBases(). 9800 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 9801 RecordDecl *BaseRecord = 9802 Specifier->getType()->castAs<RecordType>()->getDecl(); 9803 9804 DeclarationName Name = Method->getDeclName(); 9805 assert(Name.getNameKind() == DeclarationName::Identifier); 9806 9807 bool foundSameNameMethod = false; 9808 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 9809 for (Path.Decls = BaseRecord->lookup(Name).begin(); 9810 Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) { 9811 NamedDecl *D = *Path.Decls; 9812 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 9813 MD = MD->getCanonicalDecl(); 9814 foundSameNameMethod = true; 9815 // Interested only in hidden virtual methods. 9816 if (!MD->isVirtual()) 9817 continue; 9818 // If the method we are checking overrides a method from its base 9819 // don't warn about the other overloaded methods. Clang deviates from 9820 // GCC by only diagnosing overloads of inherited virtual functions that 9821 // do not override any other virtual functions in the base. GCC's 9822 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 9823 // function from a base class. These cases may be better served by a 9824 // warning (not specific to virtual functions) on call sites when the 9825 // call would select a different function from the base class, were it 9826 // visible. 9827 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 9828 if (!S->IsOverload(Method, MD, false)) 9829 return true; 9830 // Collect the overload only if its hidden. 9831 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods)) 9832 overloadedMethods.push_back(MD); 9833 } 9834 } 9835 9836 if (foundSameNameMethod) 9837 OverloadedMethods.append(overloadedMethods.begin(), 9838 overloadedMethods.end()); 9839 return foundSameNameMethod; 9840 } 9841 }; 9842 } // end anonymous namespace 9843 9844 /// Add the most overridden methods from MD to Methods 9845 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 9846 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 9847 if (MD->size_overridden_methods() == 0) 9848 Methods.insert(MD->getCanonicalDecl()); 9849 else 9850 for (const CXXMethodDecl *O : MD->overridden_methods()) 9851 AddMostOverridenMethods(O, Methods); 9852 } 9853 9854 /// Check if a method overloads virtual methods in a base class without 9855 /// overriding any. 9856 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 9857 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 9858 if (!MD->getDeclName().isIdentifier()) 9859 return; 9860 9861 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 9862 /*bool RecordPaths=*/false, 9863 /*bool DetectVirtual=*/false); 9864 FindHiddenVirtualMethod FHVM; 9865 FHVM.Method = MD; 9866 FHVM.S = this; 9867 9868 // Keep the base methods that were overridden or introduced in the subclass 9869 // by 'using' in a set. A base method not in this set is hidden. 9870 CXXRecordDecl *DC = MD->getParent(); 9871 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 9872 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 9873 NamedDecl *ND = *I; 9874 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 9875 ND = shad->getTargetDecl(); 9876 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 9877 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods); 9878 } 9879 9880 if (DC->lookupInBases(FHVM, Paths)) 9881 OverloadedMethods = FHVM.OverloadedMethods; 9882 } 9883 9884 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 9885 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 9886 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 9887 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 9888 PartialDiagnostic PD = PDiag( 9889 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 9890 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 9891 Diag(overloadedMD->getLocation(), PD); 9892 } 9893 } 9894 9895 /// Diagnose methods which overload virtual methods in a base class 9896 /// without overriding any. 9897 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 9898 if (MD->isInvalidDecl()) 9899 return; 9900 9901 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 9902 return; 9903 9904 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 9905 FindHiddenVirtualMethods(MD, OverloadedMethods); 9906 if (!OverloadedMethods.empty()) { 9907 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 9908 << MD << (OverloadedMethods.size() > 1); 9909 9910 NoteHiddenVirtualMethods(MD, OverloadedMethods); 9911 } 9912 } 9913 9914 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) { 9915 auto PrintDiagAndRemoveAttr = [&](unsigned N) { 9916 // No diagnostics if this is a template instantiation. 9917 if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) { 9918 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), 9919 diag::ext_cannot_use_trivial_abi) << &RD; 9920 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), 9921 diag::note_cannot_use_trivial_abi_reason) << &RD << N; 9922 } 9923 RD.dropAttr<TrivialABIAttr>(); 9924 }; 9925 9926 // Ill-formed if the copy and move constructors are deleted. 9927 auto HasNonDeletedCopyOrMoveConstructor = [&]() { 9928 // If the type is dependent, then assume it might have 9929 // implicit copy or move ctor because we won't know yet at this point. 9930 if (RD.isDependentType()) 9931 return true; 9932 if (RD.needsImplicitCopyConstructor() && 9933 !RD.defaultedCopyConstructorIsDeleted()) 9934 return true; 9935 if (RD.needsImplicitMoveConstructor() && 9936 !RD.defaultedMoveConstructorIsDeleted()) 9937 return true; 9938 for (const CXXConstructorDecl *CD : RD.ctors()) 9939 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted()) 9940 return true; 9941 return false; 9942 }; 9943 9944 if (!HasNonDeletedCopyOrMoveConstructor()) { 9945 PrintDiagAndRemoveAttr(0); 9946 return; 9947 } 9948 9949 // Ill-formed if the struct has virtual functions. 9950 if (RD.isPolymorphic()) { 9951 PrintDiagAndRemoveAttr(1); 9952 return; 9953 } 9954 9955 for (const auto &B : RD.bases()) { 9956 // Ill-formed if the base class is non-trivial for the purpose of calls or a 9957 // virtual base. 9958 if (!B.getType()->isDependentType() && 9959 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) { 9960 PrintDiagAndRemoveAttr(2); 9961 return; 9962 } 9963 9964 if (B.isVirtual()) { 9965 PrintDiagAndRemoveAttr(3); 9966 return; 9967 } 9968 } 9969 9970 for (const auto *FD : RD.fields()) { 9971 // Ill-formed if the field is an ObjectiveC pointer or of a type that is 9972 // non-trivial for the purpose of calls. 9973 QualType FT = FD->getType(); 9974 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) { 9975 PrintDiagAndRemoveAttr(4); 9976 return; 9977 } 9978 9979 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>()) 9980 if (!RT->isDependentType() && 9981 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) { 9982 PrintDiagAndRemoveAttr(5); 9983 return; 9984 } 9985 } 9986 } 9987 9988 void Sema::ActOnFinishCXXMemberSpecification( 9989 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, 9990 SourceLocation RBrac, const ParsedAttributesView &AttrList) { 9991 if (!TagDecl) 9992 return; 9993 9994 AdjustDeclIfTemplate(TagDecl); 9995 9996 for (const ParsedAttr &AL : AttrList) { 9997 if (AL.getKind() != ParsedAttr::AT_Visibility) 9998 continue; 9999 AL.setInvalid(); 10000 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL; 10001 } 10002 10003 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 10004 // strict aliasing violation! 10005 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 10006 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 10007 10008 CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl)); 10009 } 10010 10011 /// Find the equality comparison functions that should be implicitly declared 10012 /// in a given class definition, per C++2a [class.compare.default]p3. 10013 static void findImplicitlyDeclaredEqualityComparisons( 10014 ASTContext &Ctx, CXXRecordDecl *RD, 10015 llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) { 10016 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual); 10017 if (!RD->lookup(EqEq).empty()) 10018 // Member operator== explicitly declared: no implicit operator==s. 10019 return; 10020 10021 // Traverse friends looking for an '==' or a '<=>'. 10022 for (FriendDecl *Friend : RD->friends()) { 10023 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl()); 10024 if (!FD) continue; 10025 10026 if (FD->getOverloadedOperator() == OO_EqualEqual) { 10027 // Friend operator== explicitly declared: no implicit operator==s. 10028 Spaceships.clear(); 10029 return; 10030 } 10031 10032 if (FD->getOverloadedOperator() == OO_Spaceship && 10033 FD->isExplicitlyDefaulted()) 10034 Spaceships.push_back(FD); 10035 } 10036 10037 // Look for members named 'operator<=>'. 10038 DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship); 10039 for (NamedDecl *ND : RD->lookup(Cmp)) { 10040 // Note that we could find a non-function here (either a function template 10041 // or a using-declaration). Neither case results in an implicit 10042 // 'operator=='. 10043 if (auto *FD = dyn_cast<FunctionDecl>(ND)) 10044 if (FD->isExplicitlyDefaulted()) 10045 Spaceships.push_back(FD); 10046 } 10047 } 10048 10049 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 10050 /// special functions, such as the default constructor, copy 10051 /// constructor, or destructor, to the given C++ class (C++ 10052 /// [special]p1). This routine can only be executed just before the 10053 /// definition of the class is complete. 10054 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 10055 // Don't add implicit special members to templated classes. 10056 // FIXME: This means unqualified lookups for 'operator=' within a class 10057 // template don't work properly. 10058 if (!ClassDecl->isDependentType()) { 10059 if (ClassDecl->needsImplicitDefaultConstructor()) { 10060 ++getASTContext().NumImplicitDefaultConstructors; 10061 10062 if (ClassDecl->hasInheritedConstructor()) 10063 DeclareImplicitDefaultConstructor(ClassDecl); 10064 } 10065 10066 if (ClassDecl->needsImplicitCopyConstructor()) { 10067 ++getASTContext().NumImplicitCopyConstructors; 10068 10069 // If the properties or semantics of the copy constructor couldn't be 10070 // determined while the class was being declared, force a declaration 10071 // of it now. 10072 if (ClassDecl->needsOverloadResolutionForCopyConstructor() || 10073 ClassDecl->hasInheritedConstructor()) 10074 DeclareImplicitCopyConstructor(ClassDecl); 10075 // For the MS ABI we need to know whether the copy ctor is deleted. A 10076 // prerequisite for deleting the implicit copy ctor is that the class has 10077 // a move ctor or move assignment that is either user-declared or whose 10078 // semantics are inherited from a subobject. FIXME: We should provide a 10079 // more direct way for CodeGen to ask whether the constructor was deleted. 10080 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 10081 (ClassDecl->hasUserDeclaredMoveConstructor() || 10082 ClassDecl->needsOverloadResolutionForMoveConstructor() || 10083 ClassDecl->hasUserDeclaredMoveAssignment() || 10084 ClassDecl->needsOverloadResolutionForMoveAssignment())) 10085 DeclareImplicitCopyConstructor(ClassDecl); 10086 } 10087 10088 if (getLangOpts().CPlusPlus11 && 10089 ClassDecl->needsImplicitMoveConstructor()) { 10090 ++getASTContext().NumImplicitMoveConstructors; 10091 10092 if (ClassDecl->needsOverloadResolutionForMoveConstructor() || 10093 ClassDecl->hasInheritedConstructor()) 10094 DeclareImplicitMoveConstructor(ClassDecl); 10095 } 10096 10097 if (ClassDecl->needsImplicitCopyAssignment()) { 10098 ++getASTContext().NumImplicitCopyAssignmentOperators; 10099 10100 // If we have a dynamic class, then the copy assignment operator may be 10101 // virtual, so we have to declare it immediately. This ensures that, e.g., 10102 // it shows up in the right place in the vtable and that we diagnose 10103 // problems with the implicit exception specification. 10104 if (ClassDecl->isDynamicClass() || 10105 ClassDecl->needsOverloadResolutionForCopyAssignment() || 10106 ClassDecl->hasInheritedAssignment()) 10107 DeclareImplicitCopyAssignment(ClassDecl); 10108 } 10109 10110 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 10111 ++getASTContext().NumImplicitMoveAssignmentOperators; 10112 10113 // Likewise for the move assignment operator. 10114 if (ClassDecl->isDynamicClass() || 10115 ClassDecl->needsOverloadResolutionForMoveAssignment() || 10116 ClassDecl->hasInheritedAssignment()) 10117 DeclareImplicitMoveAssignment(ClassDecl); 10118 } 10119 10120 if (ClassDecl->needsImplicitDestructor()) { 10121 ++getASTContext().NumImplicitDestructors; 10122 10123 // If we have a dynamic class, then the destructor may be virtual, so we 10124 // have to declare the destructor immediately. This ensures that, e.g., it 10125 // shows up in the right place in the vtable and that we diagnose problems 10126 // with the implicit exception specification. 10127 if (ClassDecl->isDynamicClass() || 10128 ClassDecl->needsOverloadResolutionForDestructor()) 10129 DeclareImplicitDestructor(ClassDecl); 10130 } 10131 } 10132 10133 // C++2a [class.compare.default]p3: 10134 // If the member-specification does not explicitly declare any member or 10135 // friend named operator==, an == operator function is declared implicitly 10136 // for each defaulted three-way comparison operator function defined in 10137 // the member-specification 10138 // FIXME: Consider doing this lazily. 10139 // We do this during the initial parse for a class template, not during 10140 // instantiation, so that we can handle unqualified lookups for 'operator==' 10141 // when parsing the template. 10142 if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) { 10143 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships; 10144 findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl, 10145 DefaultedSpaceships); 10146 for (auto *FD : DefaultedSpaceships) 10147 DeclareImplicitEqualityComparison(ClassDecl, FD); 10148 } 10149 } 10150 10151 unsigned 10152 Sema::ActOnReenterTemplateScope(Decl *D, 10153 llvm::function_ref<Scope *()> EnterScope) { 10154 if (!D) 10155 return 0; 10156 AdjustDeclIfTemplate(D); 10157 10158 // In order to get name lookup right, reenter template scopes in order from 10159 // outermost to innermost. 10160 SmallVector<TemplateParameterList *, 4> ParameterLists; 10161 DeclContext *LookupDC = dyn_cast<DeclContext>(D); 10162 10163 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 10164 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 10165 ParameterLists.push_back(DD->getTemplateParameterList(i)); 10166 10167 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 10168 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 10169 ParameterLists.push_back(FTD->getTemplateParameters()); 10170 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 10171 LookupDC = VD->getDeclContext(); 10172 10173 if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate()) 10174 ParameterLists.push_back(VTD->getTemplateParameters()); 10175 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D)) 10176 ParameterLists.push_back(PSD->getTemplateParameters()); 10177 } 10178 } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 10179 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 10180 ParameterLists.push_back(TD->getTemplateParameterList(i)); 10181 10182 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 10183 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 10184 ParameterLists.push_back(CTD->getTemplateParameters()); 10185 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 10186 ParameterLists.push_back(PSD->getTemplateParameters()); 10187 } 10188 } 10189 // FIXME: Alias declarations and concepts. 10190 10191 unsigned Count = 0; 10192 Scope *InnermostTemplateScope = nullptr; 10193 for (TemplateParameterList *Params : ParameterLists) { 10194 // Ignore explicit specializations; they don't contribute to the template 10195 // depth. 10196 if (Params->size() == 0) 10197 continue; 10198 10199 InnermostTemplateScope = EnterScope(); 10200 for (NamedDecl *Param : *Params) { 10201 if (Param->getDeclName()) { 10202 InnermostTemplateScope->AddDecl(Param); 10203 IdResolver.AddDecl(Param); 10204 } 10205 } 10206 ++Count; 10207 } 10208 10209 // Associate the new template scopes with the corresponding entities. 10210 if (InnermostTemplateScope) { 10211 assert(LookupDC && "no enclosing DeclContext for template lookup"); 10212 EnterTemplatedContext(InnermostTemplateScope, LookupDC); 10213 } 10214 10215 return Count; 10216 } 10217 10218 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 10219 if (!RecordD) return; 10220 AdjustDeclIfTemplate(RecordD); 10221 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 10222 PushDeclContext(S, Record); 10223 } 10224 10225 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 10226 if (!RecordD) return; 10227 PopDeclContext(); 10228 } 10229 10230 /// This is used to implement the constant expression evaluation part of the 10231 /// attribute enable_if extension. There is nothing in standard C++ which would 10232 /// require reentering parameters. 10233 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 10234 if (!Param) 10235 return; 10236 10237 S->AddDecl(Param); 10238 if (Param->getDeclName()) 10239 IdResolver.AddDecl(Param); 10240 } 10241 10242 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 10243 /// parsing a top-level (non-nested) C++ class, and we are now 10244 /// parsing those parts of the given Method declaration that could 10245 /// not be parsed earlier (C++ [class.mem]p2), such as default 10246 /// arguments. This action should enter the scope of the given 10247 /// Method declaration as if we had just parsed the qualified method 10248 /// name. However, it should not bring the parameters into scope; 10249 /// that will be performed by ActOnDelayedCXXMethodParameter. 10250 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 10251 } 10252 10253 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 10254 /// C++ method declaration. We're (re-)introducing the given 10255 /// function parameter into scope for use in parsing later parts of 10256 /// the method declaration. For example, we could see an 10257 /// ActOnParamDefaultArgument event for this parameter. 10258 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 10259 if (!ParamD) 10260 return; 10261 10262 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 10263 10264 S->AddDecl(Param); 10265 if (Param->getDeclName()) 10266 IdResolver.AddDecl(Param); 10267 } 10268 10269 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 10270 /// processing the delayed method declaration for Method. The method 10271 /// declaration is now considered finished. There may be a separate 10272 /// ActOnStartOfFunctionDef action later (not necessarily 10273 /// immediately!) for this method, if it was also defined inside the 10274 /// class body. 10275 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 10276 if (!MethodD) 10277 return; 10278 10279 AdjustDeclIfTemplate(MethodD); 10280 10281 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 10282 10283 // Now that we have our default arguments, check the constructor 10284 // again. It could produce additional diagnostics or affect whether 10285 // the class has implicitly-declared destructors, among other 10286 // things. 10287 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 10288 CheckConstructor(Constructor); 10289 10290 // Check the default arguments, which we may have added. 10291 if (!Method->isInvalidDecl()) 10292 CheckCXXDefaultArguments(Method); 10293 } 10294 10295 // Emit the given diagnostic for each non-address-space qualifier. 10296 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator. 10297 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) { 10298 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10299 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) { 10300 bool DiagOccured = false; 10301 FTI.MethodQualifiers->forEachQualifier( 10302 [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName, 10303 SourceLocation SL) { 10304 // This diagnostic should be emitted on any qualifier except an addr 10305 // space qualifier. However, forEachQualifier currently doesn't visit 10306 // addr space qualifiers, so there's no way to write this condition 10307 // right now; we just diagnose on everything. 10308 S.Diag(SL, DiagID) << QualName << SourceRange(SL); 10309 DiagOccured = true; 10310 }); 10311 if (DiagOccured) 10312 D.setInvalidType(); 10313 } 10314 } 10315 10316 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 10317 /// the well-formedness of the constructor declarator @p D with type @p 10318 /// R. If there are any errors in the declarator, this routine will 10319 /// emit diagnostics and set the invalid bit to true. In any case, the type 10320 /// will be updated to reflect a well-formed type for the constructor and 10321 /// returned. 10322 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 10323 StorageClass &SC) { 10324 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 10325 10326 // C++ [class.ctor]p3: 10327 // A constructor shall not be virtual (10.3) or static (9.4). A 10328 // constructor can be invoked for a const, volatile or const 10329 // volatile object. A constructor shall not be declared const, 10330 // volatile, or const volatile (9.3.2). 10331 if (isVirtual) { 10332 if (!D.isInvalidType()) 10333 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 10334 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 10335 << SourceRange(D.getIdentifierLoc()); 10336 D.setInvalidType(); 10337 } 10338 if (SC == SC_Static) { 10339 if (!D.isInvalidType()) 10340 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 10341 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10342 << SourceRange(D.getIdentifierLoc()); 10343 D.setInvalidType(); 10344 SC = SC_None; 10345 } 10346 10347 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 10348 diagnoseIgnoredQualifiers( 10349 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 10350 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 10351 D.getDeclSpec().getRestrictSpecLoc(), 10352 D.getDeclSpec().getAtomicSpecLoc()); 10353 D.setInvalidType(); 10354 } 10355 10356 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor); 10357 10358 // C++0x [class.ctor]p4: 10359 // A constructor shall not be declared with a ref-qualifier. 10360 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10361 if (FTI.hasRefQualifier()) { 10362 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 10363 << FTI.RefQualifierIsLValueRef 10364 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 10365 D.setInvalidType(); 10366 } 10367 10368 // Rebuild the function type "R" without any type qualifiers (in 10369 // case any of the errors above fired) and with "void" as the 10370 // return type, since constructors don't have return types. 10371 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>(); 10372 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 10373 return R; 10374 10375 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 10376 EPI.TypeQuals = Qualifiers(); 10377 EPI.RefQualifier = RQ_None; 10378 10379 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 10380 } 10381 10382 /// CheckConstructor - Checks a fully-formed constructor for 10383 /// well-formedness, issuing any diagnostics required. Returns true if 10384 /// the constructor declarator is invalid. 10385 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 10386 CXXRecordDecl *ClassDecl 10387 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 10388 if (!ClassDecl) 10389 return Constructor->setInvalidDecl(); 10390 10391 // C++ [class.copy]p3: 10392 // A declaration of a constructor for a class X is ill-formed if 10393 // its first parameter is of type (optionally cv-qualified) X and 10394 // either there are no other parameters or else all other 10395 // parameters have default arguments. 10396 if (!Constructor->isInvalidDecl() && 10397 Constructor->hasOneParamOrDefaultArgs() && 10398 Constructor->getTemplateSpecializationKind() != 10399 TSK_ImplicitInstantiation) { 10400 QualType ParamType = Constructor->getParamDecl(0)->getType(); 10401 QualType ClassTy = Context.getTagDeclType(ClassDecl); 10402 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 10403 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 10404 const char *ConstRef 10405 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 10406 : " const &"; 10407 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 10408 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 10409 10410 // FIXME: Rather that making the constructor invalid, we should endeavor 10411 // to fix the type. 10412 Constructor->setInvalidDecl(); 10413 } 10414 } 10415 } 10416 10417 /// CheckDestructor - Checks a fully-formed destructor definition for 10418 /// well-formedness, issuing any diagnostics required. Returns true 10419 /// on error. 10420 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 10421 CXXRecordDecl *RD = Destructor->getParent(); 10422 10423 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 10424 SourceLocation Loc; 10425 10426 if (!Destructor->isImplicit()) 10427 Loc = Destructor->getLocation(); 10428 else 10429 Loc = RD->getLocation(); 10430 10431 // If we have a virtual destructor, look up the deallocation function 10432 if (FunctionDecl *OperatorDelete = 10433 FindDeallocationFunctionForDestructor(Loc, RD)) { 10434 Expr *ThisArg = nullptr; 10435 10436 // If the notional 'delete this' expression requires a non-trivial 10437 // conversion from 'this' to the type of a destroying operator delete's 10438 // first parameter, perform that conversion now. 10439 if (OperatorDelete->isDestroyingOperatorDelete()) { 10440 QualType ParamType = OperatorDelete->getParamDecl(0)->getType(); 10441 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) { 10442 // C++ [class.dtor]p13: 10443 // ... as if for the expression 'delete this' appearing in a 10444 // non-virtual destructor of the destructor's class. 10445 ContextRAII SwitchContext(*this, Destructor); 10446 ExprResult This = 10447 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation()); 10448 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?"); 10449 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing); 10450 if (This.isInvalid()) { 10451 // FIXME: Register this as a context note so that it comes out 10452 // in the right order. 10453 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here); 10454 return true; 10455 } 10456 ThisArg = This.get(); 10457 } 10458 } 10459 10460 DiagnoseUseOfDecl(OperatorDelete, Loc); 10461 MarkFunctionReferenced(Loc, OperatorDelete); 10462 Destructor->setOperatorDelete(OperatorDelete, ThisArg); 10463 } 10464 } 10465 10466 return false; 10467 } 10468 10469 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 10470 /// the well-formednes of the destructor declarator @p D with type @p 10471 /// R. If there are any errors in the declarator, this routine will 10472 /// emit diagnostics and set the declarator to invalid. Even if this happens, 10473 /// will be updated to reflect a well-formed type for the destructor and 10474 /// returned. 10475 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 10476 StorageClass& SC) { 10477 // C++ [class.dtor]p1: 10478 // [...] A typedef-name that names a class is a class-name 10479 // (7.1.3); however, a typedef-name that names a class shall not 10480 // be used as the identifier in the declarator for a destructor 10481 // declaration. 10482 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 10483 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 10484 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name) 10485 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 10486 else if (const TemplateSpecializationType *TST = 10487 DeclaratorType->getAs<TemplateSpecializationType>()) 10488 if (TST->isTypeAlias()) 10489 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name) 10490 << DeclaratorType << 1; 10491 10492 // C++ [class.dtor]p2: 10493 // A destructor is used to destroy objects of its class type. A 10494 // destructor takes no parameters, and no return type can be 10495 // specified for it (not even void). The address of a destructor 10496 // shall not be taken. A destructor shall not be static. A 10497 // destructor can be invoked for a const, volatile or const 10498 // volatile object. A destructor shall not be declared const, 10499 // volatile or const volatile (9.3.2). 10500 if (SC == SC_Static) { 10501 if (!D.isInvalidType()) 10502 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 10503 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10504 << SourceRange(D.getIdentifierLoc()) 10505 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 10506 10507 SC = SC_None; 10508 } 10509 if (!D.isInvalidType()) { 10510 // Destructors don't have return types, but the parser will 10511 // happily parse something like: 10512 // 10513 // class X { 10514 // float ~X(); 10515 // }; 10516 // 10517 // The return type will be eliminated later. 10518 if (D.getDeclSpec().hasTypeSpecifier()) 10519 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 10520 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 10521 << SourceRange(D.getIdentifierLoc()); 10522 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 10523 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 10524 SourceLocation(), 10525 D.getDeclSpec().getConstSpecLoc(), 10526 D.getDeclSpec().getVolatileSpecLoc(), 10527 D.getDeclSpec().getRestrictSpecLoc(), 10528 D.getDeclSpec().getAtomicSpecLoc()); 10529 D.setInvalidType(); 10530 } 10531 } 10532 10533 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor); 10534 10535 // C++0x [class.dtor]p2: 10536 // A destructor shall not be declared with a ref-qualifier. 10537 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10538 if (FTI.hasRefQualifier()) { 10539 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 10540 << FTI.RefQualifierIsLValueRef 10541 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 10542 D.setInvalidType(); 10543 } 10544 10545 // Make sure we don't have any parameters. 10546 if (FTIHasNonVoidParameters(FTI)) { 10547 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 10548 10549 // Delete the parameters. 10550 FTI.freeParams(); 10551 D.setInvalidType(); 10552 } 10553 10554 // Make sure the destructor isn't variadic. 10555 if (FTI.isVariadic) { 10556 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 10557 D.setInvalidType(); 10558 } 10559 10560 // Rebuild the function type "R" without any type qualifiers or 10561 // parameters (in case any of the errors above fired) and with 10562 // "void" as the return type, since destructors don't have return 10563 // types. 10564 if (!D.isInvalidType()) 10565 return R; 10566 10567 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>(); 10568 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 10569 EPI.Variadic = false; 10570 EPI.TypeQuals = Qualifiers(); 10571 EPI.RefQualifier = RQ_None; 10572 return Context.getFunctionType(Context.VoidTy, None, EPI); 10573 } 10574 10575 static void extendLeft(SourceRange &R, SourceRange Before) { 10576 if (Before.isInvalid()) 10577 return; 10578 R.setBegin(Before.getBegin()); 10579 if (R.getEnd().isInvalid()) 10580 R.setEnd(Before.getEnd()); 10581 } 10582 10583 static void extendRight(SourceRange &R, SourceRange After) { 10584 if (After.isInvalid()) 10585 return; 10586 if (R.getBegin().isInvalid()) 10587 R.setBegin(After.getBegin()); 10588 R.setEnd(After.getEnd()); 10589 } 10590 10591 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 10592 /// well-formednes of the conversion function declarator @p D with 10593 /// type @p R. If there are any errors in the declarator, this routine 10594 /// will emit diagnostics and return true. Otherwise, it will return 10595 /// false. Either way, the type @p R will be updated to reflect a 10596 /// well-formed type for the conversion operator. 10597 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 10598 StorageClass& SC) { 10599 // C++ [class.conv.fct]p1: 10600 // Neither parameter types nor return type can be specified. The 10601 // type of a conversion function (8.3.5) is "function taking no 10602 // parameter returning conversion-type-id." 10603 if (SC == SC_Static) { 10604 if (!D.isInvalidType()) 10605 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 10606 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10607 << D.getName().getSourceRange(); 10608 D.setInvalidType(); 10609 SC = SC_None; 10610 } 10611 10612 TypeSourceInfo *ConvTSI = nullptr; 10613 QualType ConvType = 10614 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); 10615 10616 const DeclSpec &DS = D.getDeclSpec(); 10617 if (DS.hasTypeSpecifier() && !D.isInvalidType()) { 10618 // Conversion functions don't have return types, but the parser will 10619 // happily parse something like: 10620 // 10621 // class X { 10622 // float operator bool(); 10623 // }; 10624 // 10625 // The return type will be changed later anyway. 10626 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 10627 << SourceRange(DS.getTypeSpecTypeLoc()) 10628 << SourceRange(D.getIdentifierLoc()); 10629 D.setInvalidType(); 10630 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) { 10631 // It's also plausible that the user writes type qualifiers in the wrong 10632 // place, such as: 10633 // struct S { const operator int(); }; 10634 // FIXME: we could provide a fixit to move the qualifiers onto the 10635 // conversion type. 10636 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 10637 << SourceRange(D.getIdentifierLoc()) << 0; 10638 D.setInvalidType(); 10639 } 10640 10641 const auto *Proto = R->castAs<FunctionProtoType>(); 10642 10643 // Make sure we don't have any parameters. 10644 if (Proto->getNumParams() > 0) { 10645 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 10646 10647 // Delete the parameters. 10648 D.getFunctionTypeInfo().freeParams(); 10649 D.setInvalidType(); 10650 } else if (Proto->isVariadic()) { 10651 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 10652 D.setInvalidType(); 10653 } 10654 10655 // Diagnose "&operator bool()" and other such nonsense. This 10656 // is actually a gcc extension which we don't support. 10657 if (Proto->getReturnType() != ConvType) { 10658 bool NeedsTypedef = false; 10659 SourceRange Before, After; 10660 10661 // Walk the chunks and extract information on them for our diagnostic. 10662 bool PastFunctionChunk = false; 10663 for (auto &Chunk : D.type_objects()) { 10664 switch (Chunk.Kind) { 10665 case DeclaratorChunk::Function: 10666 if (!PastFunctionChunk) { 10667 if (Chunk.Fun.HasTrailingReturnType) { 10668 TypeSourceInfo *TRT = nullptr; 10669 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); 10670 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); 10671 } 10672 PastFunctionChunk = true; 10673 break; 10674 } 10675 LLVM_FALLTHROUGH; 10676 case DeclaratorChunk::Array: 10677 NeedsTypedef = true; 10678 extendRight(After, Chunk.getSourceRange()); 10679 break; 10680 10681 case DeclaratorChunk::Pointer: 10682 case DeclaratorChunk::BlockPointer: 10683 case DeclaratorChunk::Reference: 10684 case DeclaratorChunk::MemberPointer: 10685 case DeclaratorChunk::Pipe: 10686 extendLeft(Before, Chunk.getSourceRange()); 10687 break; 10688 10689 case DeclaratorChunk::Paren: 10690 extendLeft(Before, Chunk.Loc); 10691 extendRight(After, Chunk.EndLoc); 10692 break; 10693 } 10694 } 10695 10696 SourceLocation Loc = Before.isValid() ? Before.getBegin() : 10697 After.isValid() ? After.getBegin() : 10698 D.getIdentifierLoc(); 10699 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); 10700 DB << Before << After; 10701 10702 if (!NeedsTypedef) { 10703 DB << /*don't need a typedef*/0; 10704 10705 // If we can provide a correct fix-it hint, do so. 10706 if (After.isInvalid() && ConvTSI) { 10707 SourceLocation InsertLoc = 10708 getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc()); 10709 DB << FixItHint::CreateInsertion(InsertLoc, " ") 10710 << FixItHint::CreateInsertionFromRange( 10711 InsertLoc, CharSourceRange::getTokenRange(Before)) 10712 << FixItHint::CreateRemoval(Before); 10713 } 10714 } else if (!Proto->getReturnType()->isDependentType()) { 10715 DB << /*typedef*/1 << Proto->getReturnType(); 10716 } else if (getLangOpts().CPlusPlus11) { 10717 DB << /*alias template*/2 << Proto->getReturnType(); 10718 } else { 10719 DB << /*might not be fixable*/3; 10720 } 10721 10722 // Recover by incorporating the other type chunks into the result type. 10723 // Note, this does *not* change the name of the function. This is compatible 10724 // with the GCC extension: 10725 // struct S { &operator int(); } s; 10726 // int &r = s.operator int(); // ok in GCC 10727 // S::operator int&() {} // error in GCC, function name is 'operator int'. 10728 ConvType = Proto->getReturnType(); 10729 } 10730 10731 // C++ [class.conv.fct]p4: 10732 // The conversion-type-id shall not represent a function type nor 10733 // an array type. 10734 if (ConvType->isArrayType()) { 10735 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 10736 ConvType = Context.getPointerType(ConvType); 10737 D.setInvalidType(); 10738 } else if (ConvType->isFunctionType()) { 10739 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 10740 ConvType = Context.getPointerType(ConvType); 10741 D.setInvalidType(); 10742 } 10743 10744 // Rebuild the function type "R" without any parameters (in case any 10745 // of the errors above fired) and with the conversion type as the 10746 // return type. 10747 if (D.isInvalidType()) 10748 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 10749 10750 // C++0x explicit conversion operators. 10751 if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20) 10752 Diag(DS.getExplicitSpecLoc(), 10753 getLangOpts().CPlusPlus11 10754 ? diag::warn_cxx98_compat_explicit_conversion_functions 10755 : diag::ext_explicit_conversion_functions) 10756 << SourceRange(DS.getExplicitSpecRange()); 10757 } 10758 10759 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 10760 /// the declaration of the given C++ conversion function. This routine 10761 /// is responsible for recording the conversion function in the C++ 10762 /// class, if possible. 10763 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 10764 assert(Conversion && "Expected to receive a conversion function declaration"); 10765 10766 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 10767 10768 // Make sure we aren't redeclaring the conversion function. 10769 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 10770 // C++ [class.conv.fct]p1: 10771 // [...] A conversion function is never used to convert a 10772 // (possibly cv-qualified) object to the (possibly cv-qualified) 10773 // same object type (or a reference to it), to a (possibly 10774 // cv-qualified) base class of that type (or a reference to it), 10775 // or to (possibly cv-qualified) void. 10776 QualType ClassType 10777 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 10778 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 10779 ConvType = ConvTypeRef->getPointeeType(); 10780 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 10781 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 10782 /* Suppress diagnostics for instantiations. */; 10783 else if (Conversion->size_overridden_methods() != 0) 10784 /* Suppress diagnostics for overriding virtual function in a base class. */; 10785 else if (ConvType->isRecordType()) { 10786 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 10787 if (ConvType == ClassType) 10788 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 10789 << ClassType; 10790 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType)) 10791 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 10792 << ClassType << ConvType; 10793 } else if (ConvType->isVoidType()) { 10794 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 10795 << ClassType << ConvType; 10796 } 10797 10798 if (FunctionTemplateDecl *ConversionTemplate 10799 = Conversion->getDescribedFunctionTemplate()) 10800 return ConversionTemplate; 10801 10802 return Conversion; 10803 } 10804 10805 namespace { 10806 /// Utility class to accumulate and print a diagnostic listing the invalid 10807 /// specifier(s) on a declaration. 10808 struct BadSpecifierDiagnoser { 10809 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID) 10810 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {} 10811 ~BadSpecifierDiagnoser() { 10812 Diagnostic << Specifiers; 10813 } 10814 10815 template<typename T> void check(SourceLocation SpecLoc, T Spec) { 10816 return check(SpecLoc, DeclSpec::getSpecifierName(Spec)); 10817 } 10818 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) { 10819 return check(SpecLoc, 10820 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy())); 10821 } 10822 void check(SourceLocation SpecLoc, const char *Spec) { 10823 if (SpecLoc.isInvalid()) return; 10824 Diagnostic << SourceRange(SpecLoc, SpecLoc); 10825 if (!Specifiers.empty()) Specifiers += " "; 10826 Specifiers += Spec; 10827 } 10828 10829 Sema &S; 10830 Sema::SemaDiagnosticBuilder Diagnostic; 10831 std::string Specifiers; 10832 }; 10833 } 10834 10835 /// Check the validity of a declarator that we parsed for a deduction-guide. 10836 /// These aren't actually declarators in the grammar, so we need to check that 10837 /// the user didn't specify any pieces that are not part of the deduction-guide 10838 /// grammar. 10839 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R, 10840 StorageClass &SC) { 10841 TemplateName GuidedTemplate = D.getName().TemplateName.get().get(); 10842 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl(); 10843 assert(GuidedTemplateDecl && "missing template decl for deduction guide"); 10844 10845 // C++ [temp.deduct.guide]p3: 10846 // A deduction-gide shall be declared in the same scope as the 10847 // corresponding class template. 10848 if (!CurContext->getRedeclContext()->Equals( 10849 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) { 10850 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope) 10851 << GuidedTemplateDecl; 10852 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here); 10853 } 10854 10855 auto &DS = D.getMutableDeclSpec(); 10856 // We leave 'friend' and 'virtual' to be rejected in the normal way. 10857 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() || 10858 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() || 10859 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) { 10860 BadSpecifierDiagnoser Diagnoser( 10861 *this, D.getIdentifierLoc(), 10862 diag::err_deduction_guide_invalid_specifier); 10863 10864 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec()); 10865 DS.ClearStorageClassSpecs(); 10866 SC = SC_None; 10867 10868 // 'explicit' is permitted. 10869 Diagnoser.check(DS.getInlineSpecLoc(), "inline"); 10870 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn"); 10871 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr"); 10872 DS.ClearConstexprSpec(); 10873 10874 Diagnoser.check(DS.getConstSpecLoc(), "const"); 10875 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict"); 10876 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile"); 10877 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic"); 10878 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned"); 10879 DS.ClearTypeQualifiers(); 10880 10881 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex()); 10882 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign()); 10883 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth()); 10884 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType()); 10885 DS.ClearTypeSpecType(); 10886 } 10887 10888 if (D.isInvalidType()) 10889 return; 10890 10891 // Check the declarator is simple enough. 10892 bool FoundFunction = false; 10893 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) { 10894 if (Chunk.Kind == DeclaratorChunk::Paren) 10895 continue; 10896 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) { 10897 Diag(D.getDeclSpec().getBeginLoc(), 10898 diag::err_deduction_guide_with_complex_decl) 10899 << D.getSourceRange(); 10900 break; 10901 } 10902 if (!Chunk.Fun.hasTrailingReturnType()) { 10903 Diag(D.getName().getBeginLoc(), 10904 diag::err_deduction_guide_no_trailing_return_type); 10905 break; 10906 } 10907 10908 // Check that the return type is written as a specialization of 10909 // the template specified as the deduction-guide's name. 10910 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType(); 10911 TypeSourceInfo *TSI = nullptr; 10912 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI); 10913 assert(TSI && "deduction guide has valid type but invalid return type?"); 10914 bool AcceptableReturnType = false; 10915 bool MightInstantiateToSpecialization = false; 10916 if (auto RetTST = 10917 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) { 10918 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName(); 10919 bool TemplateMatches = 10920 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate); 10921 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches) 10922 AcceptableReturnType = true; 10923 else { 10924 // This could still instantiate to the right type, unless we know it 10925 // names the wrong class template. 10926 auto *TD = SpecifiedName.getAsTemplateDecl(); 10927 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) && 10928 !TemplateMatches); 10929 } 10930 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) { 10931 MightInstantiateToSpecialization = true; 10932 } 10933 10934 if (!AcceptableReturnType) { 10935 Diag(TSI->getTypeLoc().getBeginLoc(), 10936 diag::err_deduction_guide_bad_trailing_return_type) 10937 << GuidedTemplate << TSI->getType() 10938 << MightInstantiateToSpecialization 10939 << TSI->getTypeLoc().getSourceRange(); 10940 } 10941 10942 // Keep going to check that we don't have any inner declarator pieces (we 10943 // could still have a function returning a pointer to a function). 10944 FoundFunction = true; 10945 } 10946 10947 if (D.isFunctionDefinition()) 10948 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function); 10949 } 10950 10951 //===----------------------------------------------------------------------===// 10952 // Namespace Handling 10953 //===----------------------------------------------------------------------===// 10954 10955 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is 10956 /// reopened. 10957 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 10958 SourceLocation Loc, 10959 IdentifierInfo *II, bool *IsInline, 10960 NamespaceDecl *PrevNS) { 10961 assert(*IsInline != PrevNS->isInline()); 10962 10963 if (PrevNS->isInline()) 10964 // The user probably just forgot the 'inline', so suggest that it 10965 // be added back. 10966 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 10967 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 10968 else 10969 S.Diag(Loc, diag::err_inline_namespace_mismatch); 10970 10971 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 10972 *IsInline = PrevNS->isInline(); 10973 } 10974 10975 /// ActOnStartNamespaceDef - This is called at the start of a namespace 10976 /// definition. 10977 Decl *Sema::ActOnStartNamespaceDef( 10978 Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc, 10979 SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace, 10980 const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) { 10981 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 10982 // For anonymous namespace, take the location of the left brace. 10983 SourceLocation Loc = II ? IdentLoc : LBrace; 10984 bool IsInline = InlineLoc.isValid(); 10985 bool IsInvalid = false; 10986 bool IsStd = false; 10987 bool AddToKnown = false; 10988 Scope *DeclRegionScope = NamespcScope->getParent(); 10989 10990 NamespaceDecl *PrevNS = nullptr; 10991 if (II) { 10992 // C++ [namespace.def]p2: 10993 // The identifier in an original-namespace-definition shall not 10994 // have been previously defined in the declarative region in 10995 // which the original-namespace-definition appears. The 10996 // identifier in an original-namespace-definition is the name of 10997 // the namespace. Subsequently in that declarative region, it is 10998 // treated as an original-namespace-name. 10999 // 11000 // Since namespace names are unique in their scope, and we don't 11001 // look through using directives, just look for any ordinary names 11002 // as if by qualified name lookup. 11003 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, 11004 ForExternalRedeclaration); 11005 LookupQualifiedName(R, CurContext->getRedeclContext()); 11006 NamedDecl *PrevDecl = 11007 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr; 11008 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 11009 11010 if (PrevNS) { 11011 // This is an extended namespace definition. 11012 if (IsInline != PrevNS->isInline()) 11013 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 11014 &IsInline, PrevNS); 11015 } else if (PrevDecl) { 11016 // This is an invalid name redefinition. 11017 Diag(Loc, diag::err_redefinition_different_kind) 11018 << II; 11019 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 11020 IsInvalid = true; 11021 // Continue on to push Namespc as current DeclContext and return it. 11022 } else if (II->isStr("std") && 11023 CurContext->getRedeclContext()->isTranslationUnit()) { 11024 // This is the first "real" definition of the namespace "std", so update 11025 // our cache of the "std" namespace to point at this definition. 11026 PrevNS = getStdNamespace(); 11027 IsStd = true; 11028 AddToKnown = !IsInline; 11029 } else { 11030 // We've seen this namespace for the first time. 11031 AddToKnown = !IsInline; 11032 } 11033 } else { 11034 // Anonymous namespaces. 11035 11036 // Determine whether the parent already has an anonymous namespace. 11037 DeclContext *Parent = CurContext->getRedeclContext(); 11038 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 11039 PrevNS = TU->getAnonymousNamespace(); 11040 } else { 11041 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 11042 PrevNS = ND->getAnonymousNamespace(); 11043 } 11044 11045 if (PrevNS && IsInline != PrevNS->isInline()) 11046 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 11047 &IsInline, PrevNS); 11048 } 11049 11050 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 11051 StartLoc, Loc, II, PrevNS); 11052 if (IsInvalid) 11053 Namespc->setInvalidDecl(); 11054 11055 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 11056 AddPragmaAttributes(DeclRegionScope, Namespc); 11057 11058 // FIXME: Should we be merging attributes? 11059 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 11060 PushNamespaceVisibilityAttr(Attr, Loc); 11061 11062 if (IsStd) 11063 StdNamespace = Namespc; 11064 if (AddToKnown) 11065 KnownNamespaces[Namespc] = false; 11066 11067 if (II) { 11068 PushOnScopeChains(Namespc, DeclRegionScope); 11069 } else { 11070 // Link the anonymous namespace into its parent. 11071 DeclContext *Parent = CurContext->getRedeclContext(); 11072 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 11073 TU->setAnonymousNamespace(Namespc); 11074 } else { 11075 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 11076 } 11077 11078 CurContext->addDecl(Namespc); 11079 11080 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 11081 // behaves as if it were replaced by 11082 // namespace unique { /* empty body */ } 11083 // using namespace unique; 11084 // namespace unique { namespace-body } 11085 // where all occurrences of 'unique' in a translation unit are 11086 // replaced by the same identifier and this identifier differs 11087 // from all other identifiers in the entire program. 11088 11089 // We just create the namespace with an empty name and then add an 11090 // implicit using declaration, just like the standard suggests. 11091 // 11092 // CodeGen enforces the "universally unique" aspect by giving all 11093 // declarations semantically contained within an anonymous 11094 // namespace internal linkage. 11095 11096 if (!PrevNS) { 11097 UD = UsingDirectiveDecl::Create(Context, Parent, 11098 /* 'using' */ LBrace, 11099 /* 'namespace' */ SourceLocation(), 11100 /* qualifier */ NestedNameSpecifierLoc(), 11101 /* identifier */ SourceLocation(), 11102 Namespc, 11103 /* Ancestor */ Parent); 11104 UD->setImplicit(); 11105 Parent->addDecl(UD); 11106 } 11107 } 11108 11109 ActOnDocumentableDecl(Namespc); 11110 11111 // Although we could have an invalid decl (i.e. the namespace name is a 11112 // redefinition), push it as current DeclContext and try to continue parsing. 11113 // FIXME: We should be able to push Namespc here, so that the each DeclContext 11114 // for the namespace has the declarations that showed up in that particular 11115 // namespace definition. 11116 PushDeclContext(NamespcScope, Namespc); 11117 return Namespc; 11118 } 11119 11120 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 11121 /// is a namespace alias, returns the namespace it points to. 11122 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 11123 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 11124 return AD->getNamespace(); 11125 return dyn_cast_or_null<NamespaceDecl>(D); 11126 } 11127 11128 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 11129 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 11130 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 11131 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 11132 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 11133 Namespc->setRBraceLoc(RBrace); 11134 PopDeclContext(); 11135 if (Namespc->hasAttr<VisibilityAttr>()) 11136 PopPragmaVisibility(true, RBrace); 11137 // If this namespace contains an export-declaration, export it now. 11138 if (DeferredExportedNamespaces.erase(Namespc)) 11139 Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported); 11140 } 11141 11142 CXXRecordDecl *Sema::getStdBadAlloc() const { 11143 return cast_or_null<CXXRecordDecl>( 11144 StdBadAlloc.get(Context.getExternalSource())); 11145 } 11146 11147 EnumDecl *Sema::getStdAlignValT() const { 11148 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource())); 11149 } 11150 11151 NamespaceDecl *Sema::getStdNamespace() const { 11152 return cast_or_null<NamespaceDecl>( 11153 StdNamespace.get(Context.getExternalSource())); 11154 } 11155 11156 NamespaceDecl *Sema::lookupStdExperimentalNamespace() { 11157 if (!StdExperimentalNamespaceCache) { 11158 if (auto Std = getStdNamespace()) { 11159 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"), 11160 SourceLocation(), LookupNamespaceName); 11161 if (!LookupQualifiedName(Result, Std) || 11162 !(StdExperimentalNamespaceCache = 11163 Result.getAsSingle<NamespaceDecl>())) 11164 Result.suppressDiagnostics(); 11165 } 11166 } 11167 return StdExperimentalNamespaceCache; 11168 } 11169 11170 namespace { 11171 11172 enum UnsupportedSTLSelect { 11173 USS_InvalidMember, 11174 USS_MissingMember, 11175 USS_NonTrivial, 11176 USS_Other 11177 }; 11178 11179 struct InvalidSTLDiagnoser { 11180 Sema &S; 11181 SourceLocation Loc; 11182 QualType TyForDiags; 11183 11184 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "", 11185 const VarDecl *VD = nullptr) { 11186 { 11187 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported) 11188 << TyForDiags << ((int)Sel); 11189 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) { 11190 assert(!Name.empty()); 11191 D << Name; 11192 } 11193 } 11194 if (Sel == USS_InvalidMember) { 11195 S.Diag(VD->getLocation(), diag::note_var_declared_here) 11196 << VD << VD->getSourceRange(); 11197 } 11198 return QualType(); 11199 } 11200 }; 11201 } // namespace 11202 11203 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind, 11204 SourceLocation Loc, 11205 ComparisonCategoryUsage Usage) { 11206 assert(getLangOpts().CPlusPlus && 11207 "Looking for comparison category type outside of C++."); 11208 11209 // Use an elaborated type for diagnostics which has a name containing the 11210 // prepended 'std' namespace but not any inline namespace names. 11211 auto TyForDiags = [&](ComparisonCategoryInfo *Info) { 11212 auto *NNS = 11213 NestedNameSpecifier::Create(Context, nullptr, getStdNamespace()); 11214 return Context.getElaboratedType(ETK_None, NNS, Info->getType()); 11215 }; 11216 11217 // Check if we've already successfully checked the comparison category type 11218 // before. If so, skip checking it again. 11219 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind); 11220 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) { 11221 // The only thing we need to check is that the type has a reachable 11222 // definition in the current context. 11223 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type)) 11224 return QualType(); 11225 11226 return Info->getType(); 11227 } 11228 11229 // If lookup failed 11230 if (!Info) { 11231 std::string NameForDiags = "std::"; 11232 NameForDiags += ComparisonCategories::getCategoryString(Kind); 11233 Diag(Loc, diag::err_implied_comparison_category_type_not_found) 11234 << NameForDiags << (int)Usage; 11235 return QualType(); 11236 } 11237 11238 assert(Info->Kind == Kind); 11239 assert(Info->Record); 11240 11241 // Update the Record decl in case we encountered a forward declaration on our 11242 // first pass. FIXME: This is a bit of a hack. 11243 if (Info->Record->hasDefinition()) 11244 Info->Record = Info->Record->getDefinition(); 11245 11246 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type)) 11247 return QualType(); 11248 11249 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)}; 11250 11251 if (!Info->Record->isTriviallyCopyable()) 11252 return UnsupportedSTLError(USS_NonTrivial); 11253 11254 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) { 11255 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl(); 11256 // Tolerate empty base classes. 11257 if (Base->isEmpty()) 11258 continue; 11259 // Reject STL implementations which have at least one non-empty base. 11260 return UnsupportedSTLError(); 11261 } 11262 11263 // Check that the STL has implemented the types using a single integer field. 11264 // This expectation allows better codegen for builtin operators. We require: 11265 // (1) The class has exactly one field. 11266 // (2) The field is an integral or enumeration type. 11267 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end(); 11268 if (std::distance(FIt, FEnd) != 1 || 11269 !FIt->getType()->isIntegralOrEnumerationType()) { 11270 return UnsupportedSTLError(); 11271 } 11272 11273 // Build each of the require values and store them in Info. 11274 for (ComparisonCategoryResult CCR : 11275 ComparisonCategories::getPossibleResultsForType(Kind)) { 11276 StringRef MemName = ComparisonCategories::getResultString(CCR); 11277 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR); 11278 11279 if (!ValInfo) 11280 return UnsupportedSTLError(USS_MissingMember, MemName); 11281 11282 VarDecl *VD = ValInfo->VD; 11283 assert(VD && "should not be null!"); 11284 11285 // Attempt to diagnose reasons why the STL definition of this type 11286 // might be foobar, including it failing to be a constant expression. 11287 // TODO Handle more ways the lookup or result can be invalid. 11288 if (!VD->isStaticDataMember() || 11289 !VD->isUsableInConstantExpressions(Context)) 11290 return UnsupportedSTLError(USS_InvalidMember, MemName, VD); 11291 11292 // Attempt to evaluate the var decl as a constant expression and extract 11293 // the value of its first field as a ICE. If this fails, the STL 11294 // implementation is not supported. 11295 if (!ValInfo->hasValidIntValue()) 11296 return UnsupportedSTLError(); 11297 11298 MarkVariableReferenced(Loc, VD); 11299 } 11300 11301 // We've successfully built the required types and expressions. Update 11302 // the cache and return the newly cached value. 11303 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true; 11304 return Info->getType(); 11305 } 11306 11307 /// Retrieve the special "std" namespace, which may require us to 11308 /// implicitly define the namespace. 11309 NamespaceDecl *Sema::getOrCreateStdNamespace() { 11310 if (!StdNamespace) { 11311 // The "std" namespace has not yet been defined, so build one implicitly. 11312 StdNamespace = NamespaceDecl::Create(Context, 11313 Context.getTranslationUnitDecl(), 11314 /*Inline=*/false, 11315 SourceLocation(), SourceLocation(), 11316 &PP.getIdentifierTable().get("std"), 11317 /*PrevDecl=*/nullptr); 11318 getStdNamespace()->setImplicit(true); 11319 } 11320 11321 return getStdNamespace(); 11322 } 11323 11324 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 11325 assert(getLangOpts().CPlusPlus && 11326 "Looking for std::initializer_list outside of C++."); 11327 11328 // We're looking for implicit instantiations of 11329 // template <typename E> class std::initializer_list. 11330 11331 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 11332 return false; 11333 11334 ClassTemplateDecl *Template = nullptr; 11335 const TemplateArgument *Arguments = nullptr; 11336 11337 if (const RecordType *RT = Ty->getAs<RecordType>()) { 11338 11339 ClassTemplateSpecializationDecl *Specialization = 11340 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 11341 if (!Specialization) 11342 return false; 11343 11344 Template = Specialization->getSpecializedTemplate(); 11345 Arguments = Specialization->getTemplateArgs().data(); 11346 } else if (const TemplateSpecializationType *TST = 11347 Ty->getAs<TemplateSpecializationType>()) { 11348 Template = dyn_cast_or_null<ClassTemplateDecl>( 11349 TST->getTemplateName().getAsTemplateDecl()); 11350 Arguments = TST->getArgs(); 11351 } 11352 if (!Template) 11353 return false; 11354 11355 if (!StdInitializerList) { 11356 // Haven't recognized std::initializer_list yet, maybe this is it. 11357 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 11358 if (TemplateClass->getIdentifier() != 11359 &PP.getIdentifierTable().get("initializer_list") || 11360 !getStdNamespace()->InEnclosingNamespaceSetOf( 11361 TemplateClass->getDeclContext())) 11362 return false; 11363 // This is a template called std::initializer_list, but is it the right 11364 // template? 11365 TemplateParameterList *Params = Template->getTemplateParameters(); 11366 if (Params->getMinRequiredArguments() != 1) 11367 return false; 11368 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 11369 return false; 11370 11371 // It's the right template. 11372 StdInitializerList = Template; 11373 } 11374 11375 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) 11376 return false; 11377 11378 // This is an instance of std::initializer_list. Find the argument type. 11379 if (Element) 11380 *Element = Arguments[0].getAsType(); 11381 return true; 11382 } 11383 11384 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 11385 NamespaceDecl *Std = S.getStdNamespace(); 11386 if (!Std) { 11387 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 11388 return nullptr; 11389 } 11390 11391 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 11392 Loc, Sema::LookupOrdinaryName); 11393 if (!S.LookupQualifiedName(Result, Std)) { 11394 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 11395 return nullptr; 11396 } 11397 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 11398 if (!Template) { 11399 Result.suppressDiagnostics(); 11400 // We found something weird. Complain about the first thing we found. 11401 NamedDecl *Found = *Result.begin(); 11402 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 11403 return nullptr; 11404 } 11405 11406 // We found some template called std::initializer_list. Now verify that it's 11407 // correct. 11408 TemplateParameterList *Params = Template->getTemplateParameters(); 11409 if (Params->getMinRequiredArguments() != 1 || 11410 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 11411 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 11412 return nullptr; 11413 } 11414 11415 return Template; 11416 } 11417 11418 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 11419 if (!StdInitializerList) { 11420 StdInitializerList = LookupStdInitializerList(*this, Loc); 11421 if (!StdInitializerList) 11422 return QualType(); 11423 } 11424 11425 TemplateArgumentListInfo Args(Loc, Loc); 11426 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 11427 Context.getTrivialTypeSourceInfo(Element, 11428 Loc))); 11429 return Context.getCanonicalType( 11430 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 11431 } 11432 11433 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) { 11434 // C++ [dcl.init.list]p2: 11435 // A constructor is an initializer-list constructor if its first parameter 11436 // is of type std::initializer_list<E> or reference to possibly cv-qualified 11437 // std::initializer_list<E> for some type E, and either there are no other 11438 // parameters or else all other parameters have default arguments. 11439 if (!Ctor->hasOneParamOrDefaultArgs()) 11440 return false; 11441 11442 QualType ArgType = Ctor->getParamDecl(0)->getType(); 11443 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 11444 ArgType = RT->getPointeeType().getUnqualifiedType(); 11445 11446 return isStdInitializerList(ArgType, nullptr); 11447 } 11448 11449 /// Determine whether a using statement is in a context where it will be 11450 /// apply in all contexts. 11451 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 11452 switch (CurContext->getDeclKind()) { 11453 case Decl::TranslationUnit: 11454 return true; 11455 case Decl::LinkageSpec: 11456 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 11457 default: 11458 return false; 11459 } 11460 } 11461 11462 namespace { 11463 11464 // Callback to only accept typo corrections that are namespaces. 11465 class NamespaceValidatorCCC final : public CorrectionCandidateCallback { 11466 public: 11467 bool ValidateCandidate(const TypoCorrection &candidate) override { 11468 if (NamedDecl *ND = candidate.getCorrectionDecl()) 11469 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 11470 return false; 11471 } 11472 11473 std::unique_ptr<CorrectionCandidateCallback> clone() override { 11474 return std::make_unique<NamespaceValidatorCCC>(*this); 11475 } 11476 }; 11477 11478 } 11479 11480 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 11481 CXXScopeSpec &SS, 11482 SourceLocation IdentLoc, 11483 IdentifierInfo *Ident) { 11484 R.clear(); 11485 NamespaceValidatorCCC CCC{}; 11486 if (TypoCorrection Corrected = 11487 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC, 11488 Sema::CTK_ErrorRecovery)) { 11489 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 11490 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 11491 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 11492 Ident->getName().equals(CorrectedStr); 11493 S.diagnoseTypo(Corrected, 11494 S.PDiag(diag::err_using_directive_member_suggest) 11495 << Ident << DC << DroppedSpecifier << SS.getRange(), 11496 S.PDiag(diag::note_namespace_defined_here)); 11497 } else { 11498 S.diagnoseTypo(Corrected, 11499 S.PDiag(diag::err_using_directive_suggest) << Ident, 11500 S.PDiag(diag::note_namespace_defined_here)); 11501 } 11502 R.addDecl(Corrected.getFoundDecl()); 11503 return true; 11504 } 11505 return false; 11506 } 11507 11508 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc, 11509 SourceLocation NamespcLoc, CXXScopeSpec &SS, 11510 SourceLocation IdentLoc, 11511 IdentifierInfo *NamespcName, 11512 const ParsedAttributesView &AttrList) { 11513 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 11514 assert(NamespcName && "Invalid NamespcName."); 11515 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 11516 11517 // This can only happen along a recovery path. 11518 while (S->isTemplateParamScope()) 11519 S = S->getParent(); 11520 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 11521 11522 UsingDirectiveDecl *UDir = nullptr; 11523 NestedNameSpecifier *Qualifier = nullptr; 11524 if (SS.isSet()) 11525 Qualifier = SS.getScopeRep(); 11526 11527 // Lookup namespace name. 11528 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 11529 LookupParsedName(R, S, &SS); 11530 if (R.isAmbiguous()) 11531 return nullptr; 11532 11533 if (R.empty()) { 11534 R.clear(); 11535 // Allow "using namespace std;" or "using namespace ::std;" even if 11536 // "std" hasn't been defined yet, for GCC compatibility. 11537 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 11538 NamespcName->isStr("std")) { 11539 Diag(IdentLoc, diag::ext_using_undefined_std); 11540 R.addDecl(getOrCreateStdNamespace()); 11541 R.resolveKind(); 11542 } 11543 // Otherwise, attempt typo correction. 11544 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 11545 } 11546 11547 if (!R.empty()) { 11548 NamedDecl *Named = R.getRepresentativeDecl(); 11549 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>(); 11550 assert(NS && "expected namespace decl"); 11551 11552 // The use of a nested name specifier may trigger deprecation warnings. 11553 DiagnoseUseOfDecl(Named, IdentLoc); 11554 11555 // C++ [namespace.udir]p1: 11556 // A using-directive specifies that the names in the nominated 11557 // namespace can be used in the scope in which the 11558 // using-directive appears after the using-directive. During 11559 // unqualified name lookup (3.4.1), the names appear as if they 11560 // were declared in the nearest enclosing namespace which 11561 // contains both the using-directive and the nominated 11562 // namespace. [Note: in this context, "contains" means "contains 11563 // directly or indirectly". ] 11564 11565 // Find enclosing context containing both using-directive and 11566 // nominated namespace. 11567 DeclContext *CommonAncestor = NS; 11568 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 11569 CommonAncestor = CommonAncestor->getParent(); 11570 11571 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 11572 SS.getWithLocInContext(Context), 11573 IdentLoc, Named, CommonAncestor); 11574 11575 if (IsUsingDirectiveInToplevelContext(CurContext) && 11576 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 11577 Diag(IdentLoc, diag::warn_using_directive_in_header); 11578 } 11579 11580 PushUsingDirective(S, UDir); 11581 } else { 11582 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 11583 } 11584 11585 if (UDir) 11586 ProcessDeclAttributeList(S, UDir, AttrList); 11587 11588 return UDir; 11589 } 11590 11591 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 11592 // If the scope has an associated entity and the using directive is at 11593 // namespace or translation unit scope, add the UsingDirectiveDecl into 11594 // its lookup structure so qualified name lookup can find it. 11595 DeclContext *Ctx = S->getEntity(); 11596 if (Ctx && !Ctx->isFunctionOrMethod()) 11597 Ctx->addDecl(UDir); 11598 else 11599 // Otherwise, it is at block scope. The using-directives will affect lookup 11600 // only to the end of the scope. 11601 S->PushUsingDirective(UDir); 11602 } 11603 11604 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS, 11605 SourceLocation UsingLoc, 11606 SourceLocation TypenameLoc, CXXScopeSpec &SS, 11607 UnqualifiedId &Name, 11608 SourceLocation EllipsisLoc, 11609 const ParsedAttributesView &AttrList) { 11610 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 11611 11612 if (SS.isEmpty()) { 11613 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname); 11614 return nullptr; 11615 } 11616 11617 switch (Name.getKind()) { 11618 case UnqualifiedIdKind::IK_ImplicitSelfParam: 11619 case UnqualifiedIdKind::IK_Identifier: 11620 case UnqualifiedIdKind::IK_OperatorFunctionId: 11621 case UnqualifiedIdKind::IK_LiteralOperatorId: 11622 case UnqualifiedIdKind::IK_ConversionFunctionId: 11623 break; 11624 11625 case UnqualifiedIdKind::IK_ConstructorName: 11626 case UnqualifiedIdKind::IK_ConstructorTemplateId: 11627 // C++11 inheriting constructors. 11628 Diag(Name.getBeginLoc(), 11629 getLangOpts().CPlusPlus11 11630 ? diag::warn_cxx98_compat_using_decl_constructor 11631 : diag::err_using_decl_constructor) 11632 << SS.getRange(); 11633 11634 if (getLangOpts().CPlusPlus11) break; 11635 11636 return nullptr; 11637 11638 case UnqualifiedIdKind::IK_DestructorName: 11639 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange(); 11640 return nullptr; 11641 11642 case UnqualifiedIdKind::IK_TemplateId: 11643 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id) 11644 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 11645 return nullptr; 11646 11647 case UnqualifiedIdKind::IK_DeductionGuideName: 11648 llvm_unreachable("cannot parse qualified deduction guide name"); 11649 } 11650 11651 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 11652 DeclarationName TargetName = TargetNameInfo.getName(); 11653 if (!TargetName) 11654 return nullptr; 11655 11656 // Warn about access declarations. 11657 if (UsingLoc.isInvalid()) { 11658 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11 11659 ? diag::err_access_decl 11660 : diag::warn_access_decl_deprecated) 11661 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 11662 } 11663 11664 if (EllipsisLoc.isInvalid()) { 11665 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 11666 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 11667 return nullptr; 11668 } else { 11669 if (!SS.getScopeRep()->containsUnexpandedParameterPack() && 11670 !TargetNameInfo.containsUnexpandedParameterPack()) { 11671 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 11672 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc()); 11673 EllipsisLoc = SourceLocation(); 11674 } 11675 } 11676 11677 NamedDecl *UD = 11678 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc, 11679 SS, TargetNameInfo, EllipsisLoc, AttrList, 11680 /*IsInstantiation*/ false, 11681 AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists)); 11682 if (UD) 11683 PushOnScopeChains(UD, S, /*AddToContext*/ false); 11684 11685 return UD; 11686 } 11687 11688 Decl *Sema::ActOnUsingEnumDeclaration(Scope *S, AccessSpecifier AS, 11689 SourceLocation UsingLoc, 11690 SourceLocation EnumLoc, 11691 const DeclSpec &DS) { 11692 switch (DS.getTypeSpecType()) { 11693 case DeclSpec::TST_error: 11694 // This will already have been diagnosed 11695 return nullptr; 11696 11697 case DeclSpec::TST_enum: 11698 break; 11699 11700 case DeclSpec::TST_typename: 11701 Diag(DS.getTypeSpecTypeLoc(), diag::err_using_enum_is_dependent); 11702 return nullptr; 11703 11704 default: 11705 llvm_unreachable("unexpected DeclSpec type"); 11706 } 11707 11708 // As with enum-decls, we ignore attributes for now. 11709 auto *Enum = cast<EnumDecl>(DS.getRepAsDecl()); 11710 if (auto *Def = Enum->getDefinition()) 11711 Enum = Def; 11712 11713 auto *UD = BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc, 11714 DS.getTypeSpecTypeNameLoc(), Enum); 11715 if (UD) 11716 PushOnScopeChains(UD, S, /*AddToContext*/ false); 11717 11718 return UD; 11719 } 11720 11721 /// Determine whether a using declaration considers the given 11722 /// declarations as "equivalent", e.g., if they are redeclarations of 11723 /// the same entity or are both typedefs of the same type. 11724 static bool 11725 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 11726 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 11727 return true; 11728 11729 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 11730 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 11731 return Context.hasSameType(TD1->getUnderlyingType(), 11732 TD2->getUnderlyingType()); 11733 11734 // Two using_if_exists using-declarations are equivalent if both are 11735 // unresolved. 11736 if (isa<UnresolvedUsingIfExistsDecl>(D1) && 11737 isa<UnresolvedUsingIfExistsDecl>(D2)) 11738 return true; 11739 11740 return false; 11741 } 11742 11743 11744 /// Determines whether to create a using shadow decl for a particular 11745 /// decl, given the set of decls existing prior to this using lookup. 11746 bool Sema::CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Orig, 11747 const LookupResult &Previous, 11748 UsingShadowDecl *&PrevShadow) { 11749 // Diagnose finding a decl which is not from a base class of the 11750 // current class. We do this now because there are cases where this 11751 // function will silently decide not to build a shadow decl, which 11752 // will pre-empt further diagnostics. 11753 // 11754 // We don't need to do this in C++11 because we do the check once on 11755 // the qualifier. 11756 // 11757 // FIXME: diagnose the following if we care enough: 11758 // struct A { int foo; }; 11759 // struct B : A { using A::foo; }; 11760 // template <class T> struct C : A {}; 11761 // template <class T> struct D : C<T> { using B::foo; } // <--- 11762 // This is invalid (during instantiation) in C++03 because B::foo 11763 // resolves to the using decl in B, which is not a base class of D<T>. 11764 // We can't diagnose it immediately because C<T> is an unknown 11765 // specialization. The UsingShadowDecl in D<T> then points directly 11766 // to A::foo, which will look well-formed when we instantiate. 11767 // The right solution is to not collapse the shadow-decl chain. 11768 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) 11769 if (auto *Using = dyn_cast<UsingDecl>(BUD)) { 11770 DeclContext *OrigDC = Orig->getDeclContext(); 11771 11772 // Handle enums and anonymous structs. 11773 if (isa<EnumDecl>(OrigDC)) 11774 OrigDC = OrigDC->getParent(); 11775 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 11776 while (OrigRec->isAnonymousStructOrUnion()) 11777 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 11778 11779 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 11780 if (OrigDC == CurContext) { 11781 Diag(Using->getLocation(), 11782 diag::err_using_decl_nested_name_specifier_is_current_class) 11783 << Using->getQualifierLoc().getSourceRange(); 11784 Diag(Orig->getLocation(), diag::note_using_decl_target); 11785 Using->setInvalidDecl(); 11786 return true; 11787 } 11788 11789 Diag(Using->getQualifierLoc().getBeginLoc(), 11790 diag::err_using_decl_nested_name_specifier_is_not_base_class) 11791 << Using->getQualifier() << cast<CXXRecordDecl>(CurContext) 11792 << Using->getQualifierLoc().getSourceRange(); 11793 Diag(Orig->getLocation(), diag::note_using_decl_target); 11794 Using->setInvalidDecl(); 11795 return true; 11796 } 11797 } 11798 11799 if (Previous.empty()) return false; 11800 11801 NamedDecl *Target = Orig; 11802 if (isa<UsingShadowDecl>(Target)) 11803 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 11804 11805 // If the target happens to be one of the previous declarations, we 11806 // don't have a conflict. 11807 // 11808 // FIXME: but we might be increasing its access, in which case we 11809 // should redeclare it. 11810 NamedDecl *NonTag = nullptr, *Tag = nullptr; 11811 bool FoundEquivalentDecl = false; 11812 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 11813 I != E; ++I) { 11814 NamedDecl *D = (*I)->getUnderlyingDecl(); 11815 // We can have UsingDecls in our Previous results because we use the same 11816 // LookupResult for checking whether the UsingDecl itself is a valid 11817 // redeclaration. 11818 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D) || isa<UsingEnumDecl>(D)) 11819 continue; 11820 11821 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 11822 // C++ [class.mem]p19: 11823 // If T is the name of a class, then [every named member other than 11824 // a non-static data member] shall have a name different from T 11825 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) && 11826 !isa<IndirectFieldDecl>(Target) && 11827 !isa<UnresolvedUsingValueDecl>(Target) && 11828 DiagnoseClassNameShadow( 11829 CurContext, 11830 DeclarationNameInfo(BUD->getDeclName(), BUD->getLocation()))) 11831 return true; 11832 } 11833 11834 if (IsEquivalentForUsingDecl(Context, D, Target)) { 11835 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 11836 PrevShadow = Shadow; 11837 FoundEquivalentDecl = true; 11838 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) { 11839 // We don't conflict with an existing using shadow decl of an equivalent 11840 // declaration, but we're not a redeclaration of it. 11841 FoundEquivalentDecl = true; 11842 } 11843 11844 if (isVisible(D)) 11845 (isa<TagDecl>(D) ? Tag : NonTag) = D; 11846 } 11847 11848 if (FoundEquivalentDecl) 11849 return false; 11850 11851 // Always emit a diagnostic for a mismatch between an unresolved 11852 // using_if_exists and a resolved using declaration in either direction. 11853 if (isa<UnresolvedUsingIfExistsDecl>(Target) != 11854 (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) { 11855 if (!NonTag && !Tag) 11856 return false; 11857 Diag(BUD->getLocation(), diag::err_using_decl_conflict); 11858 Diag(Target->getLocation(), diag::note_using_decl_target); 11859 Diag((NonTag ? NonTag : Tag)->getLocation(), 11860 diag::note_using_decl_conflict); 11861 BUD->setInvalidDecl(); 11862 return true; 11863 } 11864 11865 if (FunctionDecl *FD = Target->getAsFunction()) { 11866 NamedDecl *OldDecl = nullptr; 11867 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 11868 /*IsForUsingDecl*/ true)) { 11869 case Ovl_Overload: 11870 return false; 11871 11872 case Ovl_NonFunction: 11873 Diag(BUD->getLocation(), diag::err_using_decl_conflict); 11874 break; 11875 11876 // We found a decl with the exact signature. 11877 case Ovl_Match: 11878 // If we're in a record, we want to hide the target, so we 11879 // return true (without a diagnostic) to tell the caller not to 11880 // build a shadow decl. 11881 if (CurContext->isRecord()) 11882 return true; 11883 11884 // If we're not in a record, this is an error. 11885 Diag(BUD->getLocation(), diag::err_using_decl_conflict); 11886 break; 11887 } 11888 11889 Diag(Target->getLocation(), diag::note_using_decl_target); 11890 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 11891 BUD->setInvalidDecl(); 11892 return true; 11893 } 11894 11895 // Target is not a function. 11896 11897 if (isa<TagDecl>(Target)) { 11898 // No conflict between a tag and a non-tag. 11899 if (!Tag) return false; 11900 11901 Diag(BUD->getLocation(), diag::err_using_decl_conflict); 11902 Diag(Target->getLocation(), diag::note_using_decl_target); 11903 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 11904 BUD->setInvalidDecl(); 11905 return true; 11906 } 11907 11908 // No conflict between a tag and a non-tag. 11909 if (!NonTag) return false; 11910 11911 Diag(BUD->getLocation(), diag::err_using_decl_conflict); 11912 Diag(Target->getLocation(), diag::note_using_decl_target); 11913 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 11914 BUD->setInvalidDecl(); 11915 return true; 11916 } 11917 11918 /// Determine whether a direct base class is a virtual base class. 11919 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) { 11920 if (!Derived->getNumVBases()) 11921 return false; 11922 for (auto &B : Derived->bases()) 11923 if (B.getType()->getAsCXXRecordDecl() == Base) 11924 return B.isVirtual(); 11925 llvm_unreachable("not a direct base class"); 11926 } 11927 11928 /// Builds a shadow declaration corresponding to a 'using' declaration. 11929 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD, 11930 NamedDecl *Orig, 11931 UsingShadowDecl *PrevDecl) { 11932 // If we resolved to another shadow declaration, just coalesce them. 11933 NamedDecl *Target = Orig; 11934 if (isa<UsingShadowDecl>(Target)) { 11935 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 11936 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 11937 } 11938 11939 NamedDecl *NonTemplateTarget = Target; 11940 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target)) 11941 NonTemplateTarget = TargetTD->getTemplatedDecl(); 11942 11943 UsingShadowDecl *Shadow; 11944 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) { 11945 UsingDecl *Using = cast<UsingDecl>(BUD); 11946 bool IsVirtualBase = 11947 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext), 11948 Using->getQualifier()->getAsRecordDecl()); 11949 Shadow = ConstructorUsingShadowDecl::Create( 11950 Context, CurContext, Using->getLocation(), Using, Orig, IsVirtualBase); 11951 } else { 11952 Shadow = UsingShadowDecl::Create(Context, CurContext, BUD->getLocation(), 11953 Target->getDeclName(), BUD, Target); 11954 } 11955 BUD->addShadowDecl(Shadow); 11956 11957 Shadow->setAccess(BUD->getAccess()); 11958 if (Orig->isInvalidDecl() || BUD->isInvalidDecl()) 11959 Shadow->setInvalidDecl(); 11960 11961 Shadow->setPreviousDecl(PrevDecl); 11962 11963 if (S) 11964 PushOnScopeChains(Shadow, S); 11965 else 11966 CurContext->addDecl(Shadow); 11967 11968 11969 return Shadow; 11970 } 11971 11972 /// Hides a using shadow declaration. This is required by the current 11973 /// using-decl implementation when a resolvable using declaration in a 11974 /// class is followed by a declaration which would hide or override 11975 /// one or more of the using decl's targets; for example: 11976 /// 11977 /// struct Base { void foo(int); }; 11978 /// struct Derived : Base { 11979 /// using Base::foo; 11980 /// void foo(int); 11981 /// }; 11982 /// 11983 /// The governing language is C++03 [namespace.udecl]p12: 11984 /// 11985 /// When a using-declaration brings names from a base class into a 11986 /// derived class scope, member functions in the derived class 11987 /// override and/or hide member functions with the same name and 11988 /// parameter types in a base class (rather than conflicting). 11989 /// 11990 /// There are two ways to implement this: 11991 /// (1) optimistically create shadow decls when they're not hidden 11992 /// by existing declarations, or 11993 /// (2) don't create any shadow decls (or at least don't make them 11994 /// visible) until we've fully parsed/instantiated the class. 11995 /// The problem with (1) is that we might have to retroactively remove 11996 /// a shadow decl, which requires several O(n) operations because the 11997 /// decl structures are (very reasonably) not designed for removal. 11998 /// (2) avoids this but is very fiddly and phase-dependent. 11999 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 12000 if (Shadow->getDeclName().getNameKind() == 12001 DeclarationName::CXXConversionFunctionName) 12002 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 12003 12004 // Remove it from the DeclContext... 12005 Shadow->getDeclContext()->removeDecl(Shadow); 12006 12007 // ...and the scope, if applicable... 12008 if (S) { 12009 S->RemoveDecl(Shadow); 12010 IdResolver.RemoveDecl(Shadow); 12011 } 12012 12013 // ...and the using decl. 12014 Shadow->getIntroducer()->removeShadowDecl(Shadow); 12015 12016 // TODO: complain somehow if Shadow was used. It shouldn't 12017 // be possible for this to happen, because...? 12018 } 12019 12020 /// Find the base specifier for a base class with the given type. 12021 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 12022 QualType DesiredBase, 12023 bool &AnyDependentBases) { 12024 // Check whether the named type is a direct base class. 12025 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified() 12026 .getUnqualifiedType(); 12027 for (auto &Base : Derived->bases()) { 12028 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 12029 if (CanonicalDesiredBase == BaseType) 12030 return &Base; 12031 if (BaseType->isDependentType()) 12032 AnyDependentBases = true; 12033 } 12034 return nullptr; 12035 } 12036 12037 namespace { 12038 class UsingValidatorCCC final : public CorrectionCandidateCallback { 12039 public: 12040 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 12041 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 12042 : HasTypenameKeyword(HasTypenameKeyword), 12043 IsInstantiation(IsInstantiation), OldNNS(NNS), 12044 RequireMemberOf(RequireMemberOf) {} 12045 12046 bool ValidateCandidate(const TypoCorrection &Candidate) override { 12047 NamedDecl *ND = Candidate.getCorrectionDecl(); 12048 12049 // Keywords are not valid here. 12050 if (!ND || isa<NamespaceDecl>(ND)) 12051 return false; 12052 12053 // Completely unqualified names are invalid for a 'using' declaration. 12054 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 12055 return false; 12056 12057 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would 12058 // reject. 12059 12060 if (RequireMemberOf) { 12061 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 12062 if (FoundRecord && FoundRecord->isInjectedClassName()) { 12063 // No-one ever wants a using-declaration to name an injected-class-name 12064 // of a base class, unless they're declaring an inheriting constructor. 12065 ASTContext &Ctx = ND->getASTContext(); 12066 if (!Ctx.getLangOpts().CPlusPlus11) 12067 return false; 12068 QualType FoundType = Ctx.getRecordType(FoundRecord); 12069 12070 // Check that the injected-class-name is named as a member of its own 12071 // type; we don't want to suggest 'using Derived::Base;', since that 12072 // means something else. 12073 NestedNameSpecifier *Specifier = 12074 Candidate.WillReplaceSpecifier() 12075 ? Candidate.getCorrectionSpecifier() 12076 : OldNNS; 12077 if (!Specifier->getAsType() || 12078 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 12079 return false; 12080 12081 // Check that this inheriting constructor declaration actually names a 12082 // direct base class of the current class. 12083 bool AnyDependentBases = false; 12084 if (!findDirectBaseWithType(RequireMemberOf, 12085 Ctx.getRecordType(FoundRecord), 12086 AnyDependentBases) && 12087 !AnyDependentBases) 12088 return false; 12089 } else { 12090 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 12091 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 12092 return false; 12093 12094 // FIXME: Check that the base class member is accessible? 12095 } 12096 } else { 12097 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 12098 if (FoundRecord && FoundRecord->isInjectedClassName()) 12099 return false; 12100 } 12101 12102 if (isa<TypeDecl>(ND)) 12103 return HasTypenameKeyword || !IsInstantiation; 12104 12105 return !HasTypenameKeyword; 12106 } 12107 12108 std::unique_ptr<CorrectionCandidateCallback> clone() override { 12109 return std::make_unique<UsingValidatorCCC>(*this); 12110 } 12111 12112 private: 12113 bool HasTypenameKeyword; 12114 bool IsInstantiation; 12115 NestedNameSpecifier *OldNNS; 12116 CXXRecordDecl *RequireMemberOf; 12117 }; 12118 } // end anonymous namespace 12119 12120 /// Remove decls we can't actually see from a lookup being used to declare 12121 /// shadow using decls. 12122 /// 12123 /// \param S - The scope of the potential shadow decl 12124 /// \param Previous - The lookup of a potential shadow decl's name. 12125 void Sema::FilterUsingLookup(Scope *S, LookupResult &Previous) { 12126 // It is really dumb that we have to do this. 12127 LookupResult::Filter F = Previous.makeFilter(); 12128 while (F.hasNext()) { 12129 NamedDecl *D = F.next(); 12130 if (!isDeclInScope(D, CurContext, S)) 12131 F.erase(); 12132 // If we found a local extern declaration that's not ordinarily visible, 12133 // and this declaration is being added to a non-block scope, ignore it. 12134 // We're only checking for scope conflicts here, not also for violations 12135 // of the linkage rules. 12136 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 12137 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 12138 F.erase(); 12139 } 12140 F.done(); 12141 } 12142 12143 /// Builds a using declaration. 12144 /// 12145 /// \param IsInstantiation - Whether this call arises from an 12146 /// instantiation of an unresolved using declaration. We treat 12147 /// the lookup differently for these declarations. 12148 NamedDecl *Sema::BuildUsingDeclaration( 12149 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, 12150 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, 12151 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, 12152 const ParsedAttributesView &AttrList, bool IsInstantiation, 12153 bool IsUsingIfExists) { 12154 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 12155 SourceLocation IdentLoc = NameInfo.getLoc(); 12156 assert(IdentLoc.isValid() && "Invalid TargetName location."); 12157 12158 // FIXME: We ignore attributes for now. 12159 12160 // For an inheriting constructor declaration, the name of the using 12161 // declaration is the name of a constructor in this class, not in the 12162 // base class. 12163 DeclarationNameInfo UsingName = NameInfo; 12164 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName) 12165 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext)) 12166 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 12167 Context.getCanonicalType(Context.getRecordType(RD)))); 12168 12169 // Do the redeclaration lookup in the current scope. 12170 LookupResult Previous(*this, UsingName, LookupUsingDeclName, 12171 ForVisibleRedeclaration); 12172 Previous.setHideTags(false); 12173 if (S) { 12174 LookupName(Previous, S); 12175 12176 FilterUsingLookup(S, Previous); 12177 } else { 12178 assert(IsInstantiation && "no scope in non-instantiation"); 12179 if (CurContext->isRecord()) 12180 LookupQualifiedName(Previous, CurContext); 12181 else { 12182 // No redeclaration check is needed here; in non-member contexts we 12183 // diagnosed all possible conflicts with other using-declarations when 12184 // building the template: 12185 // 12186 // For a dependent non-type using declaration, the only valid case is 12187 // if we instantiate to a single enumerator. We check for conflicts 12188 // between shadow declarations we introduce, and we check in the template 12189 // definition for conflicts between a non-type using declaration and any 12190 // other declaration, which together covers all cases. 12191 // 12192 // A dependent typename using declaration will never successfully 12193 // instantiate, since it will always name a class member, so we reject 12194 // that in the template definition. 12195 } 12196 } 12197 12198 // Check for invalid redeclarations. 12199 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 12200 SS, IdentLoc, Previous)) 12201 return nullptr; 12202 12203 // 'using_if_exists' doesn't make sense on an inherited constructor. 12204 if (IsUsingIfExists && UsingName.getName().getNameKind() == 12205 DeclarationName::CXXConstructorName) { 12206 Diag(UsingLoc, diag::err_using_if_exists_on_ctor); 12207 return nullptr; 12208 } 12209 12210 DeclContext *LookupContext = computeDeclContext(SS); 12211 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 12212 if (!LookupContext || EllipsisLoc.isValid()) { 12213 NamedDecl *D; 12214 // Dependent scope, or an unexpanded pack 12215 if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, 12216 SS, NameInfo, IdentLoc)) 12217 return nullptr; 12218 12219 if (HasTypenameKeyword) { 12220 // FIXME: not all declaration name kinds are legal here 12221 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 12222 UsingLoc, TypenameLoc, 12223 QualifierLoc, 12224 IdentLoc, NameInfo.getName(), 12225 EllipsisLoc); 12226 } else { 12227 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 12228 QualifierLoc, NameInfo, EllipsisLoc); 12229 } 12230 D->setAccess(AS); 12231 CurContext->addDecl(D); 12232 ProcessDeclAttributeList(S, D, AttrList); 12233 return D; 12234 } 12235 12236 auto Build = [&](bool Invalid) { 12237 UsingDecl *UD = 12238 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 12239 UsingName, HasTypenameKeyword); 12240 UD->setAccess(AS); 12241 CurContext->addDecl(UD); 12242 ProcessDeclAttributeList(S, UD, AttrList); 12243 UD->setInvalidDecl(Invalid); 12244 return UD; 12245 }; 12246 auto BuildInvalid = [&]{ return Build(true); }; 12247 auto BuildValid = [&]{ return Build(false); }; 12248 12249 if (RequireCompleteDeclContext(SS, LookupContext)) 12250 return BuildInvalid(); 12251 12252 // Look up the target name. 12253 LookupResult R(*this, NameInfo, LookupOrdinaryName); 12254 12255 // Unlike most lookups, we don't always want to hide tag 12256 // declarations: tag names are visible through the using declaration 12257 // even if hidden by ordinary names, *except* in a dependent context 12258 // where it's important for the sanity of two-phase lookup. 12259 if (!IsInstantiation) 12260 R.setHideTags(false); 12261 12262 // For the purposes of this lookup, we have a base object type 12263 // equal to that of the current context. 12264 if (CurContext->isRecord()) { 12265 R.setBaseObjectType( 12266 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 12267 } 12268 12269 LookupQualifiedName(R, LookupContext); 12270 12271 // Validate the context, now we have a lookup 12272 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo, 12273 IdentLoc, &R)) 12274 return nullptr; 12275 12276 if (R.empty() && IsUsingIfExists) 12277 R.addDecl(UnresolvedUsingIfExistsDecl::Create(Context, CurContext, UsingLoc, 12278 UsingName.getName()), 12279 AS_public); 12280 12281 // Try to correct typos if possible. If constructor name lookup finds no 12282 // results, that means the named class has no explicit constructors, and we 12283 // suppressed declaring implicit ones (probably because it's dependent or 12284 // invalid). 12285 if (R.empty() && 12286 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { 12287 // HACK 2017-01-08: Work around an issue with libstdc++'s detection of 12288 // ::gets. Sometimes it believes that glibc provides a ::gets in cases where 12289 // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later. 12290 auto *II = NameInfo.getName().getAsIdentifierInfo(); 12291 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") && 12292 CurContext->isStdNamespace() && 12293 isa<TranslationUnitDecl>(LookupContext) && 12294 getSourceManager().isInSystemHeader(UsingLoc)) 12295 return nullptr; 12296 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 12297 dyn_cast<CXXRecordDecl>(CurContext)); 12298 if (TypoCorrection Corrected = 12299 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 12300 CTK_ErrorRecovery)) { 12301 // We reject candidates where DroppedSpecifier == true, hence the 12302 // literal '0' below. 12303 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 12304 << NameInfo.getName() << LookupContext << 0 12305 << SS.getRange()); 12306 12307 // If we picked a correction with no attached Decl we can't do anything 12308 // useful with it, bail out. 12309 NamedDecl *ND = Corrected.getCorrectionDecl(); 12310 if (!ND) 12311 return BuildInvalid(); 12312 12313 // If we corrected to an inheriting constructor, handle it as one. 12314 auto *RD = dyn_cast<CXXRecordDecl>(ND); 12315 if (RD && RD->isInjectedClassName()) { 12316 // The parent of the injected class name is the class itself. 12317 RD = cast<CXXRecordDecl>(RD->getParent()); 12318 12319 // Fix up the information we'll use to build the using declaration. 12320 if (Corrected.WillReplaceSpecifier()) { 12321 NestedNameSpecifierLocBuilder Builder; 12322 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 12323 QualifierLoc.getSourceRange()); 12324 QualifierLoc = Builder.getWithLocInContext(Context); 12325 } 12326 12327 // In this case, the name we introduce is the name of a derived class 12328 // constructor. 12329 auto *CurClass = cast<CXXRecordDecl>(CurContext); 12330 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 12331 Context.getCanonicalType(Context.getRecordType(CurClass)))); 12332 UsingName.setNamedTypeInfo(nullptr); 12333 for (auto *Ctor : LookupConstructors(RD)) 12334 R.addDecl(Ctor); 12335 R.resolveKind(); 12336 } else { 12337 // FIXME: Pick up all the declarations if we found an overloaded 12338 // function. 12339 UsingName.setName(ND->getDeclName()); 12340 R.addDecl(ND); 12341 } 12342 } else { 12343 Diag(IdentLoc, diag::err_no_member) 12344 << NameInfo.getName() << LookupContext << SS.getRange(); 12345 return BuildInvalid(); 12346 } 12347 } 12348 12349 if (R.isAmbiguous()) 12350 return BuildInvalid(); 12351 12352 if (HasTypenameKeyword) { 12353 // If we asked for a typename and got a non-type decl, error out. 12354 if (!R.getAsSingle<TypeDecl>() && 12355 !R.getAsSingle<UnresolvedUsingIfExistsDecl>()) { 12356 Diag(IdentLoc, diag::err_using_typename_non_type); 12357 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 12358 Diag((*I)->getUnderlyingDecl()->getLocation(), 12359 diag::note_using_decl_target); 12360 return BuildInvalid(); 12361 } 12362 } else { 12363 // If we asked for a non-typename and we got a type, error out, 12364 // but only if this is an instantiation of an unresolved using 12365 // decl. Otherwise just silently find the type name. 12366 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 12367 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 12368 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 12369 return BuildInvalid(); 12370 } 12371 } 12372 12373 // C++14 [namespace.udecl]p6: 12374 // A using-declaration shall not name a namespace. 12375 if (R.getAsSingle<NamespaceDecl>()) { 12376 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 12377 << SS.getRange(); 12378 return BuildInvalid(); 12379 } 12380 12381 UsingDecl *UD = BuildValid(); 12382 12383 // Some additional rules apply to inheriting constructors. 12384 if (UsingName.getName().getNameKind() == 12385 DeclarationName::CXXConstructorName) { 12386 // Suppress access diagnostics; the access check is instead performed at the 12387 // point of use for an inheriting constructor. 12388 R.suppressDiagnostics(); 12389 if (CheckInheritingConstructorUsingDecl(UD)) 12390 return UD; 12391 } 12392 12393 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 12394 UsingShadowDecl *PrevDecl = nullptr; 12395 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 12396 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 12397 } 12398 12399 return UD; 12400 } 12401 12402 NamedDecl *Sema::BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS, 12403 SourceLocation UsingLoc, 12404 SourceLocation EnumLoc, 12405 SourceLocation NameLoc, 12406 EnumDecl *ED) { 12407 bool Invalid = false; 12408 12409 if (CurContext->getRedeclContext()->isRecord()) { 12410 /// In class scope, check if this is a duplicate, for better a diagnostic. 12411 DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc); 12412 LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName, 12413 ForVisibleRedeclaration); 12414 12415 LookupName(Previous, S); 12416 12417 for (NamedDecl *D : Previous) 12418 if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D)) 12419 if (UED->getEnumDecl() == ED) { 12420 Diag(UsingLoc, diag::err_using_enum_decl_redeclaration) 12421 << SourceRange(EnumLoc, NameLoc); 12422 Diag(D->getLocation(), diag::note_using_enum_decl) << 1; 12423 Invalid = true; 12424 break; 12425 } 12426 } 12427 12428 if (RequireCompleteEnumDecl(ED, NameLoc)) 12429 Invalid = true; 12430 12431 UsingEnumDecl *UD = UsingEnumDecl::Create(Context, CurContext, UsingLoc, 12432 EnumLoc, NameLoc, ED); 12433 UD->setAccess(AS); 12434 CurContext->addDecl(UD); 12435 12436 if (Invalid) { 12437 UD->setInvalidDecl(); 12438 return UD; 12439 } 12440 12441 // Create the shadow decls for each enumerator 12442 for (EnumConstantDecl *EC : ED->enumerators()) { 12443 UsingShadowDecl *PrevDecl = nullptr; 12444 DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation()); 12445 LookupResult Previous(*this, DNI, LookupOrdinaryName, 12446 ForVisibleRedeclaration); 12447 LookupName(Previous, S); 12448 FilterUsingLookup(S, Previous); 12449 12450 if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl)) 12451 BuildUsingShadowDecl(S, UD, EC, PrevDecl); 12452 } 12453 12454 return UD; 12455 } 12456 12457 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom, 12458 ArrayRef<NamedDecl *> Expansions) { 12459 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || 12460 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || 12461 isa<UsingPackDecl>(InstantiatedFrom)); 12462 12463 auto *UPD = 12464 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions); 12465 UPD->setAccess(InstantiatedFrom->getAccess()); 12466 CurContext->addDecl(UPD); 12467 return UPD; 12468 } 12469 12470 /// Additional checks for a using declaration referring to a constructor name. 12471 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 12472 assert(!UD->hasTypename() && "expecting a constructor name"); 12473 12474 const Type *SourceType = UD->getQualifier()->getAsType(); 12475 assert(SourceType && 12476 "Using decl naming constructor doesn't have type in scope spec."); 12477 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 12478 12479 // Check whether the named type is a direct base class. 12480 bool AnyDependentBases = false; 12481 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 12482 AnyDependentBases); 12483 if (!Base && !AnyDependentBases) { 12484 Diag(UD->getUsingLoc(), 12485 diag::err_using_decl_constructor_not_in_direct_base) 12486 << UD->getNameInfo().getSourceRange() 12487 << QualType(SourceType, 0) << TargetClass; 12488 UD->setInvalidDecl(); 12489 return true; 12490 } 12491 12492 if (Base) 12493 Base->setInheritConstructors(); 12494 12495 return false; 12496 } 12497 12498 /// Checks that the given using declaration is not an invalid 12499 /// redeclaration. Note that this is checking only for the using decl 12500 /// itself, not for any ill-formedness among the UsingShadowDecls. 12501 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 12502 bool HasTypenameKeyword, 12503 const CXXScopeSpec &SS, 12504 SourceLocation NameLoc, 12505 const LookupResult &Prev) { 12506 NestedNameSpecifier *Qual = SS.getScopeRep(); 12507 12508 // C++03 [namespace.udecl]p8: 12509 // C++0x [namespace.udecl]p10: 12510 // A using-declaration is a declaration and can therefore be used 12511 // repeatedly where (and only where) multiple declarations are 12512 // allowed. 12513 // 12514 // That's in non-member contexts. 12515 if (!CurContext->getRedeclContext()->isRecord()) { 12516 // A dependent qualifier outside a class can only ever resolve to an 12517 // enumeration type. Therefore it conflicts with any other non-type 12518 // declaration in the same scope. 12519 // FIXME: How should we check for dependent type-type conflicts at block 12520 // scope? 12521 if (Qual->isDependent() && !HasTypenameKeyword) { 12522 for (auto *D : Prev) { 12523 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) { 12524 bool OldCouldBeEnumerator = 12525 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D); 12526 Diag(NameLoc, 12527 OldCouldBeEnumerator ? diag::err_redefinition 12528 : diag::err_redefinition_different_kind) 12529 << Prev.getLookupName(); 12530 Diag(D->getLocation(), diag::note_previous_definition); 12531 return true; 12532 } 12533 } 12534 } 12535 return false; 12536 } 12537 12538 const NestedNameSpecifier *CNNS = 12539 Context.getCanonicalNestedNameSpecifier(Qual); 12540 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 12541 NamedDecl *D = *I; 12542 12543 bool DTypename; 12544 NestedNameSpecifier *DQual; 12545 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 12546 DTypename = UD->hasTypename(); 12547 DQual = UD->getQualifier(); 12548 } else if (UnresolvedUsingValueDecl *UD 12549 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 12550 DTypename = false; 12551 DQual = UD->getQualifier(); 12552 } else if (UnresolvedUsingTypenameDecl *UD 12553 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 12554 DTypename = true; 12555 DQual = UD->getQualifier(); 12556 } else continue; 12557 12558 // using decls differ if one says 'typename' and the other doesn't. 12559 // FIXME: non-dependent using decls? 12560 if (HasTypenameKeyword != DTypename) continue; 12561 12562 // using decls differ if they name different scopes (but note that 12563 // template instantiation can cause this check to trigger when it 12564 // didn't before instantiation). 12565 if (CNNS != Context.getCanonicalNestedNameSpecifier(DQual)) 12566 continue; 12567 12568 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 12569 Diag(D->getLocation(), diag::note_using_decl) << 1; 12570 return true; 12571 } 12572 12573 return false; 12574 } 12575 12576 /// Checks that the given nested-name qualifier used in a using decl 12577 /// in the current context is appropriately related to the current 12578 /// scope. If an error is found, diagnoses it and returns true. 12579 /// R is nullptr, if the caller has not (yet) done a lookup, otherwise it's the 12580 /// result of that lookup. UD is likewise nullptr, except when we have an 12581 /// already-populated UsingDecl whose shadow decls contain the same information 12582 /// (i.e. we're instantiating a UsingDecl with non-dependent scope). 12583 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename, 12584 const CXXScopeSpec &SS, 12585 const DeclarationNameInfo &NameInfo, 12586 SourceLocation NameLoc, 12587 const LookupResult *R, const UsingDecl *UD) { 12588 DeclContext *NamedContext = computeDeclContext(SS); 12589 assert(bool(NamedContext) == (R || UD) && !(R && UD) && 12590 "resolvable context must have exactly one set of decls"); 12591 12592 // C++ 20 permits using an enumerator that does not have a class-hierarchy 12593 // relationship. 12594 bool Cxx20Enumerator = false; 12595 if (NamedContext) { 12596 EnumConstantDecl *EC = nullptr; 12597 if (R) 12598 EC = R->getAsSingle<EnumConstantDecl>(); 12599 else if (UD && UD->shadow_size() == 1) 12600 EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl()); 12601 if (EC) 12602 Cxx20Enumerator = getLangOpts().CPlusPlus20; 12603 12604 if (auto *ED = dyn_cast<EnumDecl>(NamedContext)) { 12605 // C++14 [namespace.udecl]p7: 12606 // A using-declaration shall not name a scoped enumerator. 12607 // C++20 p1099 permits enumerators. 12608 if (EC && R && ED->isScoped()) 12609 Diag(SS.getBeginLoc(), 12610 getLangOpts().CPlusPlus20 12611 ? diag::warn_cxx17_compat_using_decl_scoped_enumerator 12612 : diag::ext_using_decl_scoped_enumerator) 12613 << SS.getRange(); 12614 12615 // We want to consider the scope of the enumerator 12616 NamedContext = ED->getDeclContext(); 12617 } 12618 } 12619 12620 if (!CurContext->isRecord()) { 12621 // C++03 [namespace.udecl]p3: 12622 // C++0x [namespace.udecl]p8: 12623 // A using-declaration for a class member shall be a member-declaration. 12624 // C++20 [namespace.udecl]p7 12625 // ... other than an enumerator ... 12626 12627 // If we weren't able to compute a valid scope, it might validly be a 12628 // dependent class or enumeration scope. If we have a 'typename' keyword, 12629 // the scope must resolve to a class type. 12630 if (NamedContext ? !NamedContext->getRedeclContext()->isRecord() 12631 : !HasTypename) 12632 return false; // OK 12633 12634 Diag(NameLoc, 12635 Cxx20Enumerator 12636 ? diag::warn_cxx17_compat_using_decl_class_member_enumerator 12637 : diag::err_using_decl_can_not_refer_to_class_member) 12638 << SS.getRange(); 12639 12640 if (Cxx20Enumerator) 12641 return false; // OK 12642 12643 auto *RD = NamedContext 12644 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext()) 12645 : nullptr; 12646 if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) { 12647 // See if there's a helpful fixit 12648 12649 if (!R) { 12650 // We will have already diagnosed the problem on the template 12651 // definition, Maybe we should do so again? 12652 } else if (R->getAsSingle<TypeDecl>()) { 12653 if (getLangOpts().CPlusPlus11) { 12654 // Convert 'using X::Y;' to 'using Y = X::Y;'. 12655 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 12656 << 0 // alias declaration 12657 << FixItHint::CreateInsertion(SS.getBeginLoc(), 12658 NameInfo.getName().getAsString() + 12659 " = "); 12660 } else { 12661 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 12662 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc()); 12663 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 12664 << 1 // typedef declaration 12665 << FixItHint::CreateReplacement(UsingLoc, "typedef") 12666 << FixItHint::CreateInsertion( 12667 InsertLoc, " " + NameInfo.getName().getAsString()); 12668 } 12669 } else if (R->getAsSingle<VarDecl>()) { 12670 // Don't provide a fixit outside C++11 mode; we don't want to suggest 12671 // repeating the type of the static data member here. 12672 FixItHint FixIt; 12673 if (getLangOpts().CPlusPlus11) { 12674 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 12675 FixIt = FixItHint::CreateReplacement( 12676 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 12677 } 12678 12679 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 12680 << 2 // reference declaration 12681 << FixIt; 12682 } else if (R->getAsSingle<EnumConstantDecl>()) { 12683 // Don't provide a fixit outside C++11 mode; we don't want to suggest 12684 // repeating the type of the enumeration here, and we can't do so if 12685 // the type is anonymous. 12686 FixItHint FixIt; 12687 if (getLangOpts().CPlusPlus11) { 12688 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 12689 FixIt = FixItHint::CreateReplacement( 12690 UsingLoc, 12691 "constexpr auto " + NameInfo.getName().getAsString() + " = "); 12692 } 12693 12694 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 12695 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable 12696 << FixIt; 12697 } 12698 } 12699 12700 return true; // Fail 12701 } 12702 12703 // If the named context is dependent, we can't decide much. 12704 if (!NamedContext) { 12705 // FIXME: in C++0x, we can diagnose if we can prove that the 12706 // nested-name-specifier does not refer to a base class, which is 12707 // still possible in some cases. 12708 12709 // Otherwise we have to conservatively report that things might be 12710 // okay. 12711 return false; 12712 } 12713 12714 // The current scope is a record. 12715 if (!NamedContext->isRecord()) { 12716 // Ideally this would point at the last name in the specifier, 12717 // but we don't have that level of source info. 12718 Diag(SS.getBeginLoc(), 12719 Cxx20Enumerator 12720 ? diag::warn_cxx17_compat_using_decl_non_member_enumerator 12721 : diag::err_using_decl_nested_name_specifier_is_not_class) 12722 << SS.getScopeRep() << SS.getRange(); 12723 12724 if (Cxx20Enumerator) 12725 return false; // OK 12726 12727 return true; 12728 } 12729 12730 if (!NamedContext->isDependentContext() && 12731 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 12732 return true; 12733 12734 if (getLangOpts().CPlusPlus11) { 12735 // C++11 [namespace.udecl]p3: 12736 // In a using-declaration used as a member-declaration, the 12737 // nested-name-specifier shall name a base class of the class 12738 // being defined. 12739 12740 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 12741 cast<CXXRecordDecl>(NamedContext))) { 12742 12743 if (Cxx20Enumerator) { 12744 Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator) 12745 << SS.getRange(); 12746 return false; 12747 } 12748 12749 if (CurContext == NamedContext) { 12750 Diag(SS.getBeginLoc(), 12751 diag::err_using_decl_nested_name_specifier_is_current_class) 12752 << SS.getRange(); 12753 return !getLangOpts().CPlusPlus20; 12754 } 12755 12756 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) { 12757 Diag(SS.getBeginLoc(), 12758 diag::err_using_decl_nested_name_specifier_is_not_base_class) 12759 << SS.getScopeRep() << cast<CXXRecordDecl>(CurContext) 12760 << SS.getRange(); 12761 } 12762 return true; 12763 } 12764 12765 return false; 12766 } 12767 12768 // C++03 [namespace.udecl]p4: 12769 // A using-declaration used as a member-declaration shall refer 12770 // to a member of a base class of the class being defined [etc.]. 12771 12772 // Salient point: SS doesn't have to name a base class as long as 12773 // lookup only finds members from base classes. Therefore we can 12774 // diagnose here only if we can prove that that can't happen, 12775 // i.e. if the class hierarchies provably don't intersect. 12776 12777 // TODO: it would be nice if "definitely valid" results were cached 12778 // in the UsingDecl and UsingShadowDecl so that these checks didn't 12779 // need to be repeated. 12780 12781 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases; 12782 auto Collect = [&Bases](const CXXRecordDecl *Base) { 12783 Bases.insert(Base); 12784 return true; 12785 }; 12786 12787 // Collect all bases. Return false if we find a dependent base. 12788 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect)) 12789 return false; 12790 12791 // Returns true if the base is dependent or is one of the accumulated base 12792 // classes. 12793 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) { 12794 return !Bases.count(Base); 12795 }; 12796 12797 // Return false if the class has a dependent base or if it or one 12798 // of its bases is present in the base set of the current context. 12799 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) || 12800 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase)) 12801 return false; 12802 12803 Diag(SS.getRange().getBegin(), 12804 diag::err_using_decl_nested_name_specifier_is_not_base_class) 12805 << SS.getScopeRep() 12806 << cast<CXXRecordDecl>(CurContext) 12807 << SS.getRange(); 12808 12809 return true; 12810 } 12811 12812 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS, 12813 MultiTemplateParamsArg TemplateParamLists, 12814 SourceLocation UsingLoc, UnqualifiedId &Name, 12815 const ParsedAttributesView &AttrList, 12816 TypeResult Type, Decl *DeclFromDeclSpec) { 12817 // Skip up to the relevant declaration scope. 12818 while (S->isTemplateParamScope()) 12819 S = S->getParent(); 12820 assert((S->getFlags() & Scope::DeclScope) && 12821 "got alias-declaration outside of declaration scope"); 12822 12823 if (Type.isInvalid()) 12824 return nullptr; 12825 12826 bool Invalid = false; 12827 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 12828 TypeSourceInfo *TInfo = nullptr; 12829 GetTypeFromParser(Type.get(), &TInfo); 12830 12831 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 12832 return nullptr; 12833 12834 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 12835 UPPC_DeclarationType)) { 12836 Invalid = true; 12837 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 12838 TInfo->getTypeLoc().getBeginLoc()); 12839 } 12840 12841 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 12842 TemplateParamLists.size() 12843 ? forRedeclarationInCurContext() 12844 : ForVisibleRedeclaration); 12845 LookupName(Previous, S); 12846 12847 // Warn about shadowing the name of a template parameter. 12848 if (Previous.isSingleResult() && 12849 Previous.getFoundDecl()->isTemplateParameter()) { 12850 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 12851 Previous.clear(); 12852 } 12853 12854 assert(Name.Kind == UnqualifiedIdKind::IK_Identifier && 12855 "name in alias declaration must be an identifier"); 12856 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 12857 Name.StartLocation, 12858 Name.Identifier, TInfo); 12859 12860 NewTD->setAccess(AS); 12861 12862 if (Invalid) 12863 NewTD->setInvalidDecl(); 12864 12865 ProcessDeclAttributeList(S, NewTD, AttrList); 12866 AddPragmaAttributes(S, NewTD); 12867 12868 CheckTypedefForVariablyModifiedType(S, NewTD); 12869 Invalid |= NewTD->isInvalidDecl(); 12870 12871 bool Redeclaration = false; 12872 12873 NamedDecl *NewND; 12874 if (TemplateParamLists.size()) { 12875 TypeAliasTemplateDecl *OldDecl = nullptr; 12876 TemplateParameterList *OldTemplateParams = nullptr; 12877 12878 if (TemplateParamLists.size() != 1) { 12879 Diag(UsingLoc, diag::err_alias_template_extra_headers) 12880 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 12881 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 12882 } 12883 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 12884 12885 // Check that we can declare a template here. 12886 if (CheckTemplateDeclScope(S, TemplateParams)) 12887 return nullptr; 12888 12889 // Only consider previous declarations in the same scope. 12890 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 12891 /*ExplicitInstantiationOrSpecialization*/false); 12892 if (!Previous.empty()) { 12893 Redeclaration = true; 12894 12895 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 12896 if (!OldDecl && !Invalid) { 12897 Diag(UsingLoc, diag::err_redefinition_different_kind) 12898 << Name.Identifier; 12899 12900 NamedDecl *OldD = Previous.getRepresentativeDecl(); 12901 if (OldD->getLocation().isValid()) 12902 Diag(OldD->getLocation(), diag::note_previous_definition); 12903 12904 Invalid = true; 12905 } 12906 12907 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 12908 if (TemplateParameterListsAreEqual(TemplateParams, 12909 OldDecl->getTemplateParameters(), 12910 /*Complain=*/true, 12911 TPL_TemplateMatch)) 12912 OldTemplateParams = 12913 OldDecl->getMostRecentDecl()->getTemplateParameters(); 12914 else 12915 Invalid = true; 12916 12917 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 12918 if (!Invalid && 12919 !Context.hasSameType(OldTD->getUnderlyingType(), 12920 NewTD->getUnderlyingType())) { 12921 // FIXME: The C++0x standard does not clearly say this is ill-formed, 12922 // but we can't reasonably accept it. 12923 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 12924 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 12925 if (OldTD->getLocation().isValid()) 12926 Diag(OldTD->getLocation(), diag::note_previous_definition); 12927 Invalid = true; 12928 } 12929 } 12930 } 12931 12932 // Merge any previous default template arguments into our parameters, 12933 // and check the parameter list. 12934 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 12935 TPC_TypeAliasTemplate)) 12936 return nullptr; 12937 12938 TypeAliasTemplateDecl *NewDecl = 12939 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 12940 Name.Identifier, TemplateParams, 12941 NewTD); 12942 NewTD->setDescribedAliasTemplate(NewDecl); 12943 12944 NewDecl->setAccess(AS); 12945 12946 if (Invalid) 12947 NewDecl->setInvalidDecl(); 12948 else if (OldDecl) { 12949 NewDecl->setPreviousDecl(OldDecl); 12950 CheckRedeclarationModuleOwnership(NewDecl, OldDecl); 12951 } 12952 12953 NewND = NewDecl; 12954 } else { 12955 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { 12956 setTagNameForLinkagePurposes(TD, NewTD); 12957 handleTagNumbering(TD, S); 12958 } 12959 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 12960 NewND = NewTD; 12961 } 12962 12963 PushOnScopeChains(NewND, S); 12964 ActOnDocumentableDecl(NewND); 12965 return NewND; 12966 } 12967 12968 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 12969 SourceLocation AliasLoc, 12970 IdentifierInfo *Alias, CXXScopeSpec &SS, 12971 SourceLocation IdentLoc, 12972 IdentifierInfo *Ident) { 12973 12974 // Lookup the namespace name. 12975 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 12976 LookupParsedName(R, S, &SS); 12977 12978 if (R.isAmbiguous()) 12979 return nullptr; 12980 12981 if (R.empty()) { 12982 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 12983 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 12984 return nullptr; 12985 } 12986 } 12987 assert(!R.isAmbiguous() && !R.empty()); 12988 NamedDecl *ND = R.getRepresentativeDecl(); 12989 12990 // Check if we have a previous declaration with the same name. 12991 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName, 12992 ForVisibleRedeclaration); 12993 LookupName(PrevR, S); 12994 12995 // Check we're not shadowing a template parameter. 12996 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) { 12997 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl()); 12998 PrevR.clear(); 12999 } 13000 13001 // Filter out any other lookup result from an enclosing scope. 13002 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false, 13003 /*AllowInlineNamespace*/false); 13004 13005 // Find the previous declaration and check that we can redeclare it. 13006 NamespaceAliasDecl *Prev = nullptr; 13007 if (PrevR.isSingleResult()) { 13008 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl(); 13009 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 13010 // We already have an alias with the same name that points to the same 13011 // namespace; check that it matches. 13012 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) { 13013 Prev = AD; 13014 } else if (isVisible(PrevDecl)) { 13015 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 13016 << Alias; 13017 Diag(AD->getLocation(), diag::note_previous_namespace_alias) 13018 << AD->getNamespace(); 13019 return nullptr; 13020 } 13021 } else if (isVisible(PrevDecl)) { 13022 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl()) 13023 ? diag::err_redefinition 13024 : diag::err_redefinition_different_kind; 13025 Diag(AliasLoc, DiagID) << Alias; 13026 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 13027 return nullptr; 13028 } 13029 } 13030 13031 // The use of a nested name specifier may trigger deprecation warnings. 13032 DiagnoseUseOfDecl(ND, IdentLoc); 13033 13034 NamespaceAliasDecl *AliasDecl = 13035 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 13036 Alias, SS.getWithLocInContext(Context), 13037 IdentLoc, ND); 13038 if (Prev) 13039 AliasDecl->setPreviousDecl(Prev); 13040 13041 PushOnScopeChains(AliasDecl, S); 13042 return AliasDecl; 13043 } 13044 13045 namespace { 13046 struct SpecialMemberExceptionSpecInfo 13047 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> { 13048 SourceLocation Loc; 13049 Sema::ImplicitExceptionSpecification ExceptSpec; 13050 13051 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD, 13052 Sema::CXXSpecialMember CSM, 13053 Sema::InheritedConstructorInfo *ICI, 13054 SourceLocation Loc) 13055 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {} 13056 13057 bool visitBase(CXXBaseSpecifier *Base); 13058 bool visitField(FieldDecl *FD); 13059 13060 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 13061 unsigned Quals); 13062 13063 void visitSubobjectCall(Subobject Subobj, 13064 Sema::SpecialMemberOverloadResult SMOR); 13065 }; 13066 } 13067 13068 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) { 13069 auto *RT = Base->getType()->getAs<RecordType>(); 13070 if (!RT) 13071 return false; 13072 13073 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl()); 13074 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 13075 if (auto *BaseCtor = SMOR.getMethod()) { 13076 visitSubobjectCall(Base, BaseCtor); 13077 return false; 13078 } 13079 13080 visitClassSubobject(BaseClass, Base, 0); 13081 return false; 13082 } 13083 13084 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) { 13085 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) { 13086 Expr *E = FD->getInClassInitializer(); 13087 if (!E) 13088 // FIXME: It's a little wasteful to build and throw away a 13089 // CXXDefaultInitExpr here. 13090 // FIXME: We should have a single context note pointing at Loc, and 13091 // this location should be MD->getLocation() instead, since that's 13092 // the location where we actually use the default init expression. 13093 E = S.BuildCXXDefaultInitExpr(Loc, FD).get(); 13094 if (E) 13095 ExceptSpec.CalledExpr(E); 13096 } else if (auto *RT = S.Context.getBaseElementType(FD->getType()) 13097 ->getAs<RecordType>()) { 13098 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD, 13099 FD->getType().getCVRQualifiers()); 13100 } 13101 return false; 13102 } 13103 13104 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class, 13105 Subobject Subobj, 13106 unsigned Quals) { 13107 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 13108 bool IsMutable = Field && Field->isMutable(); 13109 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable)); 13110 } 13111 13112 void SpecialMemberExceptionSpecInfo::visitSubobjectCall( 13113 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) { 13114 // Note, if lookup fails, it doesn't matter what exception specification we 13115 // choose because the special member will be deleted. 13116 if (CXXMethodDecl *MD = SMOR.getMethod()) 13117 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD); 13118 } 13119 13120 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) { 13121 llvm::APSInt Result; 13122 ExprResult Converted = CheckConvertedConstantExpression( 13123 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool); 13124 ExplicitSpec.setExpr(Converted.get()); 13125 if (Converted.isUsable() && !Converted.get()->isValueDependent()) { 13126 ExplicitSpec.setKind(Result.getBoolValue() 13127 ? ExplicitSpecKind::ResolvedTrue 13128 : ExplicitSpecKind::ResolvedFalse); 13129 return true; 13130 } 13131 ExplicitSpec.setKind(ExplicitSpecKind::Unresolved); 13132 return false; 13133 } 13134 13135 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) { 13136 ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved); 13137 if (!ExplicitExpr->isTypeDependent()) 13138 tryResolveExplicitSpecifier(ES); 13139 return ES; 13140 } 13141 13142 static Sema::ImplicitExceptionSpecification 13143 ComputeDefaultedSpecialMemberExceptionSpec( 13144 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 13145 Sema::InheritedConstructorInfo *ICI) { 13146 ComputingExceptionSpec CES(S, MD, Loc); 13147 13148 CXXRecordDecl *ClassDecl = MD->getParent(); 13149 13150 // C++ [except.spec]p14: 13151 // An implicitly declared special member function (Clause 12) shall have an 13152 // exception-specification. [...] 13153 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation()); 13154 if (ClassDecl->isInvalidDecl()) 13155 return Info.ExceptSpec; 13156 13157 // FIXME: If this diagnostic fires, we're probably missing a check for 13158 // attempting to resolve an exception specification before it's known 13159 // at a higher level. 13160 if (S.RequireCompleteType(MD->getLocation(), 13161 S.Context.getRecordType(ClassDecl), 13162 diag::err_exception_spec_incomplete_type)) 13163 return Info.ExceptSpec; 13164 13165 // C++1z [except.spec]p7: 13166 // [Look for exceptions thrown by] a constructor selected [...] to 13167 // initialize a potentially constructed subobject, 13168 // C++1z [except.spec]p8: 13169 // The exception specification for an implicitly-declared destructor, or a 13170 // destructor without a noexcept-specifier, is potentially-throwing if and 13171 // only if any of the destructors for any of its potentially constructed 13172 // subojects is potentially throwing. 13173 // FIXME: We respect the first rule but ignore the "potentially constructed" 13174 // in the second rule to resolve a core issue (no number yet) that would have 13175 // us reject: 13176 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; }; 13177 // struct B : A {}; 13178 // struct C : B { void f(); }; 13179 // ... due to giving B::~B() a non-throwing exception specification. 13180 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases 13181 : Info.VisitAllBases); 13182 13183 return Info.ExceptSpec; 13184 } 13185 13186 namespace { 13187 /// RAII object to register a special member as being currently declared. 13188 struct DeclaringSpecialMember { 13189 Sema &S; 13190 Sema::SpecialMemberDecl D; 13191 Sema::ContextRAII SavedContext; 13192 bool WasAlreadyBeingDeclared; 13193 13194 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 13195 : S(S), D(RD, CSM), SavedContext(S, RD) { 13196 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 13197 if (WasAlreadyBeingDeclared) 13198 // This almost never happens, but if it does, ensure that our cache 13199 // doesn't contain a stale result. 13200 S.SpecialMemberCache.clear(); 13201 else { 13202 // Register a note to be produced if we encounter an error while 13203 // declaring the special member. 13204 Sema::CodeSynthesisContext Ctx; 13205 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember; 13206 // FIXME: We don't have a location to use here. Using the class's 13207 // location maintains the fiction that we declare all special members 13208 // with the class, but (1) it's not clear that lying about that helps our 13209 // users understand what's going on, and (2) there may be outer contexts 13210 // on the stack (some of which are relevant) and printing them exposes 13211 // our lies. 13212 Ctx.PointOfInstantiation = RD->getLocation(); 13213 Ctx.Entity = RD; 13214 Ctx.SpecialMember = CSM; 13215 S.pushCodeSynthesisContext(Ctx); 13216 } 13217 } 13218 ~DeclaringSpecialMember() { 13219 if (!WasAlreadyBeingDeclared) { 13220 S.SpecialMembersBeingDeclared.erase(D); 13221 S.popCodeSynthesisContext(); 13222 } 13223 } 13224 13225 /// Are we already trying to declare this special member? 13226 bool isAlreadyBeingDeclared() const { 13227 return WasAlreadyBeingDeclared; 13228 } 13229 }; 13230 } 13231 13232 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) { 13233 // Look up any existing declarations, but don't trigger declaration of all 13234 // implicit special members with this name. 13235 DeclarationName Name = FD->getDeclName(); 13236 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName, 13237 ForExternalRedeclaration); 13238 for (auto *D : FD->getParent()->lookup(Name)) 13239 if (auto *Acceptable = R.getAcceptableDecl(D)) 13240 R.addDecl(Acceptable); 13241 R.resolveKind(); 13242 R.suppressDiagnostics(); 13243 13244 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false); 13245 } 13246 13247 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem, 13248 QualType ResultTy, 13249 ArrayRef<QualType> Args) { 13250 // Build an exception specification pointing back at this constructor. 13251 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem); 13252 13253 LangAS AS = getDefaultCXXMethodAddrSpace(); 13254 if (AS != LangAS::Default) { 13255 EPI.TypeQuals.addAddressSpace(AS); 13256 } 13257 13258 auto QT = Context.getFunctionType(ResultTy, Args, EPI); 13259 SpecialMem->setType(QT); 13260 13261 // During template instantiation of implicit special member functions we need 13262 // a reliable TypeSourceInfo for the function prototype in order to allow 13263 // functions to be substituted. 13264 if (inTemplateInstantiation() && 13265 cast<CXXRecordDecl>(SpecialMem->getParent())->isLambda()) { 13266 TypeSourceInfo *TSI = 13267 Context.getTrivialTypeSourceInfo(SpecialMem->getType()); 13268 SpecialMem->setTypeSourceInfo(TSI); 13269 } 13270 } 13271 13272 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 13273 CXXRecordDecl *ClassDecl) { 13274 // C++ [class.ctor]p5: 13275 // A default constructor for a class X is a constructor of class X 13276 // that can be called without an argument. If there is no 13277 // user-declared constructor for class X, a default constructor is 13278 // implicitly declared. An implicitly-declared default constructor 13279 // is an inline public member of its class. 13280 assert(ClassDecl->needsImplicitDefaultConstructor() && 13281 "Should not build implicit default constructor!"); 13282 13283 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 13284 if (DSM.isAlreadyBeingDeclared()) 13285 return nullptr; 13286 13287 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 13288 CXXDefaultConstructor, 13289 false); 13290 13291 // Create the actual constructor declaration. 13292 CanQualType ClassType 13293 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 13294 SourceLocation ClassLoc = ClassDecl->getLocation(); 13295 DeclarationName Name 13296 = Context.DeclarationNames.getCXXConstructorName(ClassType); 13297 DeclarationNameInfo NameInfo(Name, ClassLoc); 13298 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 13299 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(), 13300 /*TInfo=*/nullptr, ExplicitSpecifier(), 13301 getCurFPFeatures().isFPConstrained(), 13302 /*isInline=*/true, /*isImplicitlyDeclared=*/true, 13303 Constexpr ? ConstexprSpecKind::Constexpr 13304 : ConstexprSpecKind::Unspecified); 13305 DefaultCon->setAccess(AS_public); 13306 DefaultCon->setDefaulted(); 13307 13308 if (getLangOpts().CUDA) { 13309 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 13310 DefaultCon, 13311 /* ConstRHS */ false, 13312 /* Diagnose */ false); 13313 } 13314 13315 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None); 13316 13317 // We don't need to use SpecialMemberIsTrivial here; triviality for default 13318 // constructors is easy to compute. 13319 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 13320 13321 // Note that we have declared this constructor. 13322 ++getASTContext().NumImplicitDefaultConstructorsDeclared; 13323 13324 Scope *S = getScopeForContext(ClassDecl); 13325 CheckImplicitSpecialMemberDeclaration(S, DefaultCon); 13326 13327 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 13328 SetDeclDeleted(DefaultCon, ClassLoc); 13329 13330 if (S) 13331 PushOnScopeChains(DefaultCon, S, false); 13332 ClassDecl->addDecl(DefaultCon); 13333 13334 return DefaultCon; 13335 } 13336 13337 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 13338 CXXConstructorDecl *Constructor) { 13339 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 13340 !Constructor->doesThisDeclarationHaveABody() && 13341 !Constructor->isDeleted()) && 13342 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 13343 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 13344 return; 13345 13346 CXXRecordDecl *ClassDecl = Constructor->getParent(); 13347 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 13348 13349 SynthesizedFunctionScope Scope(*this, Constructor); 13350 13351 // The exception specification is needed because we are defining the 13352 // function. 13353 ResolveExceptionSpec(CurrentLocation, 13354 Constructor->getType()->castAs<FunctionProtoType>()); 13355 MarkVTableUsed(CurrentLocation, ClassDecl); 13356 13357 // Add a context note for diagnostics produced after this point. 13358 Scope.addContextNote(CurrentLocation); 13359 13360 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) { 13361 Constructor->setInvalidDecl(); 13362 return; 13363 } 13364 13365 SourceLocation Loc = Constructor->getEndLoc().isValid() 13366 ? Constructor->getEndLoc() 13367 : Constructor->getLocation(); 13368 Constructor->setBody(new (Context) CompoundStmt(Loc)); 13369 Constructor->markUsed(Context); 13370 13371 if (ASTMutationListener *L = getASTMutationListener()) { 13372 L->CompletedImplicitDefinition(Constructor); 13373 } 13374 13375 DiagnoseUninitializedFields(*this, Constructor); 13376 } 13377 13378 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 13379 // Perform any delayed checks on exception specifications. 13380 CheckDelayedMemberExceptionSpecs(); 13381 } 13382 13383 /// Find or create the fake constructor we synthesize to model constructing an 13384 /// object of a derived class via a constructor of a base class. 13385 CXXConstructorDecl * 13386 Sema::findInheritingConstructor(SourceLocation Loc, 13387 CXXConstructorDecl *BaseCtor, 13388 ConstructorUsingShadowDecl *Shadow) { 13389 CXXRecordDecl *Derived = Shadow->getParent(); 13390 SourceLocation UsingLoc = Shadow->getLocation(); 13391 13392 // FIXME: Add a new kind of DeclarationName for an inherited constructor. 13393 // For now we use the name of the base class constructor as a member of the 13394 // derived class to indicate a (fake) inherited constructor name. 13395 DeclarationName Name = BaseCtor->getDeclName(); 13396 13397 // Check to see if we already have a fake constructor for this inherited 13398 // constructor call. 13399 for (NamedDecl *Ctor : Derived->lookup(Name)) 13400 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor) 13401 ->getInheritedConstructor() 13402 .getConstructor(), 13403 BaseCtor)) 13404 return cast<CXXConstructorDecl>(Ctor); 13405 13406 DeclarationNameInfo NameInfo(Name, UsingLoc); 13407 TypeSourceInfo *TInfo = 13408 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc); 13409 FunctionProtoTypeLoc ProtoLoc = 13410 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 13411 13412 // Check the inherited constructor is valid and find the list of base classes 13413 // from which it was inherited. 13414 InheritedConstructorInfo ICI(*this, Loc, Shadow); 13415 13416 bool Constexpr = 13417 BaseCtor->isConstexpr() && 13418 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor, 13419 false, BaseCtor, &ICI); 13420 13421 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 13422 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo, 13423 BaseCtor->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(), 13424 /*isInline=*/true, 13425 /*isImplicitlyDeclared=*/true, 13426 Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified, 13427 InheritedConstructor(Shadow, BaseCtor), 13428 BaseCtor->getTrailingRequiresClause()); 13429 if (Shadow->isInvalidDecl()) 13430 DerivedCtor->setInvalidDecl(); 13431 13432 // Build an unevaluated exception specification for this fake constructor. 13433 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>(); 13434 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 13435 EPI.ExceptionSpec.Type = EST_Unevaluated; 13436 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 13437 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 13438 FPT->getParamTypes(), EPI)); 13439 13440 // Build the parameter declarations. 13441 SmallVector<ParmVarDecl *, 16> ParamDecls; 13442 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 13443 TypeSourceInfo *TInfo = 13444 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 13445 ParmVarDecl *PD = ParmVarDecl::Create( 13446 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 13447 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr); 13448 PD->setScopeInfo(0, I); 13449 PD->setImplicit(); 13450 // Ensure attributes are propagated onto parameters (this matters for 13451 // format, pass_object_size, ...). 13452 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I)); 13453 ParamDecls.push_back(PD); 13454 ProtoLoc.setParam(I, PD); 13455 } 13456 13457 // Set up the new constructor. 13458 assert(!BaseCtor->isDeleted() && "should not use deleted constructor"); 13459 DerivedCtor->setAccess(BaseCtor->getAccess()); 13460 DerivedCtor->setParams(ParamDecls); 13461 Derived->addDecl(DerivedCtor); 13462 13463 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI)) 13464 SetDeclDeleted(DerivedCtor, UsingLoc); 13465 13466 return DerivedCtor; 13467 } 13468 13469 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) { 13470 InheritedConstructorInfo ICI(*this, Ctor->getLocation(), 13471 Ctor->getInheritedConstructor().getShadowDecl()); 13472 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI, 13473 /*Diagnose*/true); 13474 } 13475 13476 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 13477 CXXConstructorDecl *Constructor) { 13478 CXXRecordDecl *ClassDecl = Constructor->getParent(); 13479 assert(Constructor->getInheritedConstructor() && 13480 !Constructor->doesThisDeclarationHaveABody() && 13481 !Constructor->isDeleted()); 13482 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 13483 return; 13484 13485 // Initializations are performed "as if by a defaulted default constructor", 13486 // so enter the appropriate scope. 13487 SynthesizedFunctionScope Scope(*this, Constructor); 13488 13489 // The exception specification is needed because we are defining the 13490 // function. 13491 ResolveExceptionSpec(CurrentLocation, 13492 Constructor->getType()->castAs<FunctionProtoType>()); 13493 MarkVTableUsed(CurrentLocation, ClassDecl); 13494 13495 // Add a context note for diagnostics produced after this point. 13496 Scope.addContextNote(CurrentLocation); 13497 13498 ConstructorUsingShadowDecl *Shadow = 13499 Constructor->getInheritedConstructor().getShadowDecl(); 13500 CXXConstructorDecl *InheritedCtor = 13501 Constructor->getInheritedConstructor().getConstructor(); 13502 13503 // [class.inhctor.init]p1: 13504 // initialization proceeds as if a defaulted default constructor is used to 13505 // initialize the D object and each base class subobject from which the 13506 // constructor was inherited 13507 13508 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow); 13509 CXXRecordDecl *RD = Shadow->getParent(); 13510 SourceLocation InitLoc = Shadow->getLocation(); 13511 13512 // Build explicit initializers for all base classes from which the 13513 // constructor was inherited. 13514 SmallVector<CXXCtorInitializer*, 8> Inits; 13515 for (bool VBase : {false, true}) { 13516 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) { 13517 if (B.isVirtual() != VBase) 13518 continue; 13519 13520 auto *BaseRD = B.getType()->getAsCXXRecordDecl(); 13521 if (!BaseRD) 13522 continue; 13523 13524 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor); 13525 if (!BaseCtor.first) 13526 continue; 13527 13528 MarkFunctionReferenced(CurrentLocation, BaseCtor.first); 13529 ExprResult Init = new (Context) CXXInheritedCtorInitExpr( 13530 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second); 13531 13532 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc); 13533 Inits.push_back(new (Context) CXXCtorInitializer( 13534 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc, 13535 SourceLocation())); 13536 } 13537 } 13538 13539 // We now proceed as if for a defaulted default constructor, with the relevant 13540 // initializers replaced. 13541 13542 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) { 13543 Constructor->setInvalidDecl(); 13544 return; 13545 } 13546 13547 Constructor->setBody(new (Context) CompoundStmt(InitLoc)); 13548 Constructor->markUsed(Context); 13549 13550 if (ASTMutationListener *L = getASTMutationListener()) { 13551 L->CompletedImplicitDefinition(Constructor); 13552 } 13553 13554 DiagnoseUninitializedFields(*this, Constructor); 13555 } 13556 13557 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 13558 // C++ [class.dtor]p2: 13559 // If a class has no user-declared destructor, a destructor is 13560 // declared implicitly. An implicitly-declared destructor is an 13561 // inline public member of its class. 13562 assert(ClassDecl->needsImplicitDestructor()); 13563 13564 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 13565 if (DSM.isAlreadyBeingDeclared()) 13566 return nullptr; 13567 13568 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 13569 CXXDestructor, 13570 false); 13571 13572 // Create the actual destructor declaration. 13573 CanQualType ClassType 13574 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 13575 SourceLocation ClassLoc = ClassDecl->getLocation(); 13576 DeclarationName Name 13577 = Context.DeclarationNames.getCXXDestructorName(ClassType); 13578 DeclarationNameInfo NameInfo(Name, ClassLoc); 13579 CXXDestructorDecl *Destructor = CXXDestructorDecl::Create( 13580 Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr, 13581 getCurFPFeatures().isFPConstrained(), 13582 /*isInline=*/true, 13583 /*isImplicitlyDeclared=*/true, 13584 Constexpr ? ConstexprSpecKind::Constexpr 13585 : ConstexprSpecKind::Unspecified); 13586 Destructor->setAccess(AS_public); 13587 Destructor->setDefaulted(); 13588 13589 if (getLangOpts().CUDA) { 13590 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 13591 Destructor, 13592 /* ConstRHS */ false, 13593 /* Diagnose */ false); 13594 } 13595 13596 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None); 13597 13598 // We don't need to use SpecialMemberIsTrivial here; triviality for 13599 // destructors is easy to compute. 13600 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 13601 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() || 13602 ClassDecl->hasTrivialDestructorForCall()); 13603 13604 // Note that we have declared this destructor. 13605 ++getASTContext().NumImplicitDestructorsDeclared; 13606 13607 Scope *S = getScopeForContext(ClassDecl); 13608 CheckImplicitSpecialMemberDeclaration(S, Destructor); 13609 13610 // We can't check whether an implicit destructor is deleted before we complete 13611 // the definition of the class, because its validity depends on the alignment 13612 // of the class. We'll check this from ActOnFields once the class is complete. 13613 if (ClassDecl->isCompleteDefinition() && 13614 ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 13615 SetDeclDeleted(Destructor, ClassLoc); 13616 13617 // Introduce this destructor into its scope. 13618 if (S) 13619 PushOnScopeChains(Destructor, S, false); 13620 ClassDecl->addDecl(Destructor); 13621 13622 return Destructor; 13623 } 13624 13625 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 13626 CXXDestructorDecl *Destructor) { 13627 assert((Destructor->isDefaulted() && 13628 !Destructor->doesThisDeclarationHaveABody() && 13629 !Destructor->isDeleted()) && 13630 "DefineImplicitDestructor - call it for implicit default dtor"); 13631 if (Destructor->willHaveBody() || Destructor->isInvalidDecl()) 13632 return; 13633 13634 CXXRecordDecl *ClassDecl = Destructor->getParent(); 13635 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 13636 13637 SynthesizedFunctionScope Scope(*this, Destructor); 13638 13639 // The exception specification is needed because we are defining the 13640 // function. 13641 ResolveExceptionSpec(CurrentLocation, 13642 Destructor->getType()->castAs<FunctionProtoType>()); 13643 MarkVTableUsed(CurrentLocation, ClassDecl); 13644 13645 // Add a context note for diagnostics produced after this point. 13646 Scope.addContextNote(CurrentLocation); 13647 13648 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 13649 Destructor->getParent()); 13650 13651 if (CheckDestructor(Destructor)) { 13652 Destructor->setInvalidDecl(); 13653 return; 13654 } 13655 13656 SourceLocation Loc = Destructor->getEndLoc().isValid() 13657 ? Destructor->getEndLoc() 13658 : Destructor->getLocation(); 13659 Destructor->setBody(new (Context) CompoundStmt(Loc)); 13660 Destructor->markUsed(Context); 13661 13662 if (ASTMutationListener *L = getASTMutationListener()) { 13663 L->CompletedImplicitDefinition(Destructor); 13664 } 13665 } 13666 13667 void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation, 13668 CXXDestructorDecl *Destructor) { 13669 if (Destructor->isInvalidDecl()) 13670 return; 13671 13672 CXXRecordDecl *ClassDecl = Destructor->getParent(); 13673 assert(Context.getTargetInfo().getCXXABI().isMicrosoft() && 13674 "implicit complete dtors unneeded outside MS ABI"); 13675 assert(ClassDecl->getNumVBases() > 0 && 13676 "complete dtor only exists for classes with vbases"); 13677 13678 SynthesizedFunctionScope Scope(*this, Destructor); 13679 13680 // Add a context note for diagnostics produced after this point. 13681 Scope.addContextNote(CurrentLocation); 13682 13683 MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl); 13684 } 13685 13686 /// Perform any semantic analysis which needs to be delayed until all 13687 /// pending class member declarations have been parsed. 13688 void Sema::ActOnFinishCXXMemberDecls() { 13689 // If the context is an invalid C++ class, just suppress these checks. 13690 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 13691 if (Record->isInvalidDecl()) { 13692 DelayedOverridingExceptionSpecChecks.clear(); 13693 DelayedEquivalentExceptionSpecChecks.clear(); 13694 return; 13695 } 13696 checkForMultipleExportedDefaultConstructors(*this, Record); 13697 } 13698 } 13699 13700 void Sema::ActOnFinishCXXNonNestedClass() { 13701 referenceDLLExportedClassMethods(); 13702 13703 if (!DelayedDllExportMemberFunctions.empty()) { 13704 SmallVector<CXXMethodDecl*, 4> WorkList; 13705 std::swap(DelayedDllExportMemberFunctions, WorkList); 13706 for (CXXMethodDecl *M : WorkList) { 13707 DefineDefaultedFunction(*this, M, M->getLocation()); 13708 13709 // Pass the method to the consumer to get emitted. This is not necessary 13710 // for explicit instantiation definitions, as they will get emitted 13711 // anyway. 13712 if (M->getParent()->getTemplateSpecializationKind() != 13713 TSK_ExplicitInstantiationDefinition) 13714 ActOnFinishInlineFunctionDef(M); 13715 } 13716 } 13717 } 13718 13719 void Sema::referenceDLLExportedClassMethods() { 13720 if (!DelayedDllExportClasses.empty()) { 13721 // Calling ReferenceDllExportedMembers might cause the current function to 13722 // be called again, so use a local copy of DelayedDllExportClasses. 13723 SmallVector<CXXRecordDecl *, 4> WorkList; 13724 std::swap(DelayedDllExportClasses, WorkList); 13725 for (CXXRecordDecl *Class : WorkList) 13726 ReferenceDllExportedMembers(*this, Class); 13727 } 13728 } 13729 13730 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) { 13731 assert(getLangOpts().CPlusPlus11 && 13732 "adjusting dtor exception specs was introduced in c++11"); 13733 13734 if (Destructor->isDependentContext()) 13735 return; 13736 13737 // C++11 [class.dtor]p3: 13738 // A declaration of a destructor that does not have an exception- 13739 // specification is implicitly considered to have the same exception- 13740 // specification as an implicit declaration. 13741 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>(); 13742 if (DtorType->hasExceptionSpec()) 13743 return; 13744 13745 // Replace the destructor's type, building off the existing one. Fortunately, 13746 // the only thing of interest in the destructor type is its extended info. 13747 // The return and arguments are fixed. 13748 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 13749 EPI.ExceptionSpec.Type = EST_Unevaluated; 13750 EPI.ExceptionSpec.SourceDecl = Destructor; 13751 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 13752 13753 // FIXME: If the destructor has a body that could throw, and the newly created 13754 // spec doesn't allow exceptions, we should emit a warning, because this 13755 // change in behavior can break conforming C++03 programs at runtime. 13756 // However, we don't have a body or an exception specification yet, so it 13757 // needs to be done somewhere else. 13758 } 13759 13760 namespace { 13761 /// An abstract base class for all helper classes used in building the 13762 // copy/move operators. These classes serve as factory functions and help us 13763 // avoid using the same Expr* in the AST twice. 13764 class ExprBuilder { 13765 ExprBuilder(const ExprBuilder&) = delete; 13766 ExprBuilder &operator=(const ExprBuilder&) = delete; 13767 13768 protected: 13769 static Expr *assertNotNull(Expr *E) { 13770 assert(E && "Expression construction must not fail."); 13771 return E; 13772 } 13773 13774 public: 13775 ExprBuilder() {} 13776 virtual ~ExprBuilder() {} 13777 13778 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 13779 }; 13780 13781 class RefBuilder: public ExprBuilder { 13782 VarDecl *Var; 13783 QualType VarType; 13784 13785 public: 13786 Expr *build(Sema &S, SourceLocation Loc) const override { 13787 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc)); 13788 } 13789 13790 RefBuilder(VarDecl *Var, QualType VarType) 13791 : Var(Var), VarType(VarType) {} 13792 }; 13793 13794 class ThisBuilder: public ExprBuilder { 13795 public: 13796 Expr *build(Sema &S, SourceLocation Loc) const override { 13797 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 13798 } 13799 }; 13800 13801 class CastBuilder: public ExprBuilder { 13802 const ExprBuilder &Builder; 13803 QualType Type; 13804 ExprValueKind Kind; 13805 const CXXCastPath &Path; 13806 13807 public: 13808 Expr *build(Sema &S, SourceLocation Loc) const override { 13809 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 13810 CK_UncheckedDerivedToBase, Kind, 13811 &Path).get()); 13812 } 13813 13814 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 13815 const CXXCastPath &Path) 13816 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 13817 }; 13818 13819 class DerefBuilder: public ExprBuilder { 13820 const ExprBuilder &Builder; 13821 13822 public: 13823 Expr *build(Sema &S, SourceLocation Loc) const override { 13824 return assertNotNull( 13825 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 13826 } 13827 13828 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13829 }; 13830 13831 class MemberBuilder: public ExprBuilder { 13832 const ExprBuilder &Builder; 13833 QualType Type; 13834 CXXScopeSpec SS; 13835 bool IsArrow; 13836 LookupResult &MemberLookup; 13837 13838 public: 13839 Expr *build(Sema &S, SourceLocation Loc) const override { 13840 return assertNotNull(S.BuildMemberReferenceExpr( 13841 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 13842 nullptr, MemberLookup, nullptr, nullptr).get()); 13843 } 13844 13845 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 13846 LookupResult &MemberLookup) 13847 : Builder(Builder), Type(Type), IsArrow(IsArrow), 13848 MemberLookup(MemberLookup) {} 13849 }; 13850 13851 class MoveCastBuilder: public ExprBuilder { 13852 const ExprBuilder &Builder; 13853 13854 public: 13855 Expr *build(Sema &S, SourceLocation Loc) const override { 13856 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 13857 } 13858 13859 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13860 }; 13861 13862 class LvalueConvBuilder: public ExprBuilder { 13863 const ExprBuilder &Builder; 13864 13865 public: 13866 Expr *build(Sema &S, SourceLocation Loc) const override { 13867 return assertNotNull( 13868 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 13869 } 13870 13871 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13872 }; 13873 13874 class SubscriptBuilder: public ExprBuilder { 13875 const ExprBuilder &Base; 13876 const ExprBuilder &Index; 13877 13878 public: 13879 Expr *build(Sema &S, SourceLocation Loc) const override { 13880 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 13881 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 13882 } 13883 13884 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 13885 : Base(Base), Index(Index) {} 13886 }; 13887 13888 } // end anonymous namespace 13889 13890 /// When generating a defaulted copy or move assignment operator, if a field 13891 /// should be copied with __builtin_memcpy rather than via explicit assignments, 13892 /// do so. This optimization only applies for arrays of scalars, and for arrays 13893 /// of class type where the selected copy/move-assignment operator is trivial. 13894 static StmtResult 13895 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 13896 const ExprBuilder &ToB, const ExprBuilder &FromB) { 13897 // Compute the size of the memory buffer to be copied. 13898 QualType SizeType = S.Context.getSizeType(); 13899 llvm::APInt Size(S.Context.getTypeSize(SizeType), 13900 S.Context.getTypeSizeInChars(T).getQuantity()); 13901 13902 // Take the address of the field references for "from" and "to". We 13903 // directly construct UnaryOperators here because semantic analysis 13904 // does not permit us to take the address of an xvalue. 13905 Expr *From = FromB.build(S, Loc); 13906 From = UnaryOperator::Create( 13907 S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()), 13908 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides()); 13909 Expr *To = ToB.build(S, Loc); 13910 To = UnaryOperator::Create( 13911 S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()), 13912 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides()); 13913 13914 const Type *E = T->getBaseElementTypeUnsafe(); 13915 bool NeedsCollectableMemCpy = 13916 E->isRecordType() && 13917 E->castAs<RecordType>()->getDecl()->hasObjectMember(); 13918 13919 // Create a reference to the __builtin_objc_memmove_collectable function 13920 StringRef MemCpyName = NeedsCollectableMemCpy ? 13921 "__builtin_objc_memmove_collectable" : 13922 "__builtin_memcpy"; 13923 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 13924 Sema::LookupOrdinaryName); 13925 S.LookupName(R, S.TUScope, true); 13926 13927 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 13928 if (!MemCpy) 13929 // Something went horribly wrong earlier, and we will have complained 13930 // about it. 13931 return StmtError(); 13932 13933 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 13934 VK_PRValue, Loc, nullptr); 13935 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 13936 13937 Expr *CallArgs[] = { 13938 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 13939 }; 13940 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 13941 Loc, CallArgs, Loc); 13942 13943 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 13944 return Call.getAs<Stmt>(); 13945 } 13946 13947 /// Builds a statement that copies/moves the given entity from \p From to 13948 /// \c To. 13949 /// 13950 /// This routine is used to copy/move the members of a class with an 13951 /// implicitly-declared copy/move assignment operator. When the entities being 13952 /// copied are arrays, this routine builds for loops to copy them. 13953 /// 13954 /// \param S The Sema object used for type-checking. 13955 /// 13956 /// \param Loc The location where the implicit copy/move is being generated. 13957 /// 13958 /// \param T The type of the expressions being copied/moved. Both expressions 13959 /// must have this type. 13960 /// 13961 /// \param To The expression we are copying/moving to. 13962 /// 13963 /// \param From The expression we are copying/moving from. 13964 /// 13965 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 13966 /// Otherwise, it's a non-static member subobject. 13967 /// 13968 /// \param Copying Whether we're copying or moving. 13969 /// 13970 /// \param Depth Internal parameter recording the depth of the recursion. 13971 /// 13972 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 13973 /// if a memcpy should be used instead. 13974 static StmtResult 13975 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 13976 const ExprBuilder &To, const ExprBuilder &From, 13977 bool CopyingBaseSubobject, bool Copying, 13978 unsigned Depth = 0) { 13979 // C++11 [class.copy]p28: 13980 // Each subobject is assigned in the manner appropriate to its type: 13981 // 13982 // - if the subobject is of class type, as if by a call to operator= with 13983 // the subobject as the object expression and the corresponding 13984 // subobject of x as a single function argument (as if by explicit 13985 // qualification; that is, ignoring any possible virtual overriding 13986 // functions in more derived classes); 13987 // 13988 // C++03 [class.copy]p13: 13989 // - if the subobject is of class type, the copy assignment operator for 13990 // the class is used (as if by explicit qualification; that is, 13991 // ignoring any possible virtual overriding functions in more derived 13992 // classes); 13993 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 13994 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 13995 13996 // Look for operator=. 13997 DeclarationName Name 13998 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 13999 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 14000 S.LookupQualifiedName(OpLookup, ClassDecl, false); 14001 14002 // Prior to C++11, filter out any result that isn't a copy/move-assignment 14003 // operator. 14004 if (!S.getLangOpts().CPlusPlus11) { 14005 LookupResult::Filter F = OpLookup.makeFilter(); 14006 while (F.hasNext()) { 14007 NamedDecl *D = F.next(); 14008 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 14009 if (Method->isCopyAssignmentOperator() || 14010 (!Copying && Method->isMoveAssignmentOperator())) 14011 continue; 14012 14013 F.erase(); 14014 } 14015 F.done(); 14016 } 14017 14018 // Suppress the protected check (C++ [class.protected]) for each of the 14019 // assignment operators we found. This strange dance is required when 14020 // we're assigning via a base classes's copy-assignment operator. To 14021 // ensure that we're getting the right base class subobject (without 14022 // ambiguities), we need to cast "this" to that subobject type; to 14023 // ensure that we don't go through the virtual call mechanism, we need 14024 // to qualify the operator= name with the base class (see below). However, 14025 // this means that if the base class has a protected copy assignment 14026 // operator, the protected member access check will fail. So, we 14027 // rewrite "protected" access to "public" access in this case, since we 14028 // know by construction that we're calling from a derived class. 14029 if (CopyingBaseSubobject) { 14030 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 14031 L != LEnd; ++L) { 14032 if (L.getAccess() == AS_protected) 14033 L.setAccess(AS_public); 14034 } 14035 } 14036 14037 // Create the nested-name-specifier that will be used to qualify the 14038 // reference to operator=; this is required to suppress the virtual 14039 // call mechanism. 14040 CXXScopeSpec SS; 14041 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 14042 SS.MakeTrivial(S.Context, 14043 NestedNameSpecifier::Create(S.Context, nullptr, false, 14044 CanonicalT), 14045 Loc); 14046 14047 // Create the reference to operator=. 14048 ExprResult OpEqualRef 14049 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false, 14050 SS, /*TemplateKWLoc=*/SourceLocation(), 14051 /*FirstQualifierInScope=*/nullptr, 14052 OpLookup, 14053 /*TemplateArgs=*/nullptr, /*S*/nullptr, 14054 /*SuppressQualifierCheck=*/true); 14055 if (OpEqualRef.isInvalid()) 14056 return StmtError(); 14057 14058 // Build the call to the assignment operator. 14059 14060 Expr *FromInst = From.build(S, Loc); 14061 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 14062 OpEqualRef.getAs<Expr>(), 14063 Loc, FromInst, Loc); 14064 if (Call.isInvalid()) 14065 return StmtError(); 14066 14067 // If we built a call to a trivial 'operator=' while copying an array, 14068 // bail out. We'll replace the whole shebang with a memcpy. 14069 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 14070 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 14071 return StmtResult((Stmt*)nullptr); 14072 14073 // Convert to an expression-statement, and clean up any produced 14074 // temporaries. 14075 return S.ActOnExprStmt(Call); 14076 } 14077 14078 // - if the subobject is of scalar type, the built-in assignment 14079 // operator is used. 14080 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 14081 if (!ArrayTy) { 14082 ExprResult Assignment = S.CreateBuiltinBinOp( 14083 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 14084 if (Assignment.isInvalid()) 14085 return StmtError(); 14086 return S.ActOnExprStmt(Assignment); 14087 } 14088 14089 // - if the subobject is an array, each element is assigned, in the 14090 // manner appropriate to the element type; 14091 14092 // Construct a loop over the array bounds, e.g., 14093 // 14094 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 14095 // 14096 // that will copy each of the array elements. 14097 QualType SizeType = S.Context.getSizeType(); 14098 14099 // Create the iteration variable. 14100 IdentifierInfo *IterationVarName = nullptr; 14101 { 14102 SmallString<8> Str; 14103 llvm::raw_svector_ostream OS(Str); 14104 OS << "__i" << Depth; 14105 IterationVarName = &S.Context.Idents.get(OS.str()); 14106 } 14107 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 14108 IterationVarName, SizeType, 14109 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 14110 SC_None); 14111 14112 // Initialize the iteration variable to zero. 14113 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 14114 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 14115 14116 // Creates a reference to the iteration variable. 14117 RefBuilder IterationVarRef(IterationVar, SizeType); 14118 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 14119 14120 // Create the DeclStmt that holds the iteration variable. 14121 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 14122 14123 // Subscript the "from" and "to" expressions with the iteration variable. 14124 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 14125 MoveCastBuilder FromIndexMove(FromIndexCopy); 14126 const ExprBuilder *FromIndex; 14127 if (Copying) 14128 FromIndex = &FromIndexCopy; 14129 else 14130 FromIndex = &FromIndexMove; 14131 14132 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 14133 14134 // Build the copy/move for an individual element of the array. 14135 StmtResult Copy = 14136 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 14137 ToIndex, *FromIndex, CopyingBaseSubobject, 14138 Copying, Depth + 1); 14139 // Bail out if copying fails or if we determined that we should use memcpy. 14140 if (Copy.isInvalid() || !Copy.get()) 14141 return Copy; 14142 14143 // Create the comparison against the array bound. 14144 llvm::APInt Upper 14145 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 14146 Expr *Comparison = BinaryOperator::Create( 14147 S.Context, IterationVarRefRVal.build(S, Loc), 14148 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE, 14149 S.Context.BoolTy, VK_PRValue, OK_Ordinary, Loc, 14150 S.CurFPFeatureOverrides()); 14151 14152 // Create the pre-increment of the iteration variable. We can determine 14153 // whether the increment will overflow based on the value of the array 14154 // bound. 14155 Expr *Increment = UnaryOperator::Create( 14156 S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue, 14157 OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides()); 14158 14159 // Construct the loop that copies all elements of this array. 14160 return S.ActOnForStmt( 14161 Loc, Loc, InitStmt, 14162 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean), 14163 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get()); 14164 } 14165 14166 static StmtResult 14167 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 14168 const ExprBuilder &To, const ExprBuilder &From, 14169 bool CopyingBaseSubobject, bool Copying) { 14170 // Maybe we should use a memcpy? 14171 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 14172 T.isTriviallyCopyableType(S.Context)) 14173 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 14174 14175 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 14176 CopyingBaseSubobject, 14177 Copying, 0)); 14178 14179 // If we ended up picking a trivial assignment operator for an array of a 14180 // non-trivially-copyable class type, just emit a memcpy. 14181 if (!Result.isInvalid() && !Result.get()) 14182 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 14183 14184 return Result; 14185 } 14186 14187 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 14188 // Note: The following rules are largely analoguous to the copy 14189 // constructor rules. Note that virtual bases are not taken into account 14190 // for determining the argument type of the operator. Note also that 14191 // operators taking an object instead of a reference are allowed. 14192 assert(ClassDecl->needsImplicitCopyAssignment()); 14193 14194 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 14195 if (DSM.isAlreadyBeingDeclared()) 14196 return nullptr; 14197 14198 QualType ArgType = Context.getTypeDeclType(ClassDecl); 14199 LangAS AS = getDefaultCXXMethodAddrSpace(); 14200 if (AS != LangAS::Default) 14201 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 14202 QualType RetType = Context.getLValueReferenceType(ArgType); 14203 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 14204 if (Const) 14205 ArgType = ArgType.withConst(); 14206 14207 ArgType = Context.getLValueReferenceType(ArgType); 14208 14209 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14210 CXXCopyAssignment, 14211 Const); 14212 14213 // An implicitly-declared copy assignment operator is an inline public 14214 // member of its class. 14215 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 14216 SourceLocation ClassLoc = ClassDecl->getLocation(); 14217 DeclarationNameInfo NameInfo(Name, ClassLoc); 14218 CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create( 14219 Context, ClassDecl, ClassLoc, NameInfo, QualType(), 14220 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 14221 getCurFPFeatures().isFPConstrained(), 14222 /*isInline=*/true, 14223 Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified, 14224 SourceLocation()); 14225 CopyAssignment->setAccess(AS_public); 14226 CopyAssignment->setDefaulted(); 14227 CopyAssignment->setImplicit(); 14228 14229 if (getLangOpts().CUDA) { 14230 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 14231 CopyAssignment, 14232 /* ConstRHS */ Const, 14233 /* Diagnose */ false); 14234 } 14235 14236 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType); 14237 14238 // Add the parameter to the operator. 14239 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 14240 ClassLoc, ClassLoc, 14241 /*Id=*/nullptr, ArgType, 14242 /*TInfo=*/nullptr, SC_None, 14243 nullptr); 14244 CopyAssignment->setParams(FromParam); 14245 14246 CopyAssignment->setTrivial( 14247 ClassDecl->needsOverloadResolutionForCopyAssignment() 14248 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 14249 : ClassDecl->hasTrivialCopyAssignment()); 14250 14251 // Note that we have added this copy-assignment operator. 14252 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared; 14253 14254 Scope *S = getScopeForContext(ClassDecl); 14255 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment); 14256 14257 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) { 14258 ClassDecl->setImplicitCopyAssignmentIsDeleted(); 14259 SetDeclDeleted(CopyAssignment, ClassLoc); 14260 } 14261 14262 if (S) 14263 PushOnScopeChains(CopyAssignment, S, false); 14264 ClassDecl->addDecl(CopyAssignment); 14265 14266 return CopyAssignment; 14267 } 14268 14269 /// Diagnose an implicit copy operation for a class which is odr-used, but 14270 /// which is deprecated because the class has a user-declared copy constructor, 14271 /// copy assignment operator, or destructor. 14272 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) { 14273 assert(CopyOp->isImplicit()); 14274 14275 CXXRecordDecl *RD = CopyOp->getParent(); 14276 CXXMethodDecl *UserDeclaredOperation = nullptr; 14277 14278 // In Microsoft mode, assignment operations don't affect constructors and 14279 // vice versa. 14280 if (RD->hasUserDeclaredDestructor()) { 14281 UserDeclaredOperation = RD->getDestructor(); 14282 } else if (!isa<CXXConstructorDecl>(CopyOp) && 14283 RD->hasUserDeclaredCopyConstructor() && 14284 !S.getLangOpts().MSVCCompat) { 14285 // Find any user-declared copy constructor. 14286 for (auto *I : RD->ctors()) { 14287 if (I->isCopyConstructor()) { 14288 UserDeclaredOperation = I; 14289 break; 14290 } 14291 } 14292 assert(UserDeclaredOperation); 14293 } else if (isa<CXXConstructorDecl>(CopyOp) && 14294 RD->hasUserDeclaredCopyAssignment() && 14295 !S.getLangOpts().MSVCCompat) { 14296 // Find any user-declared move assignment operator. 14297 for (auto *I : RD->methods()) { 14298 if (I->isCopyAssignmentOperator()) { 14299 UserDeclaredOperation = I; 14300 break; 14301 } 14302 } 14303 assert(UserDeclaredOperation); 14304 } 14305 14306 if (UserDeclaredOperation) { 14307 bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided(); 14308 bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation); 14309 bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp); 14310 unsigned DiagID = 14311 (UDOIsUserProvided && UDOIsDestructor) 14312 ? diag::warn_deprecated_copy_with_user_provided_dtor 14313 : (UDOIsUserProvided && !UDOIsDestructor) 14314 ? diag::warn_deprecated_copy_with_user_provided_copy 14315 : (!UDOIsUserProvided && UDOIsDestructor) 14316 ? diag::warn_deprecated_copy_with_dtor 14317 : diag::warn_deprecated_copy; 14318 S.Diag(UserDeclaredOperation->getLocation(), DiagID) 14319 << RD << IsCopyAssignment; 14320 } 14321 } 14322 14323 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 14324 CXXMethodDecl *CopyAssignOperator) { 14325 assert((CopyAssignOperator->isDefaulted() && 14326 CopyAssignOperator->isOverloadedOperator() && 14327 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 14328 !CopyAssignOperator->doesThisDeclarationHaveABody() && 14329 !CopyAssignOperator->isDeleted()) && 14330 "DefineImplicitCopyAssignment called for wrong function"); 14331 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl()) 14332 return; 14333 14334 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 14335 if (ClassDecl->isInvalidDecl()) { 14336 CopyAssignOperator->setInvalidDecl(); 14337 return; 14338 } 14339 14340 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 14341 14342 // The exception specification is needed because we are defining the 14343 // function. 14344 ResolveExceptionSpec(CurrentLocation, 14345 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 14346 14347 // Add a context note for diagnostics produced after this point. 14348 Scope.addContextNote(CurrentLocation); 14349 14350 // C++11 [class.copy]p18: 14351 // The [definition of an implicitly declared copy assignment operator] is 14352 // deprecated if the class has a user-declared copy constructor or a 14353 // user-declared destructor. 14354 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 14355 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator); 14356 14357 // C++0x [class.copy]p30: 14358 // The implicitly-defined or explicitly-defaulted copy assignment operator 14359 // for a non-union class X performs memberwise copy assignment of its 14360 // subobjects. The direct base classes of X are assigned first, in the 14361 // order of their declaration in the base-specifier-list, and then the 14362 // immediate non-static data members of X are assigned, in the order in 14363 // which they were declared in the class definition. 14364 14365 // The statements that form the synthesized function body. 14366 SmallVector<Stmt*, 8> Statements; 14367 14368 // The parameter for the "other" object, which we are copying from. 14369 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 14370 Qualifiers OtherQuals = Other->getType().getQualifiers(); 14371 QualType OtherRefType = Other->getType(); 14372 if (const LValueReferenceType *OtherRef 14373 = OtherRefType->getAs<LValueReferenceType>()) { 14374 OtherRefType = OtherRef->getPointeeType(); 14375 OtherQuals = OtherRefType.getQualifiers(); 14376 } 14377 14378 // Our location for everything implicitly-generated. 14379 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid() 14380 ? CopyAssignOperator->getEndLoc() 14381 : CopyAssignOperator->getLocation(); 14382 14383 // Builds a DeclRefExpr for the "other" object. 14384 RefBuilder OtherRef(Other, OtherRefType); 14385 14386 // Builds the "this" pointer. 14387 ThisBuilder This; 14388 14389 // Assign base classes. 14390 bool Invalid = false; 14391 for (auto &Base : ClassDecl->bases()) { 14392 // Form the assignment: 14393 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 14394 QualType BaseType = Base.getType().getUnqualifiedType(); 14395 if (!BaseType->isRecordType()) { 14396 Invalid = true; 14397 continue; 14398 } 14399 14400 CXXCastPath BasePath; 14401 BasePath.push_back(&Base); 14402 14403 // Construct the "from" expression, which is an implicit cast to the 14404 // appropriately-qualified base type. 14405 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 14406 VK_LValue, BasePath); 14407 14408 // Dereference "this". 14409 DerefBuilder DerefThis(This); 14410 CastBuilder To(DerefThis, 14411 Context.getQualifiedType( 14412 BaseType, CopyAssignOperator->getMethodQualifiers()), 14413 VK_LValue, BasePath); 14414 14415 // Build the copy. 14416 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 14417 To, From, 14418 /*CopyingBaseSubobject=*/true, 14419 /*Copying=*/true); 14420 if (Copy.isInvalid()) { 14421 CopyAssignOperator->setInvalidDecl(); 14422 return; 14423 } 14424 14425 // Success! Record the copy. 14426 Statements.push_back(Copy.getAs<Expr>()); 14427 } 14428 14429 // Assign non-static members. 14430 for (auto *Field : ClassDecl->fields()) { 14431 // FIXME: We should form some kind of AST representation for the implied 14432 // memcpy in a union copy operation. 14433 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 14434 continue; 14435 14436 if (Field->isInvalidDecl()) { 14437 Invalid = true; 14438 continue; 14439 } 14440 14441 // Check for members of reference type; we can't copy those. 14442 if (Field->getType()->isReferenceType()) { 14443 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14444 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 14445 Diag(Field->getLocation(), diag::note_declared_at); 14446 Invalid = true; 14447 continue; 14448 } 14449 14450 // Check for members of const-qualified, non-class type. 14451 QualType BaseType = Context.getBaseElementType(Field->getType()); 14452 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 14453 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14454 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 14455 Diag(Field->getLocation(), diag::note_declared_at); 14456 Invalid = true; 14457 continue; 14458 } 14459 14460 // Suppress assigning zero-width bitfields. 14461 if (Field->isZeroLengthBitField(Context)) 14462 continue; 14463 14464 QualType FieldType = Field->getType().getNonReferenceType(); 14465 if (FieldType->isIncompleteArrayType()) { 14466 assert(ClassDecl->hasFlexibleArrayMember() && 14467 "Incomplete array type is not valid"); 14468 continue; 14469 } 14470 14471 // Build references to the field in the object we're copying from and to. 14472 CXXScopeSpec SS; // Intentionally empty 14473 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 14474 LookupMemberName); 14475 MemberLookup.addDecl(Field); 14476 MemberLookup.resolveKind(); 14477 14478 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 14479 14480 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 14481 14482 // Build the copy of this field. 14483 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 14484 To, From, 14485 /*CopyingBaseSubobject=*/false, 14486 /*Copying=*/true); 14487 if (Copy.isInvalid()) { 14488 CopyAssignOperator->setInvalidDecl(); 14489 return; 14490 } 14491 14492 // Success! Record the copy. 14493 Statements.push_back(Copy.getAs<Stmt>()); 14494 } 14495 14496 if (!Invalid) { 14497 // Add a "return *this;" 14498 ExprResult ThisObj = 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 CopyAssignOperator->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 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 14520 CopyAssignOperator->markUsed(Context); 14521 14522 if (ASTMutationListener *L = getASTMutationListener()) { 14523 L->CompletedImplicitDefinition(CopyAssignOperator); 14524 } 14525 } 14526 14527 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 14528 assert(ClassDecl->needsImplicitMoveAssignment()); 14529 14530 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 14531 if (DSM.isAlreadyBeingDeclared()) 14532 return nullptr; 14533 14534 // Note: The following rules are largely analoguous to the move 14535 // constructor rules. 14536 14537 QualType ArgType = Context.getTypeDeclType(ClassDecl); 14538 LangAS AS = getDefaultCXXMethodAddrSpace(); 14539 if (AS != LangAS::Default) 14540 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 14541 QualType RetType = Context.getLValueReferenceType(ArgType); 14542 ArgType = Context.getRValueReferenceType(ArgType); 14543 14544 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14545 CXXMoveAssignment, 14546 false); 14547 14548 // An implicitly-declared move assignment operator is an inline public 14549 // member of its class. 14550 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 14551 SourceLocation ClassLoc = ClassDecl->getLocation(); 14552 DeclarationNameInfo NameInfo(Name, ClassLoc); 14553 CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create( 14554 Context, ClassDecl, ClassLoc, NameInfo, QualType(), 14555 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 14556 getCurFPFeatures().isFPConstrained(), 14557 /*isInline=*/true, 14558 Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified, 14559 SourceLocation()); 14560 MoveAssignment->setAccess(AS_public); 14561 MoveAssignment->setDefaulted(); 14562 MoveAssignment->setImplicit(); 14563 14564 if (getLangOpts().CUDA) { 14565 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 14566 MoveAssignment, 14567 /* ConstRHS */ false, 14568 /* Diagnose */ false); 14569 } 14570 14571 setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType); 14572 14573 // Add the parameter to the operator. 14574 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 14575 ClassLoc, ClassLoc, 14576 /*Id=*/nullptr, ArgType, 14577 /*TInfo=*/nullptr, SC_None, 14578 nullptr); 14579 MoveAssignment->setParams(FromParam); 14580 14581 MoveAssignment->setTrivial( 14582 ClassDecl->needsOverloadResolutionForMoveAssignment() 14583 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 14584 : ClassDecl->hasTrivialMoveAssignment()); 14585 14586 // Note that we have added this copy-assignment operator. 14587 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared; 14588 14589 Scope *S = getScopeForContext(ClassDecl); 14590 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment); 14591 14592 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 14593 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 14594 SetDeclDeleted(MoveAssignment, ClassLoc); 14595 } 14596 14597 if (S) 14598 PushOnScopeChains(MoveAssignment, S, false); 14599 ClassDecl->addDecl(MoveAssignment); 14600 14601 return MoveAssignment; 14602 } 14603 14604 /// Check if we're implicitly defining a move assignment operator for a class 14605 /// with virtual bases. Such a move assignment might move-assign the virtual 14606 /// base multiple times. 14607 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 14608 SourceLocation CurrentLocation) { 14609 assert(!Class->isDependentContext() && "should not define dependent move"); 14610 14611 // Only a virtual base could get implicitly move-assigned multiple times. 14612 // Only a non-trivial move assignment can observe this. We only want to 14613 // diagnose if we implicitly define an assignment operator that assigns 14614 // two base classes, both of which move-assign the same virtual base. 14615 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 14616 Class->getNumBases() < 2) 14617 return; 14618 14619 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 14620 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 14621 VBaseMap VBases; 14622 14623 for (auto &BI : Class->bases()) { 14624 Worklist.push_back(&BI); 14625 while (!Worklist.empty()) { 14626 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 14627 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 14628 14629 // If the base has no non-trivial move assignment operators, 14630 // we don't care about moves from it. 14631 if (!Base->hasNonTrivialMoveAssignment()) 14632 continue; 14633 14634 // If there's nothing virtual here, skip it. 14635 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 14636 continue; 14637 14638 // If we're not actually going to call a move assignment for this base, 14639 // or the selected move assignment is trivial, skip it. 14640 Sema::SpecialMemberOverloadResult SMOR = 14641 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 14642 /*ConstArg*/false, /*VolatileArg*/false, 14643 /*RValueThis*/true, /*ConstThis*/false, 14644 /*VolatileThis*/false); 14645 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() || 14646 !SMOR.getMethod()->isMoveAssignmentOperator()) 14647 continue; 14648 14649 if (BaseSpec->isVirtual()) { 14650 // We're going to move-assign this virtual base, and its move 14651 // assignment operator is not trivial. If this can happen for 14652 // multiple distinct direct bases of Class, diagnose it. (If it 14653 // only happens in one base, we'll diagnose it when synthesizing 14654 // that base class's move assignment operator.) 14655 CXXBaseSpecifier *&Existing = 14656 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 14657 .first->second; 14658 if (Existing && Existing != &BI) { 14659 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 14660 << Class << Base; 14661 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here) 14662 << (Base->getCanonicalDecl() == 14663 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 14664 << Base << Existing->getType() << Existing->getSourceRange(); 14665 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here) 14666 << (Base->getCanonicalDecl() == 14667 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 14668 << Base << BI.getType() << BaseSpec->getSourceRange(); 14669 14670 // Only diagnose each vbase once. 14671 Existing = nullptr; 14672 } 14673 } else { 14674 // Only walk over bases that have defaulted move assignment operators. 14675 // We assume that any user-provided move assignment operator handles 14676 // the multiple-moves-of-vbase case itself somehow. 14677 if (!SMOR.getMethod()->isDefaulted()) 14678 continue; 14679 14680 // We're going to move the base classes of Base. Add them to the list. 14681 for (auto &BI : Base->bases()) 14682 Worklist.push_back(&BI); 14683 } 14684 } 14685 } 14686 } 14687 14688 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 14689 CXXMethodDecl *MoveAssignOperator) { 14690 assert((MoveAssignOperator->isDefaulted() && 14691 MoveAssignOperator->isOverloadedOperator() && 14692 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 14693 !MoveAssignOperator->doesThisDeclarationHaveABody() && 14694 !MoveAssignOperator->isDeleted()) && 14695 "DefineImplicitMoveAssignment called for wrong function"); 14696 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl()) 14697 return; 14698 14699 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 14700 if (ClassDecl->isInvalidDecl()) { 14701 MoveAssignOperator->setInvalidDecl(); 14702 return; 14703 } 14704 14705 // C++0x [class.copy]p28: 14706 // The implicitly-defined or move assignment operator for a non-union class 14707 // X performs memberwise move assignment of its subobjects. The direct base 14708 // classes of X are assigned first, in the order of their declaration in the 14709 // base-specifier-list, and then the immediate non-static data members of X 14710 // are assigned, in the order in which they were declared in the class 14711 // definition. 14712 14713 // Issue a warning if our implicit move assignment operator will move 14714 // from a virtual base more than once. 14715 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 14716 14717 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 14718 14719 // The exception specification is needed because we are defining the 14720 // function. 14721 ResolveExceptionSpec(CurrentLocation, 14722 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 14723 14724 // Add a context note for diagnostics produced after this point. 14725 Scope.addContextNote(CurrentLocation); 14726 14727 // The statements that form the synthesized function body. 14728 SmallVector<Stmt*, 8> Statements; 14729 14730 // The parameter for the "other" object, which we are move from. 14731 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 14732 QualType OtherRefType = 14733 Other->getType()->castAs<RValueReferenceType>()->getPointeeType(); 14734 14735 // Our location for everything implicitly-generated. 14736 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid() 14737 ? MoveAssignOperator->getEndLoc() 14738 : MoveAssignOperator->getLocation(); 14739 14740 // Builds a reference to the "other" object. 14741 RefBuilder OtherRef(Other, OtherRefType); 14742 // Cast to rvalue. 14743 MoveCastBuilder MoveOther(OtherRef); 14744 14745 // Builds the "this" pointer. 14746 ThisBuilder This; 14747 14748 // Assign base classes. 14749 bool Invalid = false; 14750 for (auto &Base : ClassDecl->bases()) { 14751 // C++11 [class.copy]p28: 14752 // It is unspecified whether subobjects representing virtual base classes 14753 // are assigned more than once by the implicitly-defined copy assignment 14754 // operator. 14755 // FIXME: Do not assign to a vbase that will be assigned by some other base 14756 // class. For a move-assignment, this can result in the vbase being moved 14757 // multiple times. 14758 14759 // Form the assignment: 14760 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 14761 QualType BaseType = Base.getType().getUnqualifiedType(); 14762 if (!BaseType->isRecordType()) { 14763 Invalid = true; 14764 continue; 14765 } 14766 14767 CXXCastPath BasePath; 14768 BasePath.push_back(&Base); 14769 14770 // Construct the "from" expression, which is an implicit cast to the 14771 // appropriately-qualified base type. 14772 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 14773 14774 // Dereference "this". 14775 DerefBuilder DerefThis(This); 14776 14777 // Implicitly cast "this" to the appropriately-qualified base type. 14778 CastBuilder To(DerefThis, 14779 Context.getQualifiedType( 14780 BaseType, MoveAssignOperator->getMethodQualifiers()), 14781 VK_LValue, BasePath); 14782 14783 // Build the move. 14784 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 14785 To, From, 14786 /*CopyingBaseSubobject=*/true, 14787 /*Copying=*/false); 14788 if (Move.isInvalid()) { 14789 MoveAssignOperator->setInvalidDecl(); 14790 return; 14791 } 14792 14793 // Success! Record the move. 14794 Statements.push_back(Move.getAs<Expr>()); 14795 } 14796 14797 // Assign non-static members. 14798 for (auto *Field : ClassDecl->fields()) { 14799 // FIXME: We should form some kind of AST representation for the implied 14800 // memcpy in a union copy operation. 14801 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 14802 continue; 14803 14804 if (Field->isInvalidDecl()) { 14805 Invalid = true; 14806 continue; 14807 } 14808 14809 // Check for members of reference type; we can't move those. 14810 if (Field->getType()->isReferenceType()) { 14811 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14812 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 14813 Diag(Field->getLocation(), diag::note_declared_at); 14814 Invalid = true; 14815 continue; 14816 } 14817 14818 // Check for members of const-qualified, non-class type. 14819 QualType BaseType = Context.getBaseElementType(Field->getType()); 14820 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 14821 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14822 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 14823 Diag(Field->getLocation(), diag::note_declared_at); 14824 Invalid = true; 14825 continue; 14826 } 14827 14828 // Suppress assigning zero-width bitfields. 14829 if (Field->isZeroLengthBitField(Context)) 14830 continue; 14831 14832 QualType FieldType = Field->getType().getNonReferenceType(); 14833 if (FieldType->isIncompleteArrayType()) { 14834 assert(ClassDecl->hasFlexibleArrayMember() && 14835 "Incomplete array type is not valid"); 14836 continue; 14837 } 14838 14839 // Build references to the field in the object we're copying from and to. 14840 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 14841 LookupMemberName); 14842 MemberLookup.addDecl(Field); 14843 MemberLookup.resolveKind(); 14844 MemberBuilder From(MoveOther, OtherRefType, 14845 /*IsArrow=*/false, MemberLookup); 14846 MemberBuilder To(This, getCurrentThisType(), 14847 /*IsArrow=*/true, MemberLookup); 14848 14849 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 14850 "Member reference with rvalue base must be rvalue except for reference " 14851 "members, which aren't allowed for move assignment."); 14852 14853 // Build the move of this field. 14854 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 14855 To, From, 14856 /*CopyingBaseSubobject=*/false, 14857 /*Copying=*/false); 14858 if (Move.isInvalid()) { 14859 MoveAssignOperator->setInvalidDecl(); 14860 return; 14861 } 14862 14863 // Success! Record the copy. 14864 Statements.push_back(Move.getAs<Stmt>()); 14865 } 14866 14867 if (!Invalid) { 14868 // Add a "return *this;" 14869 ExprResult ThisObj = 14870 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 14871 14872 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 14873 if (Return.isInvalid()) 14874 Invalid = true; 14875 else 14876 Statements.push_back(Return.getAs<Stmt>()); 14877 } 14878 14879 if (Invalid) { 14880 MoveAssignOperator->setInvalidDecl(); 14881 return; 14882 } 14883 14884 StmtResult Body; 14885 { 14886 CompoundScopeRAII CompoundScope(*this); 14887 Body = ActOnCompoundStmt(Loc, Loc, Statements, 14888 /*isStmtExpr=*/false); 14889 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 14890 } 14891 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 14892 MoveAssignOperator->markUsed(Context); 14893 14894 if (ASTMutationListener *L = getASTMutationListener()) { 14895 L->CompletedImplicitDefinition(MoveAssignOperator); 14896 } 14897 } 14898 14899 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 14900 CXXRecordDecl *ClassDecl) { 14901 // C++ [class.copy]p4: 14902 // If the class definition does not explicitly declare a copy 14903 // constructor, one is declared implicitly. 14904 assert(ClassDecl->needsImplicitCopyConstructor()); 14905 14906 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 14907 if (DSM.isAlreadyBeingDeclared()) 14908 return nullptr; 14909 14910 QualType ClassType = Context.getTypeDeclType(ClassDecl); 14911 QualType ArgType = ClassType; 14912 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 14913 if (Const) 14914 ArgType = ArgType.withConst(); 14915 14916 LangAS AS = getDefaultCXXMethodAddrSpace(); 14917 if (AS != LangAS::Default) 14918 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 14919 14920 ArgType = Context.getLValueReferenceType(ArgType); 14921 14922 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14923 CXXCopyConstructor, 14924 Const); 14925 14926 DeclarationName Name 14927 = Context.DeclarationNames.getCXXConstructorName( 14928 Context.getCanonicalType(ClassType)); 14929 SourceLocation ClassLoc = ClassDecl->getLocation(); 14930 DeclarationNameInfo NameInfo(Name, ClassLoc); 14931 14932 // An implicitly-declared copy constructor is an inline public 14933 // member of its class. 14934 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 14935 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 14936 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(), 14937 /*isInline=*/true, 14938 /*isImplicitlyDeclared=*/true, 14939 Constexpr ? ConstexprSpecKind::Constexpr 14940 : ConstexprSpecKind::Unspecified); 14941 CopyConstructor->setAccess(AS_public); 14942 CopyConstructor->setDefaulted(); 14943 14944 if (getLangOpts().CUDA) { 14945 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 14946 CopyConstructor, 14947 /* ConstRHS */ Const, 14948 /* Diagnose */ false); 14949 } 14950 14951 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType); 14952 14953 // During template instantiation of special member functions we need a 14954 // reliable TypeSourceInfo for the parameter types in order to allow functions 14955 // to be substituted. 14956 TypeSourceInfo *TSI = nullptr; 14957 if (inTemplateInstantiation() && ClassDecl->isLambda()) 14958 TSI = Context.getTrivialTypeSourceInfo(ArgType); 14959 14960 // Add the parameter to the constructor. 14961 ParmVarDecl *FromParam = 14962 ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc, 14963 /*IdentifierInfo=*/nullptr, ArgType, 14964 /*TInfo=*/TSI, SC_None, nullptr); 14965 CopyConstructor->setParams(FromParam); 14966 14967 CopyConstructor->setTrivial( 14968 ClassDecl->needsOverloadResolutionForCopyConstructor() 14969 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 14970 : ClassDecl->hasTrivialCopyConstructor()); 14971 14972 CopyConstructor->setTrivialForCall( 14973 ClassDecl->hasAttr<TrivialABIAttr>() || 14974 (ClassDecl->needsOverloadResolutionForCopyConstructor() 14975 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor, 14976 TAH_ConsiderTrivialABI) 14977 : ClassDecl->hasTrivialCopyConstructorForCall())); 14978 14979 // Note that we have declared this constructor. 14980 ++getASTContext().NumImplicitCopyConstructorsDeclared; 14981 14982 Scope *S = getScopeForContext(ClassDecl); 14983 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor); 14984 14985 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) { 14986 ClassDecl->setImplicitCopyConstructorIsDeleted(); 14987 SetDeclDeleted(CopyConstructor, ClassLoc); 14988 } 14989 14990 if (S) 14991 PushOnScopeChains(CopyConstructor, S, false); 14992 ClassDecl->addDecl(CopyConstructor); 14993 14994 return CopyConstructor; 14995 } 14996 14997 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 14998 CXXConstructorDecl *CopyConstructor) { 14999 assert((CopyConstructor->isDefaulted() && 15000 CopyConstructor->isCopyConstructor() && 15001 !CopyConstructor->doesThisDeclarationHaveABody() && 15002 !CopyConstructor->isDeleted()) && 15003 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 15004 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl()) 15005 return; 15006 15007 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 15008 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 15009 15010 SynthesizedFunctionScope Scope(*this, CopyConstructor); 15011 15012 // The exception specification is needed because we are defining the 15013 // function. 15014 ResolveExceptionSpec(CurrentLocation, 15015 CopyConstructor->getType()->castAs<FunctionProtoType>()); 15016 MarkVTableUsed(CurrentLocation, ClassDecl); 15017 15018 // Add a context note for diagnostics produced after this point. 15019 Scope.addContextNote(CurrentLocation); 15020 15021 // C++11 [class.copy]p7: 15022 // The [definition of an implicitly declared copy constructor] is 15023 // deprecated if the class has a user-declared copy assignment operator 15024 // or a user-declared destructor. 15025 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 15026 diagnoseDeprecatedCopyOperation(*this, CopyConstructor); 15027 15028 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) { 15029 CopyConstructor->setInvalidDecl(); 15030 } else { 15031 SourceLocation Loc = CopyConstructor->getEndLoc().isValid() 15032 ? CopyConstructor->getEndLoc() 15033 : CopyConstructor->getLocation(); 15034 Sema::CompoundScopeRAII CompoundScope(*this); 15035 CopyConstructor->setBody( 15036 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 15037 CopyConstructor->markUsed(Context); 15038 } 15039 15040 if (ASTMutationListener *L = getASTMutationListener()) { 15041 L->CompletedImplicitDefinition(CopyConstructor); 15042 } 15043 } 15044 15045 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 15046 CXXRecordDecl *ClassDecl) { 15047 assert(ClassDecl->needsImplicitMoveConstructor()); 15048 15049 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 15050 if (DSM.isAlreadyBeingDeclared()) 15051 return nullptr; 15052 15053 QualType ClassType = Context.getTypeDeclType(ClassDecl); 15054 15055 QualType ArgType = ClassType; 15056 LangAS AS = getDefaultCXXMethodAddrSpace(); 15057 if (AS != LangAS::Default) 15058 ArgType = Context.getAddrSpaceQualType(ClassType, AS); 15059 ArgType = Context.getRValueReferenceType(ArgType); 15060 15061 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 15062 CXXMoveConstructor, 15063 false); 15064 15065 DeclarationName Name 15066 = Context.DeclarationNames.getCXXConstructorName( 15067 Context.getCanonicalType(ClassType)); 15068 SourceLocation ClassLoc = ClassDecl->getLocation(); 15069 DeclarationNameInfo NameInfo(Name, ClassLoc); 15070 15071 // C++11 [class.copy]p11: 15072 // An implicitly-declared copy/move constructor is an inline public 15073 // member of its class. 15074 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 15075 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 15076 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(), 15077 /*isInline=*/true, 15078 /*isImplicitlyDeclared=*/true, 15079 Constexpr ? ConstexprSpecKind::Constexpr 15080 : ConstexprSpecKind::Unspecified); 15081 MoveConstructor->setAccess(AS_public); 15082 MoveConstructor->setDefaulted(); 15083 15084 if (getLangOpts().CUDA) { 15085 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 15086 MoveConstructor, 15087 /* ConstRHS */ false, 15088 /* Diagnose */ false); 15089 } 15090 15091 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType); 15092 15093 // Add the parameter to the constructor. 15094 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 15095 ClassLoc, ClassLoc, 15096 /*IdentifierInfo=*/nullptr, 15097 ArgType, /*TInfo=*/nullptr, 15098 SC_None, nullptr); 15099 MoveConstructor->setParams(FromParam); 15100 15101 MoveConstructor->setTrivial( 15102 ClassDecl->needsOverloadResolutionForMoveConstructor() 15103 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 15104 : ClassDecl->hasTrivialMoveConstructor()); 15105 15106 MoveConstructor->setTrivialForCall( 15107 ClassDecl->hasAttr<TrivialABIAttr>() || 15108 (ClassDecl->needsOverloadResolutionForMoveConstructor() 15109 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor, 15110 TAH_ConsiderTrivialABI) 15111 : ClassDecl->hasTrivialMoveConstructorForCall())); 15112 15113 // Note that we have declared this constructor. 15114 ++getASTContext().NumImplicitMoveConstructorsDeclared; 15115 15116 Scope *S = getScopeForContext(ClassDecl); 15117 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor); 15118 15119 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 15120 ClassDecl->setImplicitMoveConstructorIsDeleted(); 15121 SetDeclDeleted(MoveConstructor, ClassLoc); 15122 } 15123 15124 if (S) 15125 PushOnScopeChains(MoveConstructor, S, false); 15126 ClassDecl->addDecl(MoveConstructor); 15127 15128 return MoveConstructor; 15129 } 15130 15131 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 15132 CXXConstructorDecl *MoveConstructor) { 15133 assert((MoveConstructor->isDefaulted() && 15134 MoveConstructor->isMoveConstructor() && 15135 !MoveConstructor->doesThisDeclarationHaveABody() && 15136 !MoveConstructor->isDeleted()) && 15137 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 15138 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl()) 15139 return; 15140 15141 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 15142 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 15143 15144 SynthesizedFunctionScope Scope(*this, MoveConstructor); 15145 15146 // The exception specification is needed because we are defining the 15147 // function. 15148 ResolveExceptionSpec(CurrentLocation, 15149 MoveConstructor->getType()->castAs<FunctionProtoType>()); 15150 MarkVTableUsed(CurrentLocation, ClassDecl); 15151 15152 // Add a context note for diagnostics produced after this point. 15153 Scope.addContextNote(CurrentLocation); 15154 15155 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) { 15156 MoveConstructor->setInvalidDecl(); 15157 } else { 15158 SourceLocation Loc = MoveConstructor->getEndLoc().isValid() 15159 ? MoveConstructor->getEndLoc() 15160 : MoveConstructor->getLocation(); 15161 Sema::CompoundScopeRAII CompoundScope(*this); 15162 MoveConstructor->setBody(ActOnCompoundStmt( 15163 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 15164 MoveConstructor->markUsed(Context); 15165 } 15166 15167 if (ASTMutationListener *L = getASTMutationListener()) { 15168 L->CompletedImplicitDefinition(MoveConstructor); 15169 } 15170 } 15171 15172 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 15173 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 15174 } 15175 15176 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 15177 SourceLocation CurrentLocation, 15178 CXXConversionDecl *Conv) { 15179 SynthesizedFunctionScope Scope(*this, Conv); 15180 assert(!Conv->getReturnType()->isUndeducedType()); 15181 15182 QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType(); 15183 CallingConv CC = 15184 ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv(); 15185 15186 CXXRecordDecl *Lambda = Conv->getParent(); 15187 FunctionDecl *CallOp = Lambda->getLambdaCallOperator(); 15188 FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(CC); 15189 15190 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) { 15191 CallOp = InstantiateFunctionDeclaration( 15192 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 15193 if (!CallOp) 15194 return; 15195 15196 Invoker = InstantiateFunctionDeclaration( 15197 Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 15198 if (!Invoker) 15199 return; 15200 } 15201 15202 if (CallOp->isInvalidDecl()) 15203 return; 15204 15205 // Mark the call operator referenced (and add to pending instantiations 15206 // if necessary). 15207 // For both the conversion and static-invoker template specializations 15208 // we construct their body's in this function, so no need to add them 15209 // to the PendingInstantiations. 15210 MarkFunctionReferenced(CurrentLocation, CallOp); 15211 15212 // Fill in the __invoke function with a dummy implementation. IR generation 15213 // will fill in the actual details. Update its type in case it contained 15214 // an 'auto'. 15215 Invoker->markUsed(Context); 15216 Invoker->setReferenced(); 15217 Invoker->setType(Conv->getReturnType()->getPointeeType()); 15218 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 15219 15220 // Construct the body of the conversion function { return __invoke; }. 15221 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 15222 VK_LValue, Conv->getLocation()); 15223 assert(FunctionRef && "Can't refer to __invoke function?"); 15224 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 15225 Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(), 15226 Conv->getLocation())); 15227 Conv->markUsed(Context); 15228 Conv->setReferenced(); 15229 15230 if (ASTMutationListener *L = getASTMutationListener()) { 15231 L->CompletedImplicitDefinition(Conv); 15232 L->CompletedImplicitDefinition(Invoker); 15233 } 15234 } 15235 15236 15237 15238 void Sema::DefineImplicitLambdaToBlockPointerConversion( 15239 SourceLocation CurrentLocation, 15240 CXXConversionDecl *Conv) 15241 { 15242 assert(!Conv->getParent()->isGenericLambda()); 15243 15244 SynthesizedFunctionScope Scope(*this, Conv); 15245 15246 // Copy-initialize the lambda object as needed to capture it. 15247 Expr *This = ActOnCXXThis(CurrentLocation).get(); 15248 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 15249 15250 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 15251 Conv->getLocation(), 15252 Conv, DerefThis); 15253 15254 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 15255 // behavior. Note that only the general conversion function does this 15256 // (since it's unusable otherwise); in the case where we inline the 15257 // block literal, it has block literal lifetime semantics. 15258 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 15259 BuildBlock = ImplicitCastExpr::Create( 15260 Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject, 15261 BuildBlock.get(), nullptr, VK_PRValue, FPOptionsOverride()); 15262 15263 if (BuildBlock.isInvalid()) { 15264 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 15265 Conv->setInvalidDecl(); 15266 return; 15267 } 15268 15269 // Create the return statement that returns the block from the conversion 15270 // function. 15271 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 15272 if (Return.isInvalid()) { 15273 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 15274 Conv->setInvalidDecl(); 15275 return; 15276 } 15277 15278 // Set the body of the conversion function. 15279 Stmt *ReturnS = Return.get(); 15280 Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(), 15281 Conv->getLocation())); 15282 Conv->markUsed(Context); 15283 15284 // We're done; notify the mutation listener, if any. 15285 if (ASTMutationListener *L = getASTMutationListener()) { 15286 L->CompletedImplicitDefinition(Conv); 15287 } 15288 } 15289 15290 /// Determine whether the given list arguments contains exactly one 15291 /// "real" (non-default) argument. 15292 static bool hasOneRealArgument(MultiExprArg Args) { 15293 switch (Args.size()) { 15294 case 0: 15295 return false; 15296 15297 default: 15298 if (!Args[1]->isDefaultArgument()) 15299 return false; 15300 15301 LLVM_FALLTHROUGH; 15302 case 1: 15303 return !Args[0]->isDefaultArgument(); 15304 } 15305 15306 return false; 15307 } 15308 15309 ExprResult 15310 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 15311 NamedDecl *FoundDecl, 15312 CXXConstructorDecl *Constructor, 15313 MultiExprArg ExprArgs, 15314 bool HadMultipleCandidates, 15315 bool IsListInitialization, 15316 bool IsStdInitListInitialization, 15317 bool RequiresZeroInit, 15318 unsigned ConstructKind, 15319 SourceRange ParenRange) { 15320 bool Elidable = false; 15321 15322 // C++0x [class.copy]p34: 15323 // When certain criteria are met, an implementation is allowed to 15324 // omit the copy/move construction of a class object, even if the 15325 // copy/move constructor and/or destructor for the object have 15326 // side effects. [...] 15327 // - when a temporary class object that has not been bound to a 15328 // reference (12.2) would be copied/moved to a class object 15329 // with the same cv-unqualified type, the copy/move operation 15330 // can be omitted by constructing the temporary object 15331 // directly into the target of the omitted copy/move 15332 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor && 15333 // FIXME: Converting constructors should also be accepted. 15334 // But to fix this, the logic that digs down into a CXXConstructExpr 15335 // to find the source object needs to handle it. 15336 // Right now it assumes the source object is passed directly as the 15337 // first argument. 15338 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 15339 Expr *SubExpr = ExprArgs[0]; 15340 // FIXME: Per above, this is also incorrect if we want to accept 15341 // converting constructors, as isTemporaryObject will 15342 // reject temporaries with different type from the 15343 // CXXRecord itself. 15344 Elidable = SubExpr->isTemporaryObject( 15345 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 15346 } 15347 15348 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, 15349 FoundDecl, Constructor, 15350 Elidable, ExprArgs, HadMultipleCandidates, 15351 IsListInitialization, 15352 IsStdInitListInitialization, RequiresZeroInit, 15353 ConstructKind, ParenRange); 15354 } 15355 15356 ExprResult 15357 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 15358 NamedDecl *FoundDecl, 15359 CXXConstructorDecl *Constructor, 15360 bool Elidable, 15361 MultiExprArg ExprArgs, 15362 bool HadMultipleCandidates, 15363 bool IsListInitialization, 15364 bool IsStdInitListInitialization, 15365 bool RequiresZeroInit, 15366 unsigned ConstructKind, 15367 SourceRange ParenRange) { 15368 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) { 15369 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow); 15370 if (DiagnoseUseOfDecl(Constructor, ConstructLoc)) 15371 return ExprError(); 15372 } 15373 15374 return BuildCXXConstructExpr( 15375 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs, 15376 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 15377 RequiresZeroInit, ConstructKind, ParenRange); 15378 } 15379 15380 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 15381 /// including handling of its default argument expressions. 15382 ExprResult 15383 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 15384 CXXConstructorDecl *Constructor, 15385 bool Elidable, 15386 MultiExprArg ExprArgs, 15387 bool HadMultipleCandidates, 15388 bool IsListInitialization, 15389 bool IsStdInitListInitialization, 15390 bool RequiresZeroInit, 15391 unsigned ConstructKind, 15392 SourceRange ParenRange) { 15393 assert(declaresSameEntity( 15394 Constructor->getParent(), 15395 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && 15396 "given constructor for wrong type"); 15397 MarkFunctionReferenced(ConstructLoc, Constructor); 15398 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor)) 15399 return ExprError(); 15400 if (getLangOpts().SYCLIsDevice && 15401 !checkSYCLDeviceFunction(ConstructLoc, Constructor)) 15402 return ExprError(); 15403 15404 return CheckForImmediateInvocation( 15405 CXXConstructExpr::Create( 15406 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs, 15407 HadMultipleCandidates, IsListInitialization, 15408 IsStdInitListInitialization, RequiresZeroInit, 15409 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 15410 ParenRange), 15411 Constructor); 15412 } 15413 15414 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 15415 assert(Field->hasInClassInitializer()); 15416 15417 // If we already have the in-class initializer nothing needs to be done. 15418 if (Field->getInClassInitializer()) 15419 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext); 15420 15421 // If we might have already tried and failed to instantiate, don't try again. 15422 if (Field->isInvalidDecl()) 15423 return ExprError(); 15424 15425 // Maybe we haven't instantiated the in-class initializer. Go check the 15426 // pattern FieldDecl to see if it has one. 15427 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 15428 15429 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 15430 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 15431 DeclContext::lookup_result Lookup = 15432 ClassPattern->lookup(Field->getDeclName()); 15433 15434 FieldDecl *Pattern = nullptr; 15435 for (auto L : Lookup) { 15436 if (isa<FieldDecl>(L)) { 15437 Pattern = cast<FieldDecl>(L); 15438 break; 15439 } 15440 } 15441 assert(Pattern && "We must have set the Pattern!"); 15442 15443 if (!Pattern->hasInClassInitializer() || 15444 InstantiateInClassInitializer(Loc, Field, Pattern, 15445 getTemplateInstantiationArgs(Field))) { 15446 // Don't diagnose this again. 15447 Field->setInvalidDecl(); 15448 return ExprError(); 15449 } 15450 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext); 15451 } 15452 15453 // DR1351: 15454 // If the brace-or-equal-initializer of a non-static data member 15455 // invokes a defaulted default constructor of its class or of an 15456 // enclosing class in a potentially evaluated subexpression, the 15457 // program is ill-formed. 15458 // 15459 // This resolution is unworkable: the exception specification of the 15460 // default constructor can be needed in an unevaluated context, in 15461 // particular, in the operand of a noexcept-expression, and we can be 15462 // unable to compute an exception specification for an enclosed class. 15463 // 15464 // Any attempt to resolve the exception specification of a defaulted default 15465 // constructor before the initializer is lexically complete will ultimately 15466 // come here at which point we can diagnose it. 15467 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 15468 Diag(Loc, diag::err_default_member_initializer_not_yet_parsed) 15469 << OutermostClass << Field; 15470 Diag(Field->getEndLoc(), 15471 diag::note_default_member_initializer_not_yet_parsed); 15472 // Recover by marking the field invalid, unless we're in a SFINAE context. 15473 if (!isSFINAEContext()) 15474 Field->setInvalidDecl(); 15475 return ExprError(); 15476 } 15477 15478 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 15479 if (VD->isInvalidDecl()) return; 15480 // If initializing the variable failed, don't also diagnose problems with 15481 // the destructor, they're likely related. 15482 if (VD->getInit() && VD->getInit()->containsErrors()) 15483 return; 15484 15485 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 15486 if (ClassDecl->isInvalidDecl()) return; 15487 if (ClassDecl->hasIrrelevantDestructor()) return; 15488 if (ClassDecl->isDependentContext()) return; 15489 15490 if (VD->isNoDestroy(getASTContext())) 15491 return; 15492 15493 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 15494 15495 // If this is an array, we'll require the destructor during initialization, so 15496 // we can skip over this. We still want to emit exit-time destructor warnings 15497 // though. 15498 if (!VD->getType()->isArrayType()) { 15499 MarkFunctionReferenced(VD->getLocation(), Destructor); 15500 CheckDestructorAccess(VD->getLocation(), Destructor, 15501 PDiag(diag::err_access_dtor_var) 15502 << VD->getDeclName() << VD->getType()); 15503 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 15504 } 15505 15506 if (Destructor->isTrivial()) return; 15507 15508 // If the destructor is constexpr, check whether the variable has constant 15509 // destruction now. 15510 if (Destructor->isConstexpr()) { 15511 bool HasConstantInit = false; 15512 if (VD->getInit() && !VD->getInit()->isValueDependent()) 15513 HasConstantInit = VD->evaluateValue(); 15514 SmallVector<PartialDiagnosticAt, 8> Notes; 15515 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() && 15516 HasConstantInit) { 15517 Diag(VD->getLocation(), 15518 diag::err_constexpr_var_requires_const_destruction) << VD; 15519 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 15520 Diag(Notes[I].first, Notes[I].second); 15521 } 15522 } 15523 15524 if (!VD->hasGlobalStorage()) return; 15525 15526 // Emit warning for non-trivial dtor in global scope (a real global, 15527 // class-static, function-static). 15528 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 15529 15530 // TODO: this should be re-enabled for static locals by !CXAAtExit 15531 if (!VD->isStaticLocal()) 15532 Diag(VD->getLocation(), diag::warn_global_destructor); 15533 } 15534 15535 /// Given a constructor and the set of arguments provided for the 15536 /// constructor, convert the arguments and add any required default arguments 15537 /// to form a proper call to this constructor. 15538 /// 15539 /// \returns true if an error occurred, false otherwise. 15540 bool Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 15541 QualType DeclInitType, MultiExprArg ArgsPtr, 15542 SourceLocation Loc, 15543 SmallVectorImpl<Expr *> &ConvertedArgs, 15544 bool AllowExplicit, 15545 bool IsListInitialization) { 15546 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 15547 unsigned NumArgs = ArgsPtr.size(); 15548 Expr **Args = ArgsPtr.data(); 15549 15550 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>(); 15551 unsigned NumParams = Proto->getNumParams(); 15552 15553 // If too few arguments are available, we'll fill in the rest with defaults. 15554 if (NumArgs < NumParams) 15555 ConvertedArgs.reserve(NumParams); 15556 else 15557 ConvertedArgs.reserve(NumArgs); 15558 15559 VariadicCallType CallType = 15560 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 15561 SmallVector<Expr *, 8> AllArgs; 15562 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 15563 Proto, 0, 15564 llvm::makeArrayRef(Args, NumArgs), 15565 AllArgs, 15566 CallType, AllowExplicit, 15567 IsListInitialization); 15568 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 15569 15570 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 15571 15572 CheckConstructorCall(Constructor, DeclInitType, 15573 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 15574 Proto, Loc); 15575 15576 return Invalid; 15577 } 15578 15579 static inline bool 15580 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 15581 const FunctionDecl *FnDecl) { 15582 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 15583 if (isa<NamespaceDecl>(DC)) { 15584 return SemaRef.Diag(FnDecl->getLocation(), 15585 diag::err_operator_new_delete_declared_in_namespace) 15586 << FnDecl->getDeclName(); 15587 } 15588 15589 if (isa<TranslationUnitDecl>(DC) && 15590 FnDecl->getStorageClass() == SC_Static) { 15591 return SemaRef.Diag(FnDecl->getLocation(), 15592 diag::err_operator_new_delete_declared_static) 15593 << FnDecl->getDeclName(); 15594 } 15595 15596 return false; 15597 } 15598 15599 static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef, 15600 const PointerType *PtrTy) { 15601 auto &Ctx = SemaRef.Context; 15602 Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers(); 15603 PtrQuals.removeAddressSpace(); 15604 return Ctx.getPointerType(Ctx.getCanonicalType(Ctx.getQualifiedType( 15605 PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals))); 15606 } 15607 15608 static inline bool 15609 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 15610 CanQualType ExpectedResultType, 15611 CanQualType ExpectedFirstParamType, 15612 unsigned DependentParamTypeDiag, 15613 unsigned InvalidParamTypeDiag) { 15614 QualType ResultType = 15615 FnDecl->getType()->castAs<FunctionType>()->getReturnType(); 15616 15617 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 15618 // The operator is valid on any address space for OpenCL. 15619 // Drop address space from actual and expected result types. 15620 if (const auto *PtrTy = ResultType->getAs<PointerType>()) 15621 ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 15622 15623 if (auto ExpectedPtrTy = ExpectedResultType->getAs<PointerType>()) 15624 ExpectedResultType = RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy); 15625 } 15626 15627 // Check that the result type is what we expect. 15628 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) { 15629 // Reject even if the type is dependent; an operator delete function is 15630 // required to have a non-dependent result type. 15631 return SemaRef.Diag( 15632 FnDecl->getLocation(), 15633 ResultType->isDependentType() 15634 ? diag::err_operator_new_delete_dependent_result_type 15635 : diag::err_operator_new_delete_invalid_result_type) 15636 << FnDecl->getDeclName() << ExpectedResultType; 15637 } 15638 15639 // A function template must have at least 2 parameters. 15640 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 15641 return SemaRef.Diag(FnDecl->getLocation(), 15642 diag::err_operator_new_delete_template_too_few_parameters) 15643 << FnDecl->getDeclName(); 15644 15645 // The function decl must have at least 1 parameter. 15646 if (FnDecl->getNumParams() == 0) 15647 return SemaRef.Diag(FnDecl->getLocation(), 15648 diag::err_operator_new_delete_too_few_parameters) 15649 << FnDecl->getDeclName(); 15650 15651 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 15652 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 15653 // The operator is valid on any address space for OpenCL. 15654 // Drop address space from actual and expected first parameter types. 15655 if (const auto *PtrTy = 15656 FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) 15657 FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 15658 15659 if (auto ExpectedPtrTy = ExpectedFirstParamType->getAs<PointerType>()) 15660 ExpectedFirstParamType = 15661 RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy); 15662 } 15663 15664 // Check that the first parameter type is what we expect. 15665 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 15666 ExpectedFirstParamType) { 15667 // The first parameter type is not allowed to be dependent. As a tentative 15668 // DR resolution, we allow a dependent parameter type if it is the right 15669 // type anyway, to allow destroying operator delete in class templates. 15670 return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType() 15671 ? DependentParamTypeDiag 15672 : InvalidParamTypeDiag) 15673 << FnDecl->getDeclName() << ExpectedFirstParamType; 15674 } 15675 15676 return false; 15677 } 15678 15679 static bool 15680 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 15681 // C++ [basic.stc.dynamic.allocation]p1: 15682 // A program is ill-formed if an allocation function is declared in a 15683 // namespace scope other than global scope or declared static in global 15684 // scope. 15685 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 15686 return true; 15687 15688 CanQualType SizeTy = 15689 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 15690 15691 // C++ [basic.stc.dynamic.allocation]p1: 15692 // The return type shall be void*. The first parameter shall have type 15693 // std::size_t. 15694 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 15695 SizeTy, 15696 diag::err_operator_new_dependent_param_type, 15697 diag::err_operator_new_param_type)) 15698 return true; 15699 15700 // C++ [basic.stc.dynamic.allocation]p1: 15701 // The first parameter shall not have an associated default argument. 15702 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 15703 return SemaRef.Diag(FnDecl->getLocation(), 15704 diag::err_operator_new_default_arg) 15705 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 15706 15707 return false; 15708 } 15709 15710 static bool 15711 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 15712 // C++ [basic.stc.dynamic.deallocation]p1: 15713 // A program is ill-formed if deallocation functions are declared in a 15714 // namespace scope other than global scope or declared static in global 15715 // scope. 15716 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 15717 return true; 15718 15719 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl); 15720 15721 // C++ P0722: 15722 // Within a class C, the first parameter of a destroying operator delete 15723 // shall be of type C *. The first parameter of any other deallocation 15724 // function shall be of type void *. 15725 CanQualType ExpectedFirstParamType = 15726 MD && MD->isDestroyingOperatorDelete() 15727 ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType( 15728 SemaRef.Context.getRecordType(MD->getParent()))) 15729 : SemaRef.Context.VoidPtrTy; 15730 15731 // C++ [basic.stc.dynamic.deallocation]p2: 15732 // Each deallocation function shall return void 15733 if (CheckOperatorNewDeleteTypes( 15734 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType, 15735 diag::err_operator_delete_dependent_param_type, 15736 diag::err_operator_delete_param_type)) 15737 return true; 15738 15739 // C++ P0722: 15740 // A destroying operator delete shall be a usual deallocation function. 15741 if (MD && !MD->getParent()->isDependentContext() && 15742 MD->isDestroyingOperatorDelete() && 15743 !SemaRef.isUsualDeallocationFunction(MD)) { 15744 SemaRef.Diag(MD->getLocation(), 15745 diag::err_destroying_operator_delete_not_usual); 15746 return true; 15747 } 15748 15749 return false; 15750 } 15751 15752 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 15753 /// of this overloaded operator is well-formed. If so, returns false; 15754 /// otherwise, emits appropriate diagnostics and returns true. 15755 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 15756 assert(FnDecl && FnDecl->isOverloadedOperator() && 15757 "Expected an overloaded operator declaration"); 15758 15759 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 15760 15761 // C++ [over.oper]p5: 15762 // The allocation and deallocation functions, operator new, 15763 // operator new[], operator delete and operator delete[], are 15764 // described completely in 3.7.3. The attributes and restrictions 15765 // found in the rest of this subclause do not apply to them unless 15766 // explicitly stated in 3.7.3. 15767 if (Op == OO_Delete || Op == OO_Array_Delete) 15768 return CheckOperatorDeleteDeclaration(*this, FnDecl); 15769 15770 if (Op == OO_New || Op == OO_Array_New) 15771 return CheckOperatorNewDeclaration(*this, FnDecl); 15772 15773 // C++ [over.oper]p6: 15774 // An operator function shall either be a non-static member 15775 // function or be a non-member function and have at least one 15776 // parameter whose type is a class, a reference to a class, an 15777 // enumeration, or a reference to an enumeration. 15778 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 15779 if (MethodDecl->isStatic()) 15780 return Diag(FnDecl->getLocation(), 15781 diag::err_operator_overload_static) << FnDecl->getDeclName(); 15782 } else { 15783 bool ClassOrEnumParam = false; 15784 for (auto Param : FnDecl->parameters()) { 15785 QualType ParamType = Param->getType().getNonReferenceType(); 15786 if (ParamType->isDependentType() || ParamType->isRecordType() || 15787 ParamType->isEnumeralType()) { 15788 ClassOrEnumParam = true; 15789 break; 15790 } 15791 } 15792 15793 if (!ClassOrEnumParam) 15794 return Diag(FnDecl->getLocation(), 15795 diag::err_operator_overload_needs_class_or_enum) 15796 << FnDecl->getDeclName(); 15797 } 15798 15799 // C++ [over.oper]p8: 15800 // An operator function cannot have default arguments (8.3.6), 15801 // except where explicitly stated below. 15802 // 15803 // Only the function-call operator allows default arguments 15804 // (C++ [over.call]p1). 15805 if (Op != OO_Call) { 15806 for (auto Param : FnDecl->parameters()) { 15807 if (Param->hasDefaultArg()) 15808 return Diag(Param->getLocation(), 15809 diag::err_operator_overload_default_arg) 15810 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 15811 } 15812 } 15813 15814 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 15815 { false, false, false } 15816 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 15817 , { Unary, Binary, MemberOnly } 15818 #include "clang/Basic/OperatorKinds.def" 15819 }; 15820 15821 bool CanBeUnaryOperator = OperatorUses[Op][0]; 15822 bool CanBeBinaryOperator = OperatorUses[Op][1]; 15823 bool MustBeMemberOperator = OperatorUses[Op][2]; 15824 15825 // C++ [over.oper]p8: 15826 // [...] Operator functions cannot have more or fewer parameters 15827 // than the number required for the corresponding operator, as 15828 // described in the rest of this subclause. 15829 unsigned NumParams = FnDecl->getNumParams() 15830 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 15831 if (Op != OO_Call && 15832 ((NumParams == 1 && !CanBeUnaryOperator) || 15833 (NumParams == 2 && !CanBeBinaryOperator) || 15834 (NumParams < 1) || (NumParams > 2))) { 15835 // We have the wrong number of parameters. 15836 unsigned ErrorKind; 15837 if (CanBeUnaryOperator && CanBeBinaryOperator) { 15838 ErrorKind = 2; // 2 -> unary or binary. 15839 } else if (CanBeUnaryOperator) { 15840 ErrorKind = 0; // 0 -> unary 15841 } else { 15842 assert(CanBeBinaryOperator && 15843 "All non-call overloaded operators are unary or binary!"); 15844 ErrorKind = 1; // 1 -> binary 15845 } 15846 15847 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 15848 << FnDecl->getDeclName() << NumParams << ErrorKind; 15849 } 15850 15851 // Overloaded operators other than operator() cannot be variadic. 15852 if (Op != OO_Call && 15853 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) { 15854 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 15855 << FnDecl->getDeclName(); 15856 } 15857 15858 // Some operators must be non-static member functions. 15859 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 15860 return Diag(FnDecl->getLocation(), 15861 diag::err_operator_overload_must_be_member) 15862 << FnDecl->getDeclName(); 15863 } 15864 15865 // C++ [over.inc]p1: 15866 // The user-defined function called operator++ implements the 15867 // prefix and postfix ++ operator. If this function is a member 15868 // function with no parameters, or a non-member function with one 15869 // parameter of class or enumeration type, it defines the prefix 15870 // increment operator ++ for objects of that type. If the function 15871 // is a member function with one parameter (which shall be of type 15872 // int) or a non-member function with two parameters (the second 15873 // of which shall be of type int), it defines the postfix 15874 // increment operator ++ for objects of that type. 15875 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 15876 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 15877 QualType ParamType = LastParam->getType(); 15878 15879 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 15880 !ParamType->isDependentType()) 15881 return Diag(LastParam->getLocation(), 15882 diag::err_operator_overload_post_incdec_must_be_int) 15883 << LastParam->getType() << (Op == OO_MinusMinus); 15884 } 15885 15886 return false; 15887 } 15888 15889 static bool 15890 checkLiteralOperatorTemplateParameterList(Sema &SemaRef, 15891 FunctionTemplateDecl *TpDecl) { 15892 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters(); 15893 15894 // Must have one or two template parameters. 15895 if (TemplateParams->size() == 1) { 15896 NonTypeTemplateParmDecl *PmDecl = 15897 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0)); 15898 15899 // The template parameter must be a char parameter pack. 15900 if (PmDecl && PmDecl->isTemplateParameterPack() && 15901 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy)) 15902 return false; 15903 15904 // C++20 [over.literal]p5: 15905 // A string literal operator template is a literal operator template 15906 // whose template-parameter-list comprises a single non-type 15907 // template-parameter of class type. 15908 // 15909 // As a DR resolution, we also allow placeholders for deduced class 15910 // template specializations. 15911 if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl && 15912 !PmDecl->isTemplateParameterPack() && 15913 (PmDecl->getType()->isRecordType() || 15914 PmDecl->getType()->getAs<DeducedTemplateSpecializationType>())) 15915 return false; 15916 } else if (TemplateParams->size() == 2) { 15917 TemplateTypeParmDecl *PmType = 15918 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0)); 15919 NonTypeTemplateParmDecl *PmArgs = 15920 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1)); 15921 15922 // The second template parameter must be a parameter pack with the 15923 // first template parameter as its type. 15924 if (PmType && PmArgs && !PmType->isTemplateParameterPack() && 15925 PmArgs->isTemplateParameterPack()) { 15926 const TemplateTypeParmType *TArgs = 15927 PmArgs->getType()->getAs<TemplateTypeParmType>(); 15928 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 15929 TArgs->getIndex() == PmType->getIndex()) { 15930 if (!SemaRef.inTemplateInstantiation()) 15931 SemaRef.Diag(TpDecl->getLocation(), 15932 diag::ext_string_literal_operator_template); 15933 return false; 15934 } 15935 } 15936 } 15937 15938 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(), 15939 diag::err_literal_operator_template) 15940 << TpDecl->getTemplateParameters()->getSourceRange(); 15941 return true; 15942 } 15943 15944 /// CheckLiteralOperatorDeclaration - Check whether the declaration 15945 /// of this literal operator function is well-formed. If so, returns 15946 /// false; otherwise, emits appropriate diagnostics and returns true. 15947 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 15948 if (isa<CXXMethodDecl>(FnDecl)) { 15949 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 15950 << FnDecl->getDeclName(); 15951 return true; 15952 } 15953 15954 if (FnDecl->isExternC()) { 15955 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 15956 if (const LinkageSpecDecl *LSD = 15957 FnDecl->getDeclContext()->getExternCContext()) 15958 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here); 15959 return true; 15960 } 15961 15962 // This might be the definition of a literal operator template. 15963 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 15964 15965 // This might be a specialization of a literal operator template. 15966 if (!TpDecl) 15967 TpDecl = FnDecl->getPrimaryTemplate(); 15968 15969 // template <char...> type operator "" name() and 15970 // template <class T, T...> type operator "" name() are the only valid 15971 // template signatures, and the only valid signatures with no parameters. 15972 // 15973 // C++20 also allows template <SomeClass T> type operator "" name(). 15974 if (TpDecl) { 15975 if (FnDecl->param_size() != 0) { 15976 Diag(FnDecl->getLocation(), 15977 diag::err_literal_operator_template_with_params); 15978 return true; 15979 } 15980 15981 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl)) 15982 return true; 15983 15984 } else if (FnDecl->param_size() == 1) { 15985 const ParmVarDecl *Param = FnDecl->getParamDecl(0); 15986 15987 QualType ParamType = Param->getType().getUnqualifiedType(); 15988 15989 // Only unsigned long long int, long double, any character type, and const 15990 // char * are allowed as the only parameters. 15991 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) || 15992 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) || 15993 Context.hasSameType(ParamType, Context.CharTy) || 15994 Context.hasSameType(ParamType, Context.WideCharTy) || 15995 Context.hasSameType(ParamType, Context.Char8Ty) || 15996 Context.hasSameType(ParamType, Context.Char16Ty) || 15997 Context.hasSameType(ParamType, Context.Char32Ty)) { 15998 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) { 15999 QualType InnerType = Ptr->getPointeeType(); 16000 16001 // Pointer parameter must be a const char *. 16002 if (!(Context.hasSameType(InnerType.getUnqualifiedType(), 16003 Context.CharTy) && 16004 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) { 16005 Diag(Param->getSourceRange().getBegin(), 16006 diag::err_literal_operator_param) 16007 << ParamType << "'const char *'" << Param->getSourceRange(); 16008 return true; 16009 } 16010 16011 } else if (ParamType->isRealFloatingType()) { 16012 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 16013 << ParamType << Context.LongDoubleTy << Param->getSourceRange(); 16014 return true; 16015 16016 } else if (ParamType->isIntegerType()) { 16017 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 16018 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange(); 16019 return true; 16020 16021 } else { 16022 Diag(Param->getSourceRange().getBegin(), 16023 diag::err_literal_operator_invalid_param) 16024 << ParamType << Param->getSourceRange(); 16025 return true; 16026 } 16027 16028 } else if (FnDecl->param_size() == 2) { 16029 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 16030 16031 // First, verify that the first parameter is correct. 16032 16033 QualType FirstParamType = (*Param)->getType().getUnqualifiedType(); 16034 16035 // Two parameter function must have a pointer to const as a 16036 // first parameter; let's strip those qualifiers. 16037 const PointerType *PT = FirstParamType->getAs<PointerType>(); 16038 16039 if (!PT) { 16040 Diag((*Param)->getSourceRange().getBegin(), 16041 diag::err_literal_operator_param) 16042 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 16043 return true; 16044 } 16045 16046 QualType PointeeType = PT->getPointeeType(); 16047 // First parameter must be const 16048 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) { 16049 Diag((*Param)->getSourceRange().getBegin(), 16050 diag::err_literal_operator_param) 16051 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 16052 return true; 16053 } 16054 16055 QualType InnerType = PointeeType.getUnqualifiedType(); 16056 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and 16057 // const char32_t* are allowed as the first parameter to a two-parameter 16058 // function 16059 if (!(Context.hasSameType(InnerType, Context.CharTy) || 16060 Context.hasSameType(InnerType, Context.WideCharTy) || 16061 Context.hasSameType(InnerType, Context.Char8Ty) || 16062 Context.hasSameType(InnerType, Context.Char16Ty) || 16063 Context.hasSameType(InnerType, Context.Char32Ty))) { 16064 Diag((*Param)->getSourceRange().getBegin(), 16065 diag::err_literal_operator_param) 16066 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 16067 return true; 16068 } 16069 16070 // Move on to the second and final parameter. 16071 ++Param; 16072 16073 // The second parameter must be a std::size_t. 16074 QualType SecondParamType = (*Param)->getType().getUnqualifiedType(); 16075 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) { 16076 Diag((*Param)->getSourceRange().getBegin(), 16077 diag::err_literal_operator_param) 16078 << SecondParamType << Context.getSizeType() 16079 << (*Param)->getSourceRange(); 16080 return true; 16081 } 16082 } else { 16083 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count); 16084 return true; 16085 } 16086 16087 // Parameters are good. 16088 16089 // A parameter-declaration-clause containing a default argument is not 16090 // equivalent to any of the permitted forms. 16091 for (auto Param : FnDecl->parameters()) { 16092 if (Param->hasDefaultArg()) { 16093 Diag(Param->getDefaultArgRange().getBegin(), 16094 diag::err_literal_operator_default_argument) 16095 << Param->getDefaultArgRange(); 16096 break; 16097 } 16098 } 16099 16100 StringRef LiteralName 16101 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 16102 if (LiteralName[0] != '_' && 16103 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) { 16104 // C++11 [usrlit.suffix]p1: 16105 // Literal suffix identifiers that do not start with an underscore 16106 // are reserved for future standardization. 16107 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 16108 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 16109 } 16110 16111 return false; 16112 } 16113 16114 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 16115 /// linkage specification, including the language and (if present) 16116 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 16117 /// language string literal. LBraceLoc, if valid, provides the location of 16118 /// the '{' brace. Otherwise, this linkage specification does not 16119 /// have any braces. 16120 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 16121 Expr *LangStr, 16122 SourceLocation LBraceLoc) { 16123 StringLiteral *Lit = cast<StringLiteral>(LangStr); 16124 if (!Lit->isAscii()) { 16125 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 16126 << LangStr->getSourceRange(); 16127 return nullptr; 16128 } 16129 16130 StringRef Lang = Lit->getString(); 16131 LinkageSpecDecl::LanguageIDs Language; 16132 if (Lang == "C") 16133 Language = LinkageSpecDecl::lang_c; 16134 else if (Lang == "C++") 16135 Language = LinkageSpecDecl::lang_cxx; 16136 else { 16137 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 16138 << LangStr->getSourceRange(); 16139 return nullptr; 16140 } 16141 16142 // FIXME: Add all the various semantics of linkage specifications 16143 16144 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 16145 LangStr->getExprLoc(), Language, 16146 LBraceLoc.isValid()); 16147 CurContext->addDecl(D); 16148 PushDeclContext(S, D); 16149 return D; 16150 } 16151 16152 /// ActOnFinishLinkageSpecification - Complete the definition of 16153 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 16154 /// valid, it's the position of the closing '}' brace in a linkage 16155 /// specification that uses braces. 16156 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 16157 Decl *LinkageSpec, 16158 SourceLocation RBraceLoc) { 16159 if (RBraceLoc.isValid()) { 16160 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 16161 LSDecl->setRBraceLoc(RBraceLoc); 16162 } 16163 PopDeclContext(); 16164 return LinkageSpec; 16165 } 16166 16167 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 16168 const ParsedAttributesView &AttrList, 16169 SourceLocation SemiLoc) { 16170 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 16171 // Attribute declarations appertain to empty declaration so we handle 16172 // them here. 16173 ProcessDeclAttributeList(S, ED, AttrList); 16174 16175 CurContext->addDecl(ED); 16176 return ED; 16177 } 16178 16179 /// Perform semantic analysis for the variable declaration that 16180 /// occurs within a C++ catch clause, returning the newly-created 16181 /// variable. 16182 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 16183 TypeSourceInfo *TInfo, 16184 SourceLocation StartLoc, 16185 SourceLocation Loc, 16186 IdentifierInfo *Name) { 16187 bool Invalid = false; 16188 QualType ExDeclType = TInfo->getType(); 16189 16190 // Arrays and functions decay. 16191 if (ExDeclType->isArrayType()) 16192 ExDeclType = Context.getArrayDecayedType(ExDeclType); 16193 else if (ExDeclType->isFunctionType()) 16194 ExDeclType = Context.getPointerType(ExDeclType); 16195 16196 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 16197 // The exception-declaration shall not denote a pointer or reference to an 16198 // incomplete type, other than [cv] void*. 16199 // N2844 forbids rvalue references. 16200 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 16201 Diag(Loc, diag::err_catch_rvalue_ref); 16202 Invalid = true; 16203 } 16204 16205 if (ExDeclType->isVariablyModifiedType()) { 16206 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType; 16207 Invalid = true; 16208 } 16209 16210 QualType BaseType = ExDeclType; 16211 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 16212 unsigned DK = diag::err_catch_incomplete; 16213 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 16214 BaseType = Ptr->getPointeeType(); 16215 Mode = 1; 16216 DK = diag::err_catch_incomplete_ptr; 16217 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 16218 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 16219 BaseType = Ref->getPointeeType(); 16220 Mode = 2; 16221 DK = diag::err_catch_incomplete_ref; 16222 } 16223 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 16224 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 16225 Invalid = true; 16226 16227 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) { 16228 Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType; 16229 Invalid = true; 16230 } 16231 16232 if (!Invalid && !ExDeclType->isDependentType() && 16233 RequireNonAbstractType(Loc, ExDeclType, 16234 diag::err_abstract_type_in_decl, 16235 AbstractVariableType)) 16236 Invalid = true; 16237 16238 // Only the non-fragile NeXT runtime currently supports C++ catches 16239 // of ObjC types, and no runtime supports catching ObjC types by value. 16240 if (!Invalid && getLangOpts().ObjC) { 16241 QualType T = ExDeclType; 16242 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 16243 T = RT->getPointeeType(); 16244 16245 if (T->isObjCObjectType()) { 16246 Diag(Loc, diag::err_objc_object_catch); 16247 Invalid = true; 16248 } else if (T->isObjCObjectPointerType()) { 16249 // FIXME: should this be a test for macosx-fragile specifically? 16250 if (getLangOpts().ObjCRuntime.isFragile()) 16251 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 16252 } 16253 } 16254 16255 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 16256 ExDeclType, TInfo, SC_None); 16257 ExDecl->setExceptionVariable(true); 16258 16259 // In ARC, infer 'retaining' for variables of retainable type. 16260 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 16261 Invalid = true; 16262 16263 if (!Invalid && !ExDeclType->isDependentType()) { 16264 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 16265 // Insulate this from anything else we might currently be parsing. 16266 EnterExpressionEvaluationContext scope( 16267 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 16268 16269 // C++ [except.handle]p16: 16270 // The object declared in an exception-declaration or, if the 16271 // exception-declaration does not specify a name, a temporary (12.2) is 16272 // copy-initialized (8.5) from the exception object. [...] 16273 // The object is destroyed when the handler exits, after the destruction 16274 // of any automatic objects initialized within the handler. 16275 // 16276 // We just pretend to initialize the object with itself, then make sure 16277 // it can be destroyed later. 16278 QualType initType = Context.getExceptionObjectType(ExDeclType); 16279 16280 InitializedEntity entity = 16281 InitializedEntity::InitializeVariable(ExDecl); 16282 InitializationKind initKind = 16283 InitializationKind::CreateCopy(Loc, SourceLocation()); 16284 16285 Expr *opaqueValue = 16286 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 16287 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 16288 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 16289 if (result.isInvalid()) 16290 Invalid = true; 16291 else { 16292 // If the constructor used was non-trivial, set this as the 16293 // "initializer". 16294 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 16295 if (!construct->getConstructor()->isTrivial()) { 16296 Expr *init = MaybeCreateExprWithCleanups(construct); 16297 ExDecl->setInit(init); 16298 } 16299 16300 // And make sure it's destructable. 16301 FinalizeVarWithDestructor(ExDecl, recordType); 16302 } 16303 } 16304 } 16305 16306 if (Invalid) 16307 ExDecl->setInvalidDecl(); 16308 16309 return ExDecl; 16310 } 16311 16312 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 16313 /// handler. 16314 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 16315 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16316 bool Invalid = D.isInvalidType(); 16317 16318 // Check for unexpanded parameter packs. 16319 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 16320 UPPC_ExceptionType)) { 16321 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 16322 D.getIdentifierLoc()); 16323 Invalid = true; 16324 } 16325 16326 IdentifierInfo *II = D.getIdentifier(); 16327 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 16328 LookupOrdinaryName, 16329 ForVisibleRedeclaration)) { 16330 // The scope should be freshly made just for us. There is just no way 16331 // it contains any previous declaration, except for function parameters in 16332 // a function-try-block's catch statement. 16333 assert(!S->isDeclScope(PrevDecl)); 16334 if (isDeclInScope(PrevDecl, CurContext, S)) { 16335 Diag(D.getIdentifierLoc(), diag::err_redefinition) 16336 << D.getIdentifier(); 16337 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 16338 Invalid = true; 16339 } else if (PrevDecl->isTemplateParameter()) 16340 // Maybe we will complain about the shadowed template parameter. 16341 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 16342 } 16343 16344 if (D.getCXXScopeSpec().isSet() && !Invalid) { 16345 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 16346 << D.getCXXScopeSpec().getRange(); 16347 Invalid = true; 16348 } 16349 16350 VarDecl *ExDecl = BuildExceptionDeclaration( 16351 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier()); 16352 if (Invalid) 16353 ExDecl->setInvalidDecl(); 16354 16355 // Add the exception declaration into this scope. 16356 if (II) 16357 PushOnScopeChains(ExDecl, S); 16358 else 16359 CurContext->addDecl(ExDecl); 16360 16361 ProcessDeclAttributes(S, ExDecl, D); 16362 return ExDecl; 16363 } 16364 16365 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 16366 Expr *AssertExpr, 16367 Expr *AssertMessageExpr, 16368 SourceLocation RParenLoc) { 16369 StringLiteral *AssertMessage = 16370 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 16371 16372 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 16373 return nullptr; 16374 16375 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 16376 AssertMessage, RParenLoc, false); 16377 } 16378 16379 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 16380 Expr *AssertExpr, 16381 StringLiteral *AssertMessage, 16382 SourceLocation RParenLoc, 16383 bool Failed) { 16384 assert(AssertExpr != nullptr && "Expected non-null condition"); 16385 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 16386 !Failed) { 16387 // In a static_assert-declaration, the constant-expression shall be a 16388 // constant expression that can be contextually converted to bool. 16389 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 16390 if (Converted.isInvalid()) 16391 Failed = true; 16392 16393 ExprResult FullAssertExpr = 16394 ActOnFinishFullExpr(Converted.get(), StaticAssertLoc, 16395 /*DiscardedValue*/ false, 16396 /*IsConstexpr*/ true); 16397 if (FullAssertExpr.isInvalid()) 16398 Failed = true; 16399 else 16400 AssertExpr = FullAssertExpr.get(); 16401 16402 llvm::APSInt Cond; 16403 if (!Failed && VerifyIntegerConstantExpression( 16404 AssertExpr, &Cond, 16405 diag::err_static_assert_expression_is_not_constant) 16406 .isInvalid()) 16407 Failed = true; 16408 16409 if (!Failed && !Cond) { 16410 SmallString<256> MsgBuffer; 16411 llvm::raw_svector_ostream Msg(MsgBuffer); 16412 if (AssertMessage) 16413 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 16414 16415 Expr *InnerCond = nullptr; 16416 std::string InnerCondDescription; 16417 std::tie(InnerCond, InnerCondDescription) = 16418 findFailedBooleanCondition(Converted.get()); 16419 if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) { 16420 // Drill down into concept specialization expressions to see why they 16421 // weren't satisfied. 16422 Diag(StaticAssertLoc, diag::err_static_assert_failed) 16423 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 16424 ConstraintSatisfaction Satisfaction; 16425 if (!CheckConstraintSatisfaction(InnerCond, Satisfaction)) 16426 DiagnoseUnsatisfiedConstraint(Satisfaction); 16427 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond) 16428 && !isa<IntegerLiteral>(InnerCond)) { 16429 Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed) 16430 << InnerCondDescription << !AssertMessage 16431 << Msg.str() << InnerCond->getSourceRange(); 16432 } else { 16433 Diag(StaticAssertLoc, diag::err_static_assert_failed) 16434 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 16435 } 16436 Failed = true; 16437 } 16438 } else { 16439 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc, 16440 /*DiscardedValue*/false, 16441 /*IsConstexpr*/true); 16442 if (FullAssertExpr.isInvalid()) 16443 Failed = true; 16444 else 16445 AssertExpr = FullAssertExpr.get(); 16446 } 16447 16448 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 16449 AssertExpr, AssertMessage, RParenLoc, 16450 Failed); 16451 16452 CurContext->addDecl(Decl); 16453 return Decl; 16454 } 16455 16456 /// Perform semantic analysis of the given friend type declaration. 16457 /// 16458 /// \returns A friend declaration that. 16459 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 16460 SourceLocation FriendLoc, 16461 TypeSourceInfo *TSInfo) { 16462 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 16463 16464 QualType T = TSInfo->getType(); 16465 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 16466 16467 // C++03 [class.friend]p2: 16468 // An elaborated-type-specifier shall be used in a friend declaration 16469 // for a class.* 16470 // 16471 // * The class-key of the elaborated-type-specifier is required. 16472 if (!CodeSynthesisContexts.empty()) { 16473 // Do not complain about the form of friend template types during any kind 16474 // of code synthesis. For template instantiation, we will have complained 16475 // when the template was defined. 16476 } else { 16477 if (!T->isElaboratedTypeSpecifier()) { 16478 // If we evaluated the type to a record type, suggest putting 16479 // a tag in front. 16480 if (const RecordType *RT = T->getAs<RecordType>()) { 16481 RecordDecl *RD = RT->getDecl(); 16482 16483 SmallString<16> InsertionText(" "); 16484 InsertionText += RD->getKindName(); 16485 16486 Diag(TypeRange.getBegin(), 16487 getLangOpts().CPlusPlus11 ? 16488 diag::warn_cxx98_compat_unelaborated_friend_type : 16489 diag::ext_unelaborated_friend_type) 16490 << (unsigned) RD->getTagKind() 16491 << T 16492 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc), 16493 InsertionText); 16494 } else { 16495 Diag(FriendLoc, 16496 getLangOpts().CPlusPlus11 ? 16497 diag::warn_cxx98_compat_nonclass_type_friend : 16498 diag::ext_nonclass_type_friend) 16499 << T 16500 << TypeRange; 16501 } 16502 } else if (T->getAs<EnumType>()) { 16503 Diag(FriendLoc, 16504 getLangOpts().CPlusPlus11 ? 16505 diag::warn_cxx98_compat_enum_friend : 16506 diag::ext_enum_friend) 16507 << T 16508 << TypeRange; 16509 } 16510 16511 // C++11 [class.friend]p3: 16512 // A friend declaration that does not declare a function shall have one 16513 // of the following forms: 16514 // friend elaborated-type-specifier ; 16515 // friend simple-type-specifier ; 16516 // friend typename-specifier ; 16517 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 16518 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 16519 } 16520 16521 // If the type specifier in a friend declaration designates a (possibly 16522 // cv-qualified) class type, that class is declared as a friend; otherwise, 16523 // the friend declaration is ignored. 16524 return FriendDecl::Create(Context, CurContext, 16525 TSInfo->getTypeLoc().getBeginLoc(), TSInfo, 16526 FriendLoc); 16527 } 16528 16529 /// Handle a friend tag declaration where the scope specifier was 16530 /// templated. 16531 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 16532 unsigned TagSpec, SourceLocation TagLoc, 16533 CXXScopeSpec &SS, IdentifierInfo *Name, 16534 SourceLocation NameLoc, 16535 const ParsedAttributesView &Attr, 16536 MultiTemplateParamsArg TempParamLists) { 16537 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 16538 16539 bool IsMemberSpecialization = false; 16540 bool Invalid = false; 16541 16542 if (TemplateParameterList *TemplateParams = 16543 MatchTemplateParametersToScopeSpecifier( 16544 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 16545 IsMemberSpecialization, Invalid)) { 16546 if (TemplateParams->size() > 0) { 16547 // This is a declaration of a class template. 16548 if (Invalid) 16549 return nullptr; 16550 16551 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 16552 NameLoc, Attr, TemplateParams, AS_public, 16553 /*ModulePrivateLoc=*/SourceLocation(), 16554 FriendLoc, TempParamLists.size() - 1, 16555 TempParamLists.data()).get(); 16556 } else { 16557 // The "template<>" header is extraneous. 16558 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 16559 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 16560 IsMemberSpecialization = true; 16561 } 16562 } 16563 16564 if (Invalid) return nullptr; 16565 16566 bool isAllExplicitSpecializations = true; 16567 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 16568 if (TempParamLists[I]->size()) { 16569 isAllExplicitSpecializations = false; 16570 break; 16571 } 16572 } 16573 16574 // FIXME: don't ignore attributes. 16575 16576 // If it's explicit specializations all the way down, just forget 16577 // about the template header and build an appropriate non-templated 16578 // friend. TODO: for source fidelity, remember the headers. 16579 if (isAllExplicitSpecializations) { 16580 if (SS.isEmpty()) { 16581 bool Owned = false; 16582 bool IsDependent = false; 16583 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 16584 Attr, AS_public, 16585 /*ModulePrivateLoc=*/SourceLocation(), 16586 MultiTemplateParamsArg(), Owned, IsDependent, 16587 /*ScopedEnumKWLoc=*/SourceLocation(), 16588 /*ScopedEnumUsesClassTag=*/false, 16589 /*UnderlyingType=*/TypeResult(), 16590 /*IsTypeSpecifier=*/false, 16591 /*IsTemplateParamOrArg=*/false); 16592 } 16593 16594 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 16595 ElaboratedTypeKeyword Keyword 16596 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 16597 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 16598 *Name, NameLoc); 16599 if (T.isNull()) 16600 return nullptr; 16601 16602 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 16603 if (isa<DependentNameType>(T)) { 16604 DependentNameTypeLoc TL = 16605 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 16606 TL.setElaboratedKeywordLoc(TagLoc); 16607 TL.setQualifierLoc(QualifierLoc); 16608 TL.setNameLoc(NameLoc); 16609 } else { 16610 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 16611 TL.setElaboratedKeywordLoc(TagLoc); 16612 TL.setQualifierLoc(QualifierLoc); 16613 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 16614 } 16615 16616 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 16617 TSI, FriendLoc, TempParamLists); 16618 Friend->setAccess(AS_public); 16619 CurContext->addDecl(Friend); 16620 return Friend; 16621 } 16622 16623 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 16624 16625 16626 16627 // Handle the case of a templated-scope friend class. e.g. 16628 // template <class T> class A<T>::B; 16629 // FIXME: we don't support these right now. 16630 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 16631 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 16632 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 16633 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 16634 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 16635 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 16636 TL.setElaboratedKeywordLoc(TagLoc); 16637 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 16638 TL.setNameLoc(NameLoc); 16639 16640 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 16641 TSI, FriendLoc, TempParamLists); 16642 Friend->setAccess(AS_public); 16643 Friend->setUnsupportedFriend(true); 16644 CurContext->addDecl(Friend); 16645 return Friend; 16646 } 16647 16648 /// Handle a friend type declaration. This works in tandem with 16649 /// ActOnTag. 16650 /// 16651 /// Notes on friend class templates: 16652 /// 16653 /// We generally treat friend class declarations as if they were 16654 /// declaring a class. So, for example, the elaborated type specifier 16655 /// in a friend declaration is required to obey the restrictions of a 16656 /// class-head (i.e. no typedefs in the scope chain), template 16657 /// parameters are required to match up with simple template-ids, &c. 16658 /// However, unlike when declaring a template specialization, it's 16659 /// okay to refer to a template specialization without an empty 16660 /// template parameter declaration, e.g. 16661 /// friend class A<T>::B<unsigned>; 16662 /// We permit this as a special case; if there are any template 16663 /// parameters present at all, require proper matching, i.e. 16664 /// template <> template \<class T> friend class A<int>::B; 16665 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 16666 MultiTemplateParamsArg TempParams) { 16667 SourceLocation Loc = DS.getBeginLoc(); 16668 16669 assert(DS.isFriendSpecified()); 16670 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 16671 16672 // C++ [class.friend]p3: 16673 // A friend declaration that does not declare a function shall have one of 16674 // the following forms: 16675 // friend elaborated-type-specifier ; 16676 // friend simple-type-specifier ; 16677 // friend typename-specifier ; 16678 // 16679 // Any declaration with a type qualifier does not have that form. (It's 16680 // legal to specify a qualified type as a friend, you just can't write the 16681 // keywords.) 16682 if (DS.getTypeQualifiers()) { 16683 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 16684 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const"; 16685 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 16686 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile"; 16687 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 16688 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict"; 16689 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 16690 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic"; 16691 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 16692 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned"; 16693 } 16694 16695 // Try to convert the decl specifier to a type. This works for 16696 // friend templates because ActOnTag never produces a ClassTemplateDecl 16697 // for a TUK_Friend. 16698 Declarator TheDeclarator(DS, DeclaratorContext::Member); 16699 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 16700 QualType T = TSI->getType(); 16701 if (TheDeclarator.isInvalidType()) 16702 return nullptr; 16703 16704 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 16705 return nullptr; 16706 16707 // This is definitely an error in C++98. It's probably meant to 16708 // be forbidden in C++0x, too, but the specification is just 16709 // poorly written. 16710 // 16711 // The problem is with declarations like the following: 16712 // template <T> friend A<T>::foo; 16713 // where deciding whether a class C is a friend or not now hinges 16714 // on whether there exists an instantiation of A that causes 16715 // 'foo' to equal C. There are restrictions on class-heads 16716 // (which we declare (by fiat) elaborated friend declarations to 16717 // be) that makes this tractable. 16718 // 16719 // FIXME: handle "template <> friend class A<T>;", which 16720 // is possibly well-formed? Who even knows? 16721 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 16722 Diag(Loc, diag::err_tagless_friend_type_template) 16723 << DS.getSourceRange(); 16724 return nullptr; 16725 } 16726 16727 // C++98 [class.friend]p1: A friend of a class is a function 16728 // or class that is not a member of the class . . . 16729 // This is fixed in DR77, which just barely didn't make the C++03 16730 // deadline. It's also a very silly restriction that seriously 16731 // affects inner classes and which nobody else seems to implement; 16732 // thus we never diagnose it, not even in -pedantic. 16733 // 16734 // But note that we could warn about it: it's always useless to 16735 // friend one of your own members (it's not, however, worthless to 16736 // friend a member of an arbitrary specialization of your template). 16737 16738 Decl *D; 16739 if (!TempParams.empty()) 16740 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 16741 TempParams, 16742 TSI, 16743 DS.getFriendSpecLoc()); 16744 else 16745 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 16746 16747 if (!D) 16748 return nullptr; 16749 16750 D->setAccess(AS_public); 16751 CurContext->addDecl(D); 16752 16753 return D; 16754 } 16755 16756 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 16757 MultiTemplateParamsArg TemplateParams) { 16758 const DeclSpec &DS = D.getDeclSpec(); 16759 16760 assert(DS.isFriendSpecified()); 16761 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 16762 16763 SourceLocation Loc = D.getIdentifierLoc(); 16764 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16765 16766 // C++ [class.friend]p1 16767 // A friend of a class is a function or class.... 16768 // Note that this sees through typedefs, which is intended. 16769 // It *doesn't* see through dependent types, which is correct 16770 // according to [temp.arg.type]p3: 16771 // If a declaration acquires a function type through a 16772 // type dependent on a template-parameter and this causes 16773 // a declaration that does not use the syntactic form of a 16774 // function declarator to have a function type, the program 16775 // is ill-formed. 16776 if (!TInfo->getType()->isFunctionType()) { 16777 Diag(Loc, diag::err_unexpected_friend); 16778 16779 // It might be worthwhile to try to recover by creating an 16780 // appropriate declaration. 16781 return nullptr; 16782 } 16783 16784 // C++ [namespace.memdef]p3 16785 // - If a friend declaration in a non-local class first declares a 16786 // class or function, the friend class or function is a member 16787 // of the innermost enclosing namespace. 16788 // - The name of the friend is not found by simple name lookup 16789 // until a matching declaration is provided in that namespace 16790 // scope (either before or after the class declaration granting 16791 // friendship). 16792 // - If a friend function is called, its name may be found by the 16793 // name lookup that considers functions from namespaces and 16794 // classes associated with the types of the function arguments. 16795 // - When looking for a prior declaration of a class or a function 16796 // declared as a friend, scopes outside the innermost enclosing 16797 // namespace scope are not considered. 16798 16799 CXXScopeSpec &SS = D.getCXXScopeSpec(); 16800 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 16801 assert(NameInfo.getName()); 16802 16803 // Check for unexpanded parameter packs. 16804 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 16805 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 16806 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 16807 return nullptr; 16808 16809 // The context we found the declaration in, or in which we should 16810 // create the declaration. 16811 DeclContext *DC; 16812 Scope *DCScope = S; 16813 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 16814 ForExternalRedeclaration); 16815 16816 // There are five cases here. 16817 // - There's no scope specifier and we're in a local class. Only look 16818 // for functions declared in the immediately-enclosing block scope. 16819 // We recover from invalid scope qualifiers as if they just weren't there. 16820 FunctionDecl *FunctionContainingLocalClass = nullptr; 16821 if ((SS.isInvalid() || !SS.isSet()) && 16822 (FunctionContainingLocalClass = 16823 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 16824 // C++11 [class.friend]p11: 16825 // If a friend declaration appears in a local class and the name 16826 // specified is an unqualified name, a prior declaration is 16827 // looked up without considering scopes that are outside the 16828 // innermost enclosing non-class scope. For a friend function 16829 // declaration, if there is no prior declaration, the program is 16830 // ill-formed. 16831 16832 // Find the innermost enclosing non-class scope. This is the block 16833 // scope containing the local class definition (or for a nested class, 16834 // the outer local class). 16835 DCScope = S->getFnParent(); 16836 16837 // Look up the function name in the scope. 16838 Previous.clear(LookupLocalFriendName); 16839 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 16840 16841 if (!Previous.empty()) { 16842 // All possible previous declarations must have the same context: 16843 // either they were declared at block scope or they are members of 16844 // one of the enclosing local classes. 16845 DC = Previous.getRepresentativeDecl()->getDeclContext(); 16846 } else { 16847 // This is ill-formed, but provide the context that we would have 16848 // declared the function in, if we were permitted to, for error recovery. 16849 DC = FunctionContainingLocalClass; 16850 } 16851 adjustContextForLocalExternDecl(DC); 16852 16853 // C++ [class.friend]p6: 16854 // A function can be defined in a friend declaration of a class if and 16855 // only if the class is a non-local class (9.8), the function name is 16856 // unqualified, and the function has namespace scope. 16857 if (D.isFunctionDefinition()) { 16858 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 16859 } 16860 16861 // - There's no scope specifier, in which case we just go to the 16862 // appropriate scope and look for a function or function template 16863 // there as appropriate. 16864 } else if (SS.isInvalid() || !SS.isSet()) { 16865 // C++11 [namespace.memdef]p3: 16866 // If the name in a friend declaration is neither qualified nor 16867 // a template-id and the declaration is a function or an 16868 // elaborated-type-specifier, the lookup to determine whether 16869 // the entity has been previously declared shall not consider 16870 // any scopes outside the innermost enclosing namespace. 16871 bool isTemplateId = 16872 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId; 16873 16874 // Find the appropriate context according to the above. 16875 DC = CurContext; 16876 16877 // Skip class contexts. If someone can cite chapter and verse 16878 // for this behavior, that would be nice --- it's what GCC and 16879 // EDG do, and it seems like a reasonable intent, but the spec 16880 // really only says that checks for unqualified existing 16881 // declarations should stop at the nearest enclosing namespace, 16882 // not that they should only consider the nearest enclosing 16883 // namespace. 16884 while (DC->isRecord()) 16885 DC = DC->getParent(); 16886 16887 DeclContext *LookupDC = DC->getNonTransparentContext(); 16888 while (true) { 16889 LookupQualifiedName(Previous, LookupDC); 16890 16891 if (!Previous.empty()) { 16892 DC = LookupDC; 16893 break; 16894 } 16895 16896 if (isTemplateId) { 16897 if (isa<TranslationUnitDecl>(LookupDC)) break; 16898 } else { 16899 if (LookupDC->isFileContext()) break; 16900 } 16901 LookupDC = LookupDC->getParent(); 16902 } 16903 16904 DCScope = getScopeForDeclContext(S, DC); 16905 16906 // - There's a non-dependent scope specifier, in which case we 16907 // compute it and do a previous lookup there for a function 16908 // or function template. 16909 } else if (!SS.getScopeRep()->isDependent()) { 16910 DC = computeDeclContext(SS); 16911 if (!DC) return nullptr; 16912 16913 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 16914 16915 LookupQualifiedName(Previous, DC); 16916 16917 // C++ [class.friend]p1: A friend of a class is a function or 16918 // class that is not a member of the class . . . 16919 if (DC->Equals(CurContext)) 16920 Diag(DS.getFriendSpecLoc(), 16921 getLangOpts().CPlusPlus11 ? 16922 diag::warn_cxx98_compat_friend_is_member : 16923 diag::err_friend_is_member); 16924 16925 if (D.isFunctionDefinition()) { 16926 // C++ [class.friend]p6: 16927 // A function can be defined in a friend declaration of a class if and 16928 // only if the class is a non-local class (9.8), the function name is 16929 // unqualified, and the function has namespace scope. 16930 // 16931 // FIXME: We should only do this if the scope specifier names the 16932 // innermost enclosing namespace; otherwise the fixit changes the 16933 // meaning of the code. 16934 SemaDiagnosticBuilder DB 16935 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 16936 16937 DB << SS.getScopeRep(); 16938 if (DC->isFileContext()) 16939 DB << FixItHint::CreateRemoval(SS.getRange()); 16940 SS.clear(); 16941 } 16942 16943 // - There's a scope specifier that does not match any template 16944 // parameter lists, in which case we use some arbitrary context, 16945 // create a method or method template, and wait for instantiation. 16946 // - There's a scope specifier that does match some template 16947 // parameter lists, which we don't handle right now. 16948 } else { 16949 if (D.isFunctionDefinition()) { 16950 // C++ [class.friend]p6: 16951 // A function can be defined in a friend declaration of a class if and 16952 // only if the class is a non-local class (9.8), the function name is 16953 // unqualified, and the function has namespace scope. 16954 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 16955 << SS.getScopeRep(); 16956 } 16957 16958 DC = CurContext; 16959 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 16960 } 16961 16962 if (!DC->isRecord()) { 16963 int DiagArg = -1; 16964 switch (D.getName().getKind()) { 16965 case UnqualifiedIdKind::IK_ConstructorTemplateId: 16966 case UnqualifiedIdKind::IK_ConstructorName: 16967 DiagArg = 0; 16968 break; 16969 case UnqualifiedIdKind::IK_DestructorName: 16970 DiagArg = 1; 16971 break; 16972 case UnqualifiedIdKind::IK_ConversionFunctionId: 16973 DiagArg = 2; 16974 break; 16975 case UnqualifiedIdKind::IK_DeductionGuideName: 16976 DiagArg = 3; 16977 break; 16978 case UnqualifiedIdKind::IK_Identifier: 16979 case UnqualifiedIdKind::IK_ImplicitSelfParam: 16980 case UnqualifiedIdKind::IK_LiteralOperatorId: 16981 case UnqualifiedIdKind::IK_OperatorFunctionId: 16982 case UnqualifiedIdKind::IK_TemplateId: 16983 break; 16984 } 16985 // This implies that it has to be an operator or function. 16986 if (DiagArg >= 0) { 16987 Diag(Loc, diag::err_introducing_special_friend) << DiagArg; 16988 return nullptr; 16989 } 16990 } 16991 16992 // FIXME: This is an egregious hack to cope with cases where the scope stack 16993 // does not contain the declaration context, i.e., in an out-of-line 16994 // definition of a class. 16995 Scope FakeDCScope(S, Scope::DeclScope, Diags); 16996 if (!DCScope) { 16997 FakeDCScope.setEntity(DC); 16998 DCScope = &FakeDCScope; 16999 } 17000 17001 bool AddToScope = true; 17002 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 17003 TemplateParams, AddToScope); 17004 if (!ND) return nullptr; 17005 17006 assert(ND->getLexicalDeclContext() == CurContext); 17007 17008 // If we performed typo correction, we might have added a scope specifier 17009 // and changed the decl context. 17010 DC = ND->getDeclContext(); 17011 17012 // Add the function declaration to the appropriate lookup tables, 17013 // adjusting the redeclarations list as necessary. We don't 17014 // want to do this yet if the friending class is dependent. 17015 // 17016 // Also update the scope-based lookup if the target context's 17017 // lookup context is in lexical scope. 17018 if (!CurContext->isDependentContext()) { 17019 DC = DC->getRedeclContext(); 17020 DC->makeDeclVisibleInContext(ND); 17021 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 17022 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 17023 } 17024 17025 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 17026 D.getIdentifierLoc(), ND, 17027 DS.getFriendSpecLoc()); 17028 FrD->setAccess(AS_public); 17029 CurContext->addDecl(FrD); 17030 17031 if (ND->isInvalidDecl()) { 17032 FrD->setInvalidDecl(); 17033 } else { 17034 if (DC->isRecord()) CheckFriendAccess(ND); 17035 17036 FunctionDecl *FD; 17037 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 17038 FD = FTD->getTemplatedDecl(); 17039 else 17040 FD = cast<FunctionDecl>(ND); 17041 17042 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 17043 // default argument expression, that declaration shall be a definition 17044 // and shall be the only declaration of the function or function 17045 // template in the translation unit. 17046 if (functionDeclHasDefaultArgument(FD)) { 17047 // We can't look at FD->getPreviousDecl() because it may not have been set 17048 // if we're in a dependent context. If the function is known to be a 17049 // redeclaration, we will have narrowed Previous down to the right decl. 17050 if (D.isRedeclaration()) { 17051 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 17052 Diag(Previous.getRepresentativeDecl()->getLocation(), 17053 diag::note_previous_declaration); 17054 } else if (!D.isFunctionDefinition()) 17055 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 17056 } 17057 17058 // Mark templated-scope function declarations as unsupported. 17059 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 17060 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 17061 << SS.getScopeRep() << SS.getRange() 17062 << cast<CXXRecordDecl>(CurContext); 17063 FrD->setUnsupportedFriend(true); 17064 } 17065 } 17066 17067 warnOnReservedIdentifier(ND); 17068 17069 return ND; 17070 } 17071 17072 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 17073 AdjustDeclIfTemplate(Dcl); 17074 17075 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 17076 if (!Fn) { 17077 Diag(DelLoc, diag::err_deleted_non_function); 17078 return; 17079 } 17080 17081 // Deleted function does not have a body. 17082 Fn->setWillHaveBody(false); 17083 17084 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 17085 // Don't consider the implicit declaration we generate for explicit 17086 // specializations. FIXME: Do not generate these implicit declarations. 17087 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 17088 Prev->getPreviousDecl()) && 17089 !Prev->isDefined()) { 17090 Diag(DelLoc, diag::err_deleted_decl_not_first); 17091 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 17092 Prev->isImplicit() ? diag::note_previous_implicit_declaration 17093 : diag::note_previous_declaration); 17094 // We can't recover from this; the declaration might have already 17095 // been used. 17096 Fn->setInvalidDecl(); 17097 return; 17098 } 17099 17100 // To maintain the invariant that functions are only deleted on their first 17101 // declaration, mark the implicitly-instantiated declaration of the 17102 // explicitly-specialized function as deleted instead of marking the 17103 // instantiated redeclaration. 17104 Fn = Fn->getCanonicalDecl(); 17105 } 17106 17107 // dllimport/dllexport cannot be deleted. 17108 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 17109 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 17110 Fn->setInvalidDecl(); 17111 } 17112 17113 // C++11 [basic.start.main]p3: 17114 // A program that defines main as deleted [...] is ill-formed. 17115 if (Fn->isMain()) 17116 Diag(DelLoc, diag::err_deleted_main); 17117 17118 // C++11 [dcl.fct.def.delete]p4: 17119 // A deleted function is implicitly inline. 17120 Fn->setImplicitlyInline(); 17121 Fn->setDeletedAsWritten(); 17122 } 17123 17124 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 17125 if (!Dcl || Dcl->isInvalidDecl()) 17126 return; 17127 17128 auto *FD = dyn_cast<FunctionDecl>(Dcl); 17129 if (!FD) { 17130 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) { 17131 if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) { 17132 Diag(DefaultLoc, diag::err_defaulted_comparison_template); 17133 return; 17134 } 17135 } 17136 17137 Diag(DefaultLoc, diag::err_default_special_members) 17138 << getLangOpts().CPlusPlus20; 17139 return; 17140 } 17141 17142 // Reject if this can't possibly be a defaultable function. 17143 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD); 17144 if (!DefKind && 17145 // A dependent function that doesn't locally look defaultable can 17146 // still instantiate to a defaultable function if it's a constructor 17147 // or assignment operator. 17148 (!FD->isDependentContext() || 17149 (!isa<CXXConstructorDecl>(FD) && 17150 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) { 17151 Diag(DefaultLoc, diag::err_default_special_members) 17152 << getLangOpts().CPlusPlus20; 17153 return; 17154 } 17155 17156 if (DefKind.isComparison() && 17157 !isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 17158 Diag(FD->getLocation(), diag::err_defaulted_comparison_out_of_class) 17159 << (int)DefKind.asComparison(); 17160 return; 17161 } 17162 17163 // Issue compatibility warning. We already warned if the operator is 17164 // 'operator<=>' when parsing the '<=>' token. 17165 if (DefKind.isComparison() && 17166 DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) { 17167 Diag(DefaultLoc, getLangOpts().CPlusPlus20 17168 ? diag::warn_cxx17_compat_defaulted_comparison 17169 : diag::ext_defaulted_comparison); 17170 } 17171 17172 FD->setDefaulted(); 17173 FD->setExplicitlyDefaulted(); 17174 17175 // Defer checking functions that are defaulted in a dependent context. 17176 if (FD->isDependentContext()) 17177 return; 17178 17179 // Unset that we will have a body for this function. We might not, 17180 // if it turns out to be trivial, and we don't need this marking now 17181 // that we've marked it as defaulted. 17182 FD->setWillHaveBody(false); 17183 17184 // If this definition appears within the record, do the checking when 17185 // the record is complete. This is always the case for a defaulted 17186 // comparison. 17187 if (DefKind.isComparison()) 17188 return; 17189 auto *MD = cast<CXXMethodDecl>(FD); 17190 17191 const FunctionDecl *Primary = FD; 17192 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern()) 17193 // Ask the template instantiation pattern that actually had the 17194 // '= default' on it. 17195 Primary = Pattern; 17196 17197 // If the method was defaulted on its first declaration, we will have 17198 // already performed the checking in CheckCompletedCXXClass. Such a 17199 // declaration doesn't trigger an implicit definition. 17200 if (Primary->getCanonicalDecl()->isDefaulted()) 17201 return; 17202 17203 // FIXME: Once we support defining comparisons out of class, check for a 17204 // defaulted comparison here. 17205 if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember())) 17206 MD->setInvalidDecl(); 17207 else 17208 DefineDefaultedFunction(*this, MD, DefaultLoc); 17209 } 17210 17211 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 17212 for (Stmt *SubStmt : S->children()) { 17213 if (!SubStmt) 17214 continue; 17215 if (isa<ReturnStmt>(SubStmt)) 17216 Self.Diag(SubStmt->getBeginLoc(), 17217 diag::err_return_in_constructor_handler); 17218 if (!isa<Expr>(SubStmt)) 17219 SearchForReturnInStmt(Self, SubStmt); 17220 } 17221 } 17222 17223 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 17224 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 17225 CXXCatchStmt *Handler = TryBlock->getHandler(I); 17226 SearchForReturnInStmt(*this, Handler); 17227 } 17228 } 17229 17230 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 17231 const CXXMethodDecl *Old) { 17232 const auto *NewFT = New->getType()->castAs<FunctionProtoType>(); 17233 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>(); 17234 17235 if (OldFT->hasExtParameterInfos()) { 17236 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I) 17237 // A parameter of the overriding method should be annotated with noescape 17238 // if the corresponding parameter of the overridden method is annotated. 17239 if (OldFT->getExtParameterInfo(I).isNoEscape() && 17240 !NewFT->getExtParameterInfo(I).isNoEscape()) { 17241 Diag(New->getParamDecl(I)->getLocation(), 17242 diag::warn_overriding_method_missing_noescape); 17243 Diag(Old->getParamDecl(I)->getLocation(), 17244 diag::note_overridden_marked_noescape); 17245 } 17246 } 17247 17248 // Virtual overrides must have the same code_seg. 17249 const auto *OldCSA = Old->getAttr<CodeSegAttr>(); 17250 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 17251 if ((NewCSA || OldCSA) && 17252 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) { 17253 Diag(New->getLocation(), diag::err_mismatched_code_seg_override); 17254 Diag(Old->getLocation(), diag::note_previous_declaration); 17255 return true; 17256 } 17257 17258 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 17259 17260 // If the calling conventions match, everything is fine 17261 if (NewCC == OldCC) 17262 return false; 17263 17264 // If the calling conventions mismatch because the new function is static, 17265 // suppress the calling convention mismatch error; the error about static 17266 // function override (err_static_overrides_virtual from 17267 // Sema::CheckFunctionDeclaration) is more clear. 17268 if (New->getStorageClass() == SC_Static) 17269 return false; 17270 17271 Diag(New->getLocation(), 17272 diag::err_conflicting_overriding_cc_attributes) 17273 << New->getDeclName() << New->getType() << Old->getType(); 17274 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 17275 return true; 17276 } 17277 17278 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 17279 const CXXMethodDecl *Old) { 17280 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType(); 17281 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType(); 17282 17283 if (Context.hasSameType(NewTy, OldTy) || 17284 NewTy->isDependentType() || OldTy->isDependentType()) 17285 return false; 17286 17287 // Check if the return types are covariant 17288 QualType NewClassTy, OldClassTy; 17289 17290 /// Both types must be pointers or references to classes. 17291 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 17292 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 17293 NewClassTy = NewPT->getPointeeType(); 17294 OldClassTy = OldPT->getPointeeType(); 17295 } 17296 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 17297 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 17298 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 17299 NewClassTy = NewRT->getPointeeType(); 17300 OldClassTy = OldRT->getPointeeType(); 17301 } 17302 } 17303 } 17304 17305 // The return types aren't either both pointers or references to a class type. 17306 if (NewClassTy.isNull()) { 17307 Diag(New->getLocation(), 17308 diag::err_different_return_type_for_overriding_virtual_function) 17309 << New->getDeclName() << NewTy << OldTy 17310 << New->getReturnTypeSourceRange(); 17311 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17312 << Old->getReturnTypeSourceRange(); 17313 17314 return true; 17315 } 17316 17317 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 17318 // C++14 [class.virtual]p8: 17319 // If the class type in the covariant return type of D::f differs from 17320 // that of B::f, the class type in the return type of D::f shall be 17321 // complete at the point of declaration of D::f or shall be the class 17322 // type D. 17323 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 17324 if (!RT->isBeingDefined() && 17325 RequireCompleteType(New->getLocation(), NewClassTy, 17326 diag::err_covariant_return_incomplete, 17327 New->getDeclName())) 17328 return true; 17329 } 17330 17331 // Check if the new class derives from the old class. 17332 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) { 17333 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 17334 << New->getDeclName() << NewTy << OldTy 17335 << New->getReturnTypeSourceRange(); 17336 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17337 << Old->getReturnTypeSourceRange(); 17338 return true; 17339 } 17340 17341 // Check if we the conversion from derived to base is valid. 17342 if (CheckDerivedToBaseConversion( 17343 NewClassTy, OldClassTy, 17344 diag::err_covariant_return_inaccessible_base, 17345 diag::err_covariant_return_ambiguous_derived_to_base_conv, 17346 New->getLocation(), New->getReturnTypeSourceRange(), 17347 New->getDeclName(), nullptr)) { 17348 // FIXME: this note won't trigger for delayed access control 17349 // diagnostics, and it's impossible to get an undelayed error 17350 // here from access control during the original parse because 17351 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 17352 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17353 << Old->getReturnTypeSourceRange(); 17354 return true; 17355 } 17356 } 17357 17358 // The qualifiers of the return types must be the same. 17359 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 17360 Diag(New->getLocation(), 17361 diag::err_covariant_return_type_different_qualifications) 17362 << New->getDeclName() << NewTy << OldTy 17363 << New->getReturnTypeSourceRange(); 17364 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17365 << Old->getReturnTypeSourceRange(); 17366 return true; 17367 } 17368 17369 17370 // The new class type must have the same or less qualifiers as the old type. 17371 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 17372 Diag(New->getLocation(), 17373 diag::err_covariant_return_type_class_type_more_qualified) 17374 << New->getDeclName() << NewTy << OldTy 17375 << New->getReturnTypeSourceRange(); 17376 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17377 << Old->getReturnTypeSourceRange(); 17378 return true; 17379 } 17380 17381 return false; 17382 } 17383 17384 /// Mark the given method pure. 17385 /// 17386 /// \param Method the method to be marked pure. 17387 /// 17388 /// \param InitRange the source range that covers the "0" initializer. 17389 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 17390 SourceLocation EndLoc = InitRange.getEnd(); 17391 if (EndLoc.isValid()) 17392 Method->setRangeEnd(EndLoc); 17393 17394 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 17395 Method->setPure(); 17396 return false; 17397 } 17398 17399 if (!Method->isInvalidDecl()) 17400 Diag(Method->getLocation(), diag::err_non_virtual_pure) 17401 << Method->getDeclName() << InitRange; 17402 return true; 17403 } 17404 17405 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) { 17406 if (D->getFriendObjectKind()) 17407 Diag(D->getLocation(), diag::err_pure_friend); 17408 else if (auto *M = dyn_cast<CXXMethodDecl>(D)) 17409 CheckPureMethod(M, ZeroLoc); 17410 else 17411 Diag(D->getLocation(), diag::err_illegal_initializer); 17412 } 17413 17414 /// Determine whether the given declaration is a global variable or 17415 /// static data member. 17416 static bool isNonlocalVariable(const Decl *D) { 17417 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 17418 return Var->hasGlobalStorage(); 17419 17420 return false; 17421 } 17422 17423 /// Invoked when we are about to parse an initializer for the declaration 17424 /// 'Dcl'. 17425 /// 17426 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 17427 /// static data member of class X, names should be looked up in the scope of 17428 /// class X. If the declaration had a scope specifier, a scope will have 17429 /// been created and passed in for this purpose. Otherwise, S will be null. 17430 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 17431 // If there is no declaration, there was an error parsing it. 17432 if (!D || D->isInvalidDecl()) 17433 return; 17434 17435 // We will always have a nested name specifier here, but this declaration 17436 // might not be out of line if the specifier names the current namespace: 17437 // extern int n; 17438 // int ::n = 0; 17439 if (S && D->isOutOfLine()) 17440 EnterDeclaratorContext(S, D->getDeclContext()); 17441 17442 // If we are parsing the initializer for a static data member, push a 17443 // new expression evaluation context that is associated with this static 17444 // data member. 17445 if (isNonlocalVariable(D)) 17446 PushExpressionEvaluationContext( 17447 ExpressionEvaluationContext::PotentiallyEvaluated, D); 17448 } 17449 17450 /// Invoked after we are finished parsing an initializer for the declaration D. 17451 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 17452 // If there is no declaration, there was an error parsing it. 17453 if (!D || D->isInvalidDecl()) 17454 return; 17455 17456 if (isNonlocalVariable(D)) 17457 PopExpressionEvaluationContext(); 17458 17459 if (S && D->isOutOfLine()) 17460 ExitDeclaratorContext(S); 17461 } 17462 17463 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 17464 /// C++ if/switch/while/for statement. 17465 /// e.g: "if (int x = f()) {...}" 17466 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 17467 // C++ 6.4p2: 17468 // The declarator shall not specify a function or an array. 17469 // The type-specifier-seq shall not contain typedef and shall not declare a 17470 // new class or enumeration. 17471 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 17472 "Parser allowed 'typedef' as storage class of condition decl."); 17473 17474 Decl *Dcl = ActOnDeclarator(S, D); 17475 if (!Dcl) 17476 return true; 17477 17478 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 17479 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 17480 << D.getSourceRange(); 17481 return true; 17482 } 17483 17484 return Dcl; 17485 } 17486 17487 void Sema::LoadExternalVTableUses() { 17488 if (!ExternalSource) 17489 return; 17490 17491 SmallVector<ExternalVTableUse, 4> VTables; 17492 ExternalSource->ReadUsedVTables(VTables); 17493 SmallVector<VTableUse, 4> NewUses; 17494 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 17495 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 17496 = VTablesUsed.find(VTables[I].Record); 17497 // Even if a definition wasn't required before, it may be required now. 17498 if (Pos != VTablesUsed.end()) { 17499 if (!Pos->second && VTables[I].DefinitionRequired) 17500 Pos->second = true; 17501 continue; 17502 } 17503 17504 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 17505 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 17506 } 17507 17508 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 17509 } 17510 17511 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 17512 bool DefinitionRequired) { 17513 // Ignore any vtable uses in unevaluated operands or for classes that do 17514 // not have a vtable. 17515 if (!Class->isDynamicClass() || Class->isDependentContext() || 17516 CurContext->isDependentContext() || isUnevaluatedContext()) 17517 return; 17518 // Do not mark as used if compiling for the device outside of the target 17519 // region. 17520 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice && 17521 !isInOpenMPDeclareTargetContext() && 17522 !isInOpenMPTargetExecutionDirective()) { 17523 if (!DefinitionRequired) 17524 MarkVirtualMembersReferenced(Loc, Class); 17525 return; 17526 } 17527 17528 // Try to insert this class into the map. 17529 LoadExternalVTableUses(); 17530 Class = Class->getCanonicalDecl(); 17531 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 17532 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 17533 if (!Pos.second) { 17534 // If we already had an entry, check to see if we are promoting this vtable 17535 // to require a definition. If so, we need to reappend to the VTableUses 17536 // list, since we may have already processed the first entry. 17537 if (DefinitionRequired && !Pos.first->second) { 17538 Pos.first->second = true; 17539 } else { 17540 // Otherwise, we can early exit. 17541 return; 17542 } 17543 } else { 17544 // The Microsoft ABI requires that we perform the destructor body 17545 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 17546 // the deleting destructor is emitted with the vtable, not with the 17547 // destructor definition as in the Itanium ABI. 17548 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 17549 CXXDestructorDecl *DD = Class->getDestructor(); 17550 if (DD && DD->isVirtual() && !DD->isDeleted()) { 17551 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) { 17552 // If this is an out-of-line declaration, marking it referenced will 17553 // not do anything. Manually call CheckDestructor to look up operator 17554 // delete(). 17555 ContextRAII SavedContext(*this, DD); 17556 CheckDestructor(DD); 17557 } else { 17558 MarkFunctionReferenced(Loc, Class->getDestructor()); 17559 } 17560 } 17561 } 17562 } 17563 17564 // Local classes need to have their virtual members marked 17565 // immediately. For all other classes, we mark their virtual members 17566 // at the end of the translation unit. 17567 if (Class->isLocalClass()) 17568 MarkVirtualMembersReferenced(Loc, Class); 17569 else 17570 VTableUses.push_back(std::make_pair(Class, Loc)); 17571 } 17572 17573 bool Sema::DefineUsedVTables() { 17574 LoadExternalVTableUses(); 17575 if (VTableUses.empty()) 17576 return false; 17577 17578 // Note: The VTableUses vector could grow as a result of marking 17579 // the members of a class as "used", so we check the size each 17580 // time through the loop and prefer indices (which are stable) to 17581 // iterators (which are not). 17582 bool DefinedAnything = false; 17583 for (unsigned I = 0; I != VTableUses.size(); ++I) { 17584 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 17585 if (!Class) 17586 continue; 17587 TemplateSpecializationKind ClassTSK = 17588 Class->getTemplateSpecializationKind(); 17589 17590 SourceLocation Loc = VTableUses[I].second; 17591 17592 bool DefineVTable = true; 17593 17594 // If this class has a key function, but that key function is 17595 // defined in another translation unit, we don't need to emit the 17596 // vtable even though we're using it. 17597 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 17598 if (KeyFunction && !KeyFunction->hasBody()) { 17599 // The key function is in another translation unit. 17600 DefineVTable = false; 17601 TemplateSpecializationKind TSK = 17602 KeyFunction->getTemplateSpecializationKind(); 17603 assert(TSK != TSK_ExplicitInstantiationDefinition && 17604 TSK != TSK_ImplicitInstantiation && 17605 "Instantiations don't have key functions"); 17606 (void)TSK; 17607 } else if (!KeyFunction) { 17608 // If we have a class with no key function that is the subject 17609 // of an explicit instantiation declaration, suppress the 17610 // vtable; it will live with the explicit instantiation 17611 // definition. 17612 bool IsExplicitInstantiationDeclaration = 17613 ClassTSK == TSK_ExplicitInstantiationDeclaration; 17614 for (auto R : Class->redecls()) { 17615 TemplateSpecializationKind TSK 17616 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 17617 if (TSK == TSK_ExplicitInstantiationDeclaration) 17618 IsExplicitInstantiationDeclaration = true; 17619 else if (TSK == TSK_ExplicitInstantiationDefinition) { 17620 IsExplicitInstantiationDeclaration = false; 17621 break; 17622 } 17623 } 17624 17625 if (IsExplicitInstantiationDeclaration) 17626 DefineVTable = false; 17627 } 17628 17629 // The exception specifications for all virtual members may be needed even 17630 // if we are not providing an authoritative form of the vtable in this TU. 17631 // We may choose to emit it available_externally anyway. 17632 if (!DefineVTable) { 17633 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 17634 continue; 17635 } 17636 17637 // Mark all of the virtual members of this class as referenced, so 17638 // that we can build a vtable. Then, tell the AST consumer that a 17639 // vtable for this class is required. 17640 DefinedAnything = true; 17641 MarkVirtualMembersReferenced(Loc, Class); 17642 CXXRecordDecl *Canonical = Class->getCanonicalDecl(); 17643 if (VTablesUsed[Canonical]) 17644 Consumer.HandleVTable(Class); 17645 17646 // Warn if we're emitting a weak vtable. The vtable will be weak if there is 17647 // no key function or the key function is inlined. Don't warn in C++ ABIs 17648 // that lack key functions, since the user won't be able to make one. 17649 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() && 17650 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation && 17651 ClassTSK != TSK_ExplicitInstantiationDefinition) { 17652 const FunctionDecl *KeyFunctionDef = nullptr; 17653 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) && 17654 KeyFunctionDef->isInlined())) 17655 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class; 17656 } 17657 } 17658 VTableUses.clear(); 17659 17660 return DefinedAnything; 17661 } 17662 17663 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 17664 const CXXRecordDecl *RD) { 17665 for (const auto *I : RD->methods()) 17666 if (I->isVirtual() && !I->isPure()) 17667 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 17668 } 17669 17670 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 17671 const CXXRecordDecl *RD, 17672 bool ConstexprOnly) { 17673 // Mark all functions which will appear in RD's vtable as used. 17674 CXXFinalOverriderMap FinalOverriders; 17675 RD->getFinalOverriders(FinalOverriders); 17676 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 17677 E = FinalOverriders.end(); 17678 I != E; ++I) { 17679 for (OverridingMethods::const_iterator OI = I->second.begin(), 17680 OE = I->second.end(); 17681 OI != OE; ++OI) { 17682 assert(OI->second.size() > 0 && "no final overrider"); 17683 CXXMethodDecl *Overrider = OI->second.front().Method; 17684 17685 // C++ [basic.def.odr]p2: 17686 // [...] A virtual member function is used if it is not pure. [...] 17687 if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr())) 17688 MarkFunctionReferenced(Loc, Overrider); 17689 } 17690 } 17691 17692 // Only classes that have virtual bases need a VTT. 17693 if (RD->getNumVBases() == 0) 17694 return; 17695 17696 for (const auto &I : RD->bases()) { 17697 const auto *Base = 17698 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 17699 if (Base->getNumVBases() == 0) 17700 continue; 17701 MarkVirtualMembersReferenced(Loc, Base); 17702 } 17703 } 17704 17705 /// SetIvarInitializers - This routine builds initialization ASTs for the 17706 /// Objective-C implementation whose ivars need be initialized. 17707 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 17708 if (!getLangOpts().CPlusPlus) 17709 return; 17710 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 17711 SmallVector<ObjCIvarDecl*, 8> ivars; 17712 CollectIvarsToConstructOrDestruct(OID, ivars); 17713 if (ivars.empty()) 17714 return; 17715 SmallVector<CXXCtorInitializer*, 32> AllToInit; 17716 for (unsigned i = 0; i < ivars.size(); i++) { 17717 FieldDecl *Field = ivars[i]; 17718 if (Field->isInvalidDecl()) 17719 continue; 17720 17721 CXXCtorInitializer *Member; 17722 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 17723 InitializationKind InitKind = 17724 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 17725 17726 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 17727 ExprResult MemberInit = 17728 InitSeq.Perform(*this, InitEntity, InitKind, None); 17729 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 17730 // Note, MemberInit could actually come back empty if no initialization 17731 // is required (e.g., because it would call a trivial default constructor) 17732 if (!MemberInit.get() || MemberInit.isInvalid()) 17733 continue; 17734 17735 Member = 17736 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 17737 SourceLocation(), 17738 MemberInit.getAs<Expr>(), 17739 SourceLocation()); 17740 AllToInit.push_back(Member); 17741 17742 // Be sure that the destructor is accessible and is marked as referenced. 17743 if (const RecordType *RecordTy = 17744 Context.getBaseElementType(Field->getType()) 17745 ->getAs<RecordType>()) { 17746 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 17747 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 17748 MarkFunctionReferenced(Field->getLocation(), Destructor); 17749 CheckDestructorAccess(Field->getLocation(), Destructor, 17750 PDiag(diag::err_access_dtor_ivar) 17751 << Context.getBaseElementType(Field->getType())); 17752 } 17753 } 17754 } 17755 ObjCImplementation->setIvarInitializers(Context, 17756 AllToInit.data(), AllToInit.size()); 17757 } 17758 } 17759 17760 static 17761 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 17762 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid, 17763 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid, 17764 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current, 17765 Sema &S) { 17766 if (Ctor->isInvalidDecl()) 17767 return; 17768 17769 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 17770 17771 // Target may not be determinable yet, for instance if this is a dependent 17772 // call in an uninstantiated template. 17773 if (Target) { 17774 const FunctionDecl *FNTarget = nullptr; 17775 (void)Target->hasBody(FNTarget); 17776 Target = const_cast<CXXConstructorDecl*>( 17777 cast_or_null<CXXConstructorDecl>(FNTarget)); 17778 } 17779 17780 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 17781 // Avoid dereferencing a null pointer here. 17782 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 17783 17784 if (!Current.insert(Canonical).second) 17785 return; 17786 17787 // We know that beyond here, we aren't chaining into a cycle. 17788 if (!Target || !Target->isDelegatingConstructor() || 17789 Target->isInvalidDecl() || Valid.count(TCanonical)) { 17790 Valid.insert(Current.begin(), Current.end()); 17791 Current.clear(); 17792 // We've hit a cycle. 17793 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 17794 Current.count(TCanonical)) { 17795 // If we haven't diagnosed this cycle yet, do so now. 17796 if (!Invalid.count(TCanonical)) { 17797 S.Diag((*Ctor->init_begin())->getSourceLocation(), 17798 diag::warn_delegating_ctor_cycle) 17799 << Ctor; 17800 17801 // Don't add a note for a function delegating directly to itself. 17802 if (TCanonical != Canonical) 17803 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 17804 17805 CXXConstructorDecl *C = Target; 17806 while (C->getCanonicalDecl() != Canonical) { 17807 const FunctionDecl *FNTarget = nullptr; 17808 (void)C->getTargetConstructor()->hasBody(FNTarget); 17809 assert(FNTarget && "Ctor cycle through bodiless function"); 17810 17811 C = const_cast<CXXConstructorDecl*>( 17812 cast<CXXConstructorDecl>(FNTarget)); 17813 S.Diag(C->getLocation(), diag::note_which_delegates_to); 17814 } 17815 } 17816 17817 Invalid.insert(Current.begin(), Current.end()); 17818 Current.clear(); 17819 } else { 17820 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 17821 } 17822 } 17823 17824 17825 void Sema::CheckDelegatingCtorCycles() { 17826 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 17827 17828 for (DelegatingCtorDeclsType::iterator 17829 I = DelegatingCtorDecls.begin(ExternalSource), 17830 E = DelegatingCtorDecls.end(); 17831 I != E; ++I) 17832 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 17833 17834 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI) 17835 (*CI)->setInvalidDecl(); 17836 } 17837 17838 namespace { 17839 /// AST visitor that finds references to the 'this' expression. 17840 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 17841 Sema &S; 17842 17843 public: 17844 explicit FindCXXThisExpr(Sema &S) : S(S) { } 17845 17846 bool VisitCXXThisExpr(CXXThisExpr *E) { 17847 S.Diag(E->getLocation(), diag::err_this_static_member_func) 17848 << E->isImplicit(); 17849 return false; 17850 } 17851 }; 17852 } 17853 17854 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 17855 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 17856 if (!TSInfo) 17857 return false; 17858 17859 TypeLoc TL = TSInfo->getTypeLoc(); 17860 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 17861 if (!ProtoTL) 17862 return false; 17863 17864 // C++11 [expr.prim.general]p3: 17865 // [The expression this] shall not appear before the optional 17866 // cv-qualifier-seq and it shall not appear within the declaration of a 17867 // static member function (although its type and value category are defined 17868 // within a static member function as they are within a non-static member 17869 // function). [ Note: this is because declaration matching does not occur 17870 // until the complete declarator is known. - end note ] 17871 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 17872 FindCXXThisExpr Finder(*this); 17873 17874 // If the return type came after the cv-qualifier-seq, check it now. 17875 if (Proto->hasTrailingReturn() && 17876 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 17877 return true; 17878 17879 // Check the exception specification. 17880 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 17881 return true; 17882 17883 // Check the trailing requires clause 17884 if (Expr *E = Method->getTrailingRequiresClause()) 17885 if (!Finder.TraverseStmt(E)) 17886 return true; 17887 17888 return checkThisInStaticMemberFunctionAttributes(Method); 17889 } 17890 17891 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 17892 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 17893 if (!TSInfo) 17894 return false; 17895 17896 TypeLoc TL = TSInfo->getTypeLoc(); 17897 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 17898 if (!ProtoTL) 17899 return false; 17900 17901 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 17902 FindCXXThisExpr Finder(*this); 17903 17904 switch (Proto->getExceptionSpecType()) { 17905 case EST_Unparsed: 17906 case EST_Uninstantiated: 17907 case EST_Unevaluated: 17908 case EST_BasicNoexcept: 17909 case EST_NoThrow: 17910 case EST_DynamicNone: 17911 case EST_MSAny: 17912 case EST_None: 17913 break; 17914 17915 case EST_DependentNoexcept: 17916 case EST_NoexceptFalse: 17917 case EST_NoexceptTrue: 17918 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 17919 return true; 17920 LLVM_FALLTHROUGH; 17921 17922 case EST_Dynamic: 17923 for (const auto &E : Proto->exceptions()) { 17924 if (!Finder.TraverseType(E)) 17925 return true; 17926 } 17927 break; 17928 } 17929 17930 return false; 17931 } 17932 17933 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 17934 FindCXXThisExpr Finder(*this); 17935 17936 // Check attributes. 17937 for (const auto *A : Method->attrs()) { 17938 // FIXME: This should be emitted by tblgen. 17939 Expr *Arg = nullptr; 17940 ArrayRef<Expr *> Args; 17941 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 17942 Arg = G->getArg(); 17943 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 17944 Arg = G->getArg(); 17945 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 17946 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 17947 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 17948 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 17949 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 17950 Arg = ETLF->getSuccessValue(); 17951 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 17952 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 17953 Arg = STLF->getSuccessValue(); 17954 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 17955 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 17956 Arg = LR->getArg(); 17957 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 17958 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 17959 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 17960 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 17961 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 17962 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 17963 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 17964 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 17965 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 17966 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 17967 17968 if (Arg && !Finder.TraverseStmt(Arg)) 17969 return true; 17970 17971 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 17972 if (!Finder.TraverseStmt(Args[I])) 17973 return true; 17974 } 17975 } 17976 17977 return false; 17978 } 17979 17980 void Sema::checkExceptionSpecification( 17981 bool IsTopLevel, ExceptionSpecificationType EST, 17982 ArrayRef<ParsedType> DynamicExceptions, 17983 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 17984 SmallVectorImpl<QualType> &Exceptions, 17985 FunctionProtoType::ExceptionSpecInfo &ESI) { 17986 Exceptions.clear(); 17987 ESI.Type = EST; 17988 if (EST == EST_Dynamic) { 17989 Exceptions.reserve(DynamicExceptions.size()); 17990 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 17991 // FIXME: Preserve type source info. 17992 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 17993 17994 if (IsTopLevel) { 17995 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 17996 collectUnexpandedParameterPacks(ET, Unexpanded); 17997 if (!Unexpanded.empty()) { 17998 DiagnoseUnexpandedParameterPacks( 17999 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 18000 Unexpanded); 18001 continue; 18002 } 18003 } 18004 18005 // Check that the type is valid for an exception spec, and 18006 // drop it if not. 18007 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 18008 Exceptions.push_back(ET); 18009 } 18010 ESI.Exceptions = Exceptions; 18011 return; 18012 } 18013 18014 if (isComputedNoexcept(EST)) { 18015 assert((NoexceptExpr->isTypeDependent() || 18016 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 18017 Context.BoolTy) && 18018 "Parser should have made sure that the expression is boolean"); 18019 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 18020 ESI.Type = EST_BasicNoexcept; 18021 return; 18022 } 18023 18024 ESI.NoexceptExpr = NoexceptExpr; 18025 return; 18026 } 18027 } 18028 18029 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 18030 ExceptionSpecificationType EST, 18031 SourceRange SpecificationRange, 18032 ArrayRef<ParsedType> DynamicExceptions, 18033 ArrayRef<SourceRange> DynamicExceptionRanges, 18034 Expr *NoexceptExpr) { 18035 if (!MethodD) 18036 return; 18037 18038 // Dig out the method we're referring to. 18039 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 18040 MethodD = FunTmpl->getTemplatedDecl(); 18041 18042 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 18043 if (!Method) 18044 return; 18045 18046 // Check the exception specification. 18047 llvm::SmallVector<QualType, 4> Exceptions; 18048 FunctionProtoType::ExceptionSpecInfo ESI; 18049 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 18050 DynamicExceptionRanges, NoexceptExpr, Exceptions, 18051 ESI); 18052 18053 // Update the exception specification on the function type. 18054 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 18055 18056 if (Method->isStatic()) 18057 checkThisInStaticMemberFunctionExceptionSpec(Method); 18058 18059 if (Method->isVirtual()) { 18060 // Check overrides, which we previously had to delay. 18061 for (const CXXMethodDecl *O : Method->overridden_methods()) 18062 CheckOverridingFunctionExceptionSpec(Method, O); 18063 } 18064 } 18065 18066 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 18067 /// 18068 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 18069 SourceLocation DeclStart, Declarator &D, 18070 Expr *BitWidth, 18071 InClassInitStyle InitStyle, 18072 AccessSpecifier AS, 18073 const ParsedAttr &MSPropertyAttr) { 18074 IdentifierInfo *II = D.getIdentifier(); 18075 if (!II) { 18076 Diag(DeclStart, diag::err_anonymous_property); 18077 return nullptr; 18078 } 18079 SourceLocation Loc = D.getIdentifierLoc(); 18080 18081 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 18082 QualType T = TInfo->getType(); 18083 if (getLangOpts().CPlusPlus) { 18084 CheckExtraCXXDefaultArguments(D); 18085 18086 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 18087 UPPC_DataMemberType)) { 18088 D.setInvalidType(); 18089 T = Context.IntTy; 18090 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 18091 } 18092 } 18093 18094 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 18095 18096 if (D.getDeclSpec().isInlineSpecified()) 18097 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 18098 << getLangOpts().CPlusPlus17; 18099 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 18100 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 18101 diag::err_invalid_thread) 18102 << DeclSpec::getSpecifierName(TSCS); 18103 18104 // Check to see if this name was declared as a member previously 18105 NamedDecl *PrevDecl = nullptr; 18106 LookupResult Previous(*this, II, Loc, LookupMemberName, 18107 ForVisibleRedeclaration); 18108 LookupName(Previous, S); 18109 switch (Previous.getResultKind()) { 18110 case LookupResult::Found: 18111 case LookupResult::FoundUnresolvedValue: 18112 PrevDecl = Previous.getAsSingle<NamedDecl>(); 18113 break; 18114 18115 case LookupResult::FoundOverloaded: 18116 PrevDecl = Previous.getRepresentativeDecl(); 18117 break; 18118 18119 case LookupResult::NotFound: 18120 case LookupResult::NotFoundInCurrentInstantiation: 18121 case LookupResult::Ambiguous: 18122 break; 18123 } 18124 18125 if (PrevDecl && PrevDecl->isTemplateParameter()) { 18126 // Maybe we will complain about the shadowed template parameter. 18127 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 18128 // Just pretend that we didn't see the previous declaration. 18129 PrevDecl = nullptr; 18130 } 18131 18132 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 18133 PrevDecl = nullptr; 18134 18135 SourceLocation TSSL = D.getBeginLoc(); 18136 MSPropertyDecl *NewPD = 18137 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL, 18138 MSPropertyAttr.getPropertyDataGetter(), 18139 MSPropertyAttr.getPropertyDataSetter()); 18140 ProcessDeclAttributes(TUScope, NewPD, D); 18141 NewPD->setAccess(AS); 18142 18143 if (NewPD->isInvalidDecl()) 18144 Record->setInvalidDecl(); 18145 18146 if (D.getDeclSpec().isModulePrivateSpecified()) 18147 NewPD->setModulePrivate(); 18148 18149 if (NewPD->isInvalidDecl() && PrevDecl) { 18150 // Don't introduce NewFD into scope; there's already something 18151 // with the same name in the same scope. 18152 } else if (II) { 18153 PushOnScopeChains(NewPD, S); 18154 } else 18155 Record->addDecl(NewPD); 18156 18157 return NewPD; 18158 } 18159 18160 void Sema::ActOnStartFunctionDeclarationDeclarator( 18161 Declarator &Declarator, unsigned TemplateParameterDepth) { 18162 auto &Info = InventedParameterInfos.emplace_back(); 18163 TemplateParameterList *ExplicitParams = nullptr; 18164 ArrayRef<TemplateParameterList *> ExplicitLists = 18165 Declarator.getTemplateParameterLists(); 18166 if (!ExplicitLists.empty()) { 18167 bool IsMemberSpecialization, IsInvalid; 18168 ExplicitParams = MatchTemplateParametersToScopeSpecifier( 18169 Declarator.getBeginLoc(), Declarator.getIdentifierLoc(), 18170 Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr, 18171 ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid, 18172 /*SuppressDiagnostic=*/true); 18173 } 18174 if (ExplicitParams) { 18175 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth(); 18176 for (NamedDecl *Param : *ExplicitParams) 18177 Info.TemplateParams.push_back(Param); 18178 Info.NumExplicitTemplateParams = ExplicitParams->size(); 18179 } else { 18180 Info.AutoTemplateParameterDepth = TemplateParameterDepth; 18181 Info.NumExplicitTemplateParams = 0; 18182 } 18183 } 18184 18185 void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) { 18186 auto &FSI = InventedParameterInfos.back(); 18187 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) { 18188 if (FSI.NumExplicitTemplateParams != 0) { 18189 TemplateParameterList *ExplicitParams = 18190 Declarator.getTemplateParameterLists().back(); 18191 Declarator.setInventedTemplateParameterList( 18192 TemplateParameterList::Create( 18193 Context, ExplicitParams->getTemplateLoc(), 18194 ExplicitParams->getLAngleLoc(), FSI.TemplateParams, 18195 ExplicitParams->getRAngleLoc(), 18196 ExplicitParams->getRequiresClause())); 18197 } else { 18198 Declarator.setInventedTemplateParameterList( 18199 TemplateParameterList::Create( 18200 Context, SourceLocation(), SourceLocation(), FSI.TemplateParams, 18201 SourceLocation(), /*RequiresClause=*/nullptr)); 18202 } 18203 } 18204 InventedParameterInfos.pop_back(); 18205 } 18206