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 if (NewBaseType->isDependentType()) 2733 continue; 2734 // Note this base's direct & indirect bases, if there could be ambiguity. 2735 if (Bases.size() > 1) 2736 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType); 2737 2738 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 2739 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 2740 if (Class->isInterface() && 2741 (!RD->isInterfaceLike() || 2742 KnownBase->getAccessSpecifier() != AS_public)) { 2743 // The Microsoft extension __interface does not permit bases that 2744 // are not themselves public interfaces. 2745 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface) 2746 << getRecordDiagFromTagKind(RD->getTagKind()) << RD 2747 << RD->getSourceRange(); 2748 Invalid = true; 2749 } 2750 if (RD->hasAttr<WeakAttr>()) 2751 Class->addAttr(WeakAttr::CreateImplicit(Context)); 2752 } 2753 } 2754 } 2755 2756 // Attach the remaining base class specifiers to the derived class. 2757 Class->setBases(Bases.data(), NumGoodBases); 2758 2759 // Check that the only base classes that are duplicate are virtual. 2760 for (unsigned idx = 0; idx < NumGoodBases; ++idx) { 2761 // Check whether this direct base is inaccessible due to ambiguity. 2762 QualType BaseType = Bases[idx]->getType(); 2763 2764 // Skip all dependent types in templates being used as base specifiers. 2765 // Checks below assume that the base specifier is a CXXRecord. 2766 if (BaseType->isDependentType()) 2767 continue; 2768 2769 CanQualType CanonicalBase = Context.getCanonicalType(BaseType) 2770 .getUnqualifiedType(); 2771 2772 if (IndirectBaseTypes.count(CanonicalBase)) { 2773 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2774 /*DetectVirtual=*/true); 2775 bool found 2776 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); 2777 assert(found); 2778 (void)found; 2779 2780 if (Paths.isAmbiguous(CanonicalBase)) 2781 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class) 2782 << BaseType << getAmbiguousPathsDisplayString(Paths) 2783 << Bases[idx]->getSourceRange(); 2784 else 2785 assert(Bases[idx]->isVirtual()); 2786 } 2787 2788 // Delete the base class specifier, since its data has been copied 2789 // into the CXXRecordDecl. 2790 Context.Deallocate(Bases[idx]); 2791 } 2792 2793 return Invalid; 2794 } 2795 2796 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 2797 /// class, after checking whether there are any duplicate base 2798 /// classes. 2799 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, 2800 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2801 if (!ClassDecl || Bases.empty()) 2802 return; 2803 2804 AdjustDeclIfTemplate(ClassDecl); 2805 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases); 2806 } 2807 2808 /// Determine whether the type \p Derived is a C++ class that is 2809 /// derived from the type \p Base. 2810 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) { 2811 if (!getLangOpts().CPlusPlus) 2812 return false; 2813 2814 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2815 if (!DerivedRD) 2816 return false; 2817 2818 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2819 if (!BaseRD) 2820 return false; 2821 2822 // If either the base or the derived type is invalid, don't try to 2823 // check whether one is derived from the other. 2824 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 2825 return false; 2826 2827 // FIXME: In a modules build, do we need the entire path to be visible for us 2828 // to be able to use the inheritance relationship? 2829 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2830 return false; 2831 2832 return DerivedRD->isDerivedFrom(BaseRD); 2833 } 2834 2835 /// Determine whether the type \p Derived is a C++ class that is 2836 /// derived from the type \p Base. 2837 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, 2838 CXXBasePaths &Paths) { 2839 if (!getLangOpts().CPlusPlus) 2840 return false; 2841 2842 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2843 if (!DerivedRD) 2844 return false; 2845 2846 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2847 if (!BaseRD) 2848 return false; 2849 2850 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2851 return false; 2852 2853 return DerivedRD->isDerivedFrom(BaseRD, Paths); 2854 } 2855 2856 static void BuildBasePathArray(const CXXBasePath &Path, 2857 CXXCastPath &BasePathArray) { 2858 // We first go backward and check if we have a virtual base. 2859 // FIXME: It would be better if CXXBasePath had the base specifier for 2860 // the nearest virtual base. 2861 unsigned Start = 0; 2862 for (unsigned I = Path.size(); I != 0; --I) { 2863 if (Path[I - 1].Base->isVirtual()) { 2864 Start = I - 1; 2865 break; 2866 } 2867 } 2868 2869 // Now add all bases. 2870 for (unsigned I = Start, E = Path.size(); I != E; ++I) 2871 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 2872 } 2873 2874 2875 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 2876 CXXCastPath &BasePathArray) { 2877 assert(BasePathArray.empty() && "Base path array must be empty!"); 2878 assert(Paths.isRecordingPaths() && "Must record paths!"); 2879 return ::BuildBasePathArray(Paths.front(), BasePathArray); 2880 } 2881 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 2882 /// conversion (where Derived and Base are class types) is 2883 /// well-formed, meaning that the conversion is unambiguous (and 2884 /// that all of the base classes are accessible). Returns true 2885 /// and emits a diagnostic if the code is ill-formed, returns false 2886 /// otherwise. Loc is the location where this routine should point to 2887 /// if there is an error, and Range is the source range to highlight 2888 /// if there is an error. 2889 /// 2890 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the 2891 /// diagnostic for the respective type of error will be suppressed, but the 2892 /// check for ill-formed code will still be performed. 2893 bool 2894 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2895 unsigned InaccessibleBaseID, 2896 unsigned AmbiguousBaseConvID, 2897 SourceLocation Loc, SourceRange Range, 2898 DeclarationName Name, 2899 CXXCastPath *BasePath, 2900 bool IgnoreAccess) { 2901 // First, determine whether the path from Derived to Base is 2902 // ambiguous. This is slightly more expensive than checking whether 2903 // the Derived to Base conversion exists, because here we need to 2904 // explore multiple paths to determine if there is an ambiguity. 2905 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2906 /*DetectVirtual=*/false); 2907 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2908 if (!DerivationOkay) 2909 return true; 2910 2911 const CXXBasePath *Path = nullptr; 2912 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) 2913 Path = &Paths.front(); 2914 2915 // For MSVC compatibility, check if Derived directly inherits from Base. Clang 2916 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the 2917 // user to access such bases. 2918 if (!Path && getLangOpts().MSVCCompat) { 2919 for (const CXXBasePath &PossiblePath : Paths) { 2920 if (PossiblePath.size() == 1) { 2921 Path = &PossiblePath; 2922 if (AmbiguousBaseConvID) 2923 Diag(Loc, diag::ext_ms_ambiguous_direct_base) 2924 << Base << Derived << Range; 2925 break; 2926 } 2927 } 2928 } 2929 2930 if (Path) { 2931 if (!IgnoreAccess) { 2932 // Check that the base class can be accessed. 2933 switch ( 2934 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) { 2935 case AR_inaccessible: 2936 return true; 2937 case AR_accessible: 2938 case AR_dependent: 2939 case AR_delayed: 2940 break; 2941 } 2942 } 2943 2944 // Build a base path if necessary. 2945 if (BasePath) 2946 ::BuildBasePathArray(*Path, *BasePath); 2947 return false; 2948 } 2949 2950 if (AmbiguousBaseConvID) { 2951 // We know that the derived-to-base conversion is ambiguous, and 2952 // we're going to produce a diagnostic. Perform the derived-to-base 2953 // search just one more time to compute all of the possible paths so 2954 // that we can print them out. This is more expensive than any of 2955 // the previous derived-to-base checks we've done, but at this point 2956 // performance isn't as much of an issue. 2957 Paths.clear(); 2958 Paths.setRecordingPaths(true); 2959 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2960 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 2961 (void)StillOkay; 2962 2963 // Build up a textual representation of the ambiguous paths, e.g., 2964 // D -> B -> A, that will be used to illustrate the ambiguous 2965 // conversions in the diagnostic. We only print one of the paths 2966 // to each base class subobject. 2967 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2968 2969 Diag(Loc, AmbiguousBaseConvID) 2970 << Derived << Base << PathDisplayStr << Range << Name; 2971 } 2972 return true; 2973 } 2974 2975 bool 2976 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2977 SourceLocation Loc, SourceRange Range, 2978 CXXCastPath *BasePath, 2979 bool IgnoreAccess) { 2980 return CheckDerivedToBaseConversion( 2981 Derived, Base, diag::err_upcast_to_inaccessible_base, 2982 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(), 2983 BasePath, IgnoreAccess); 2984 } 2985 2986 2987 /// Builds a string representing ambiguous paths from a 2988 /// specific derived class to different subobjects of the same base 2989 /// class. 2990 /// 2991 /// This function builds a string that can be used in error messages 2992 /// to show the different paths that one can take through the 2993 /// inheritance hierarchy to go from the derived class to different 2994 /// subobjects of a base class. The result looks something like this: 2995 /// @code 2996 /// struct D -> struct B -> struct A 2997 /// struct D -> struct C -> struct A 2998 /// @endcode 2999 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 3000 std::string PathDisplayStr; 3001 std::set<unsigned> DisplayedPaths; 3002 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 3003 Path != Paths.end(); ++Path) { 3004 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 3005 // We haven't displayed a path to this particular base 3006 // class subobject yet. 3007 PathDisplayStr += "\n "; 3008 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 3009 for (CXXBasePath::const_iterator Element = Path->begin(); 3010 Element != Path->end(); ++Element) 3011 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 3012 } 3013 } 3014 3015 return PathDisplayStr; 3016 } 3017 3018 //===----------------------------------------------------------------------===// 3019 // C++ class member Handling 3020 //===----------------------------------------------------------------------===// 3021 3022 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 3023 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, 3024 SourceLocation ColonLoc, 3025 const ParsedAttributesView &Attrs) { 3026 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 3027 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 3028 ASLoc, ColonLoc); 3029 CurContext->addHiddenDecl(ASDecl); 3030 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 3031 } 3032 3033 /// CheckOverrideControl - Check C++11 override control semantics. 3034 void Sema::CheckOverrideControl(NamedDecl *D) { 3035 if (D->isInvalidDecl()) 3036 return; 3037 3038 // We only care about "override" and "final" declarations. 3039 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 3040 return; 3041 3042 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 3043 3044 // We can't check dependent instance methods. 3045 if (MD && MD->isInstance() && 3046 (MD->getParent()->hasAnyDependentBases() || 3047 MD->getType()->isDependentType())) 3048 return; 3049 3050 if (MD && !MD->isVirtual()) { 3051 // If we have a non-virtual method, check if if hides a virtual method. 3052 // (In that case, it's most likely the method has the wrong type.) 3053 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 3054 FindHiddenVirtualMethods(MD, OverloadedMethods); 3055 3056 if (!OverloadedMethods.empty()) { 3057 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 3058 Diag(OA->getLocation(), 3059 diag::override_keyword_hides_virtual_member_function) 3060 << "override" << (OverloadedMethods.size() > 1); 3061 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 3062 Diag(FA->getLocation(), 3063 diag::override_keyword_hides_virtual_member_function) 3064 << (FA->isSpelledAsSealed() ? "sealed" : "final") 3065 << (OverloadedMethods.size() > 1); 3066 } 3067 NoteHiddenVirtualMethods(MD, OverloadedMethods); 3068 MD->setInvalidDecl(); 3069 return; 3070 } 3071 // Fall through into the general case diagnostic. 3072 // FIXME: We might want to attempt typo correction here. 3073 } 3074 3075 if (!MD || !MD->isVirtual()) { 3076 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 3077 Diag(OA->getLocation(), 3078 diag::override_keyword_only_allowed_on_virtual_member_functions) 3079 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 3080 D->dropAttr<OverrideAttr>(); 3081 } 3082 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 3083 Diag(FA->getLocation(), 3084 diag::override_keyword_only_allowed_on_virtual_member_functions) 3085 << (FA->isSpelledAsSealed() ? "sealed" : "final") 3086 << FixItHint::CreateRemoval(FA->getLocation()); 3087 D->dropAttr<FinalAttr>(); 3088 } 3089 return; 3090 } 3091 3092 // C++11 [class.virtual]p5: 3093 // If a function is marked with the virt-specifier override and 3094 // does not override a member function of a base class, the program is 3095 // ill-formed. 3096 bool HasOverriddenMethods = MD->size_overridden_methods() != 0; 3097 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 3098 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 3099 << MD->getDeclName(); 3100 } 3101 3102 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) { 3103 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) 3104 return; 3105 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 3106 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>()) 3107 return; 3108 3109 SourceLocation Loc = MD->getLocation(); 3110 SourceLocation SpellingLoc = Loc; 3111 if (getSourceManager().isMacroArgExpansion(Loc)) 3112 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin(); 3113 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); 3114 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) 3115 return; 3116 3117 if (MD->size_overridden_methods() > 0) { 3118 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) { 3119 unsigned DiagID = 3120 Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation()) 3121 ? DiagInconsistent 3122 : DiagSuggest; 3123 Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 3124 const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); 3125 Diag(OMD->getLocation(), diag::note_overridden_virtual_function); 3126 }; 3127 if (isa<CXXDestructorDecl>(MD)) 3128 EmitDiag( 3129 diag::warn_inconsistent_destructor_marked_not_override_overriding, 3130 diag::warn_suggest_destructor_marked_not_override_overriding); 3131 else 3132 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding, 3133 diag::warn_suggest_function_marked_not_override_overriding); 3134 } 3135 } 3136 3137 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 3138 /// function overrides a virtual member function marked 'final', according to 3139 /// C++11 [class.virtual]p4. 3140 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 3141 const CXXMethodDecl *Old) { 3142 FinalAttr *FA = Old->getAttr<FinalAttr>(); 3143 if (!FA) 3144 return false; 3145 3146 Diag(New->getLocation(), diag::err_final_function_overridden) 3147 << New->getDeclName() 3148 << FA->isSpelledAsSealed(); 3149 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 3150 return true; 3151 } 3152 3153 static bool InitializationHasSideEffects(const FieldDecl &FD) { 3154 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 3155 // FIXME: Destruction of ObjC lifetime types has side-effects. 3156 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 3157 return !RD->isCompleteDefinition() || 3158 !RD->hasTrivialDefaultConstructor() || 3159 !RD->hasTrivialDestructor(); 3160 return false; 3161 } 3162 3163 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) { 3164 ParsedAttributesView::const_iterator Itr = 3165 llvm::find_if(list, [](const ParsedAttr &AL) { 3166 return AL.isDeclspecPropertyAttribute(); 3167 }); 3168 if (Itr != list.end()) 3169 return &*Itr; 3170 return nullptr; 3171 } 3172 3173 // Check if there is a field shadowing. 3174 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc, 3175 DeclarationName FieldName, 3176 const CXXRecordDecl *RD, 3177 bool DeclIsField) { 3178 if (Diags.isIgnored(diag::warn_shadow_field, Loc)) 3179 return; 3180 3181 // To record a shadowed field in a base 3182 std::map<CXXRecordDecl*, NamedDecl*> Bases; 3183 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier, 3184 CXXBasePath &Path) { 3185 const auto Base = Specifier->getType()->getAsCXXRecordDecl(); 3186 // Record an ambiguous path directly 3187 if (Bases.find(Base) != Bases.end()) 3188 return true; 3189 for (const auto Field : Base->lookup(FieldName)) { 3190 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) && 3191 Field->getAccess() != AS_private) { 3192 assert(Field->getAccess() != AS_none); 3193 assert(Bases.find(Base) == Bases.end()); 3194 Bases[Base] = Field; 3195 return true; 3196 } 3197 } 3198 return false; 3199 }; 3200 3201 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3202 /*DetectVirtual=*/true); 3203 if (!RD->lookupInBases(FieldShadowed, Paths)) 3204 return; 3205 3206 for (const auto &P : Paths) { 3207 auto Base = P.back().Base->getType()->getAsCXXRecordDecl(); 3208 auto It = Bases.find(Base); 3209 // Skip duplicated bases 3210 if (It == Bases.end()) 3211 continue; 3212 auto BaseField = It->second; 3213 assert(BaseField->getAccess() != AS_private); 3214 if (AS_none != 3215 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) { 3216 Diag(Loc, diag::warn_shadow_field) 3217 << FieldName << RD << Base << DeclIsField; 3218 Diag(BaseField->getLocation(), diag::note_shadow_field); 3219 Bases.erase(It); 3220 } 3221 } 3222 } 3223 3224 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 3225 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 3226 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 3227 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 3228 /// present (but parsing it has been deferred). 3229 NamedDecl * 3230 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 3231 MultiTemplateParamsArg TemplateParameterLists, 3232 Expr *BW, const VirtSpecifiers &VS, 3233 InClassInitStyle InitStyle) { 3234 const DeclSpec &DS = D.getDeclSpec(); 3235 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 3236 DeclarationName Name = NameInfo.getName(); 3237 SourceLocation Loc = NameInfo.getLoc(); 3238 3239 // For anonymous bitfields, the location should point to the type. 3240 if (Loc.isInvalid()) 3241 Loc = D.getBeginLoc(); 3242 3243 Expr *BitWidth = static_cast<Expr*>(BW); 3244 3245 assert(isa<CXXRecordDecl>(CurContext)); 3246 assert(!DS.isFriendSpecified()); 3247 3248 bool isFunc = D.isDeclarationOfFunction(); 3249 const ParsedAttr *MSPropertyAttr = 3250 getMSPropertyAttr(D.getDeclSpec().getAttributes()); 3251 3252 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 3253 // The Microsoft extension __interface only permits public member functions 3254 // and prohibits constructors, destructors, operators, non-public member 3255 // functions, static methods and data members. 3256 unsigned InvalidDecl; 3257 bool ShowDeclName = true; 3258 if (!isFunc && 3259 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr)) 3260 InvalidDecl = 0; 3261 else if (!isFunc) 3262 InvalidDecl = 1; 3263 else if (AS != AS_public) 3264 InvalidDecl = 2; 3265 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 3266 InvalidDecl = 3; 3267 else switch (Name.getNameKind()) { 3268 case DeclarationName::CXXConstructorName: 3269 InvalidDecl = 4; 3270 ShowDeclName = false; 3271 break; 3272 3273 case DeclarationName::CXXDestructorName: 3274 InvalidDecl = 5; 3275 ShowDeclName = false; 3276 break; 3277 3278 case DeclarationName::CXXOperatorName: 3279 case DeclarationName::CXXConversionFunctionName: 3280 InvalidDecl = 6; 3281 break; 3282 3283 default: 3284 InvalidDecl = 0; 3285 break; 3286 } 3287 3288 if (InvalidDecl) { 3289 if (ShowDeclName) 3290 Diag(Loc, diag::err_invalid_member_in_interface) 3291 << (InvalidDecl-1) << Name; 3292 else 3293 Diag(Loc, diag::err_invalid_member_in_interface) 3294 << (InvalidDecl-1) << ""; 3295 return nullptr; 3296 } 3297 } 3298 3299 // C++ 9.2p6: A member shall not be declared to have automatic storage 3300 // duration (auto, register) or with the extern storage-class-specifier. 3301 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 3302 // data members and cannot be applied to names declared const or static, 3303 // and cannot be applied to reference members. 3304 switch (DS.getStorageClassSpec()) { 3305 case DeclSpec::SCS_unspecified: 3306 case DeclSpec::SCS_typedef: 3307 case DeclSpec::SCS_static: 3308 break; 3309 case DeclSpec::SCS_mutable: 3310 if (isFunc) { 3311 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 3312 3313 // FIXME: It would be nicer if the keyword was ignored only for this 3314 // declarator. Otherwise we could get follow-up errors. 3315 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3316 } 3317 break; 3318 default: 3319 Diag(DS.getStorageClassSpecLoc(), 3320 diag::err_storageclass_invalid_for_member); 3321 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3322 break; 3323 } 3324 3325 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 3326 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 3327 !isFunc); 3328 3329 if (DS.hasConstexprSpecifier() && isInstField) { 3330 SemaDiagnosticBuilder B = 3331 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 3332 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 3333 if (InitStyle == ICIS_NoInit) { 3334 B << 0 << 0; 3335 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 3336 B << FixItHint::CreateRemoval(ConstexprLoc); 3337 else { 3338 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 3339 D.getMutableDeclSpec().ClearConstexprSpec(); 3340 const char *PrevSpec; 3341 unsigned DiagID; 3342 bool Failed = D.getMutableDeclSpec().SetTypeQual( 3343 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 3344 (void)Failed; 3345 assert(!Failed && "Making a constexpr member const shouldn't fail"); 3346 } 3347 } else { 3348 B << 1; 3349 const char *PrevSpec; 3350 unsigned DiagID; 3351 if (D.getMutableDeclSpec().SetStorageClassSpec( 3352 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 3353 Context.getPrintingPolicy())) { 3354 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 3355 "This is the only DeclSpec that should fail to be applied"); 3356 B << 1; 3357 } else { 3358 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 3359 isInstField = false; 3360 } 3361 } 3362 } 3363 3364 NamedDecl *Member; 3365 if (isInstField) { 3366 CXXScopeSpec &SS = D.getCXXScopeSpec(); 3367 3368 // Data members must have identifiers for names. 3369 if (!Name.isIdentifier()) { 3370 Diag(Loc, diag::err_bad_variable_name) 3371 << Name; 3372 return nullptr; 3373 } 3374 3375 IdentifierInfo *II = Name.getAsIdentifierInfo(); 3376 3377 // Member field could not be with "template" keyword. 3378 // So TemplateParameterLists should be empty in this case. 3379 if (TemplateParameterLists.size()) { 3380 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 3381 if (TemplateParams->size()) { 3382 // There is no such thing as a member field template. 3383 Diag(D.getIdentifierLoc(), diag::err_template_member) 3384 << II 3385 << SourceRange(TemplateParams->getTemplateLoc(), 3386 TemplateParams->getRAngleLoc()); 3387 } else { 3388 // There is an extraneous 'template<>' for this member. 3389 Diag(TemplateParams->getTemplateLoc(), 3390 diag::err_template_member_noparams) 3391 << II 3392 << SourceRange(TemplateParams->getTemplateLoc(), 3393 TemplateParams->getRAngleLoc()); 3394 } 3395 return nullptr; 3396 } 3397 3398 if (SS.isSet() && !SS.isInvalid()) { 3399 // The user provided a superfluous scope specifier inside a class 3400 // definition: 3401 // 3402 // class X { 3403 // int X::member; 3404 // }; 3405 if (DeclContext *DC = computeDeclContext(SS, false)) 3406 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(), 3407 D.getName().getKind() == 3408 UnqualifiedIdKind::IK_TemplateId); 3409 else 3410 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 3411 << Name << SS.getRange(); 3412 3413 SS.clear(); 3414 } 3415 3416 if (MSPropertyAttr) { 3417 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3418 BitWidth, InitStyle, AS, *MSPropertyAttr); 3419 if (!Member) 3420 return nullptr; 3421 isInstField = false; 3422 } else { 3423 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3424 BitWidth, InitStyle, AS); 3425 if (!Member) 3426 return nullptr; 3427 } 3428 3429 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext)); 3430 } else { 3431 Member = HandleDeclarator(S, D, TemplateParameterLists); 3432 if (!Member) 3433 return nullptr; 3434 3435 // Non-instance-fields can't have a bitfield. 3436 if (BitWidth) { 3437 if (Member->isInvalidDecl()) { 3438 // don't emit another diagnostic. 3439 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) { 3440 // C++ 9.6p3: A bit-field shall not be a static member. 3441 // "static member 'A' cannot be a bit-field" 3442 Diag(Loc, diag::err_static_not_bitfield) 3443 << Name << BitWidth->getSourceRange(); 3444 } else if (isa<TypedefDecl>(Member)) { 3445 // "typedef member 'x' cannot be a bit-field" 3446 Diag(Loc, diag::err_typedef_not_bitfield) 3447 << Name << BitWidth->getSourceRange(); 3448 } else { 3449 // A function typedef ("typedef int f(); f a;"). 3450 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 3451 Diag(Loc, diag::err_not_integral_type_bitfield) 3452 << Name << cast<ValueDecl>(Member)->getType() 3453 << BitWidth->getSourceRange(); 3454 } 3455 3456 BitWidth = nullptr; 3457 Member->setInvalidDecl(); 3458 } 3459 3460 NamedDecl *NonTemplateMember = Member; 3461 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 3462 NonTemplateMember = FunTmpl->getTemplatedDecl(); 3463 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 3464 NonTemplateMember = VarTmpl->getTemplatedDecl(); 3465 3466 Member->setAccess(AS); 3467 3468 // If we have declared a member function template or static data member 3469 // template, set the access of the templated declaration as well. 3470 if (NonTemplateMember != Member) 3471 NonTemplateMember->setAccess(AS); 3472 3473 // C++ [temp.deduct.guide]p3: 3474 // A deduction guide [...] for a member class template [shall be 3475 // declared] with the same access [as the template]. 3476 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) { 3477 auto *TD = DG->getDeducedTemplate(); 3478 // Access specifiers are only meaningful if both the template and the 3479 // deduction guide are from the same scope. 3480 if (AS != TD->getAccess() && 3481 TD->getDeclContext()->getRedeclContext()->Equals( 3482 DG->getDeclContext()->getRedeclContext())) { 3483 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access); 3484 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access) 3485 << TD->getAccess(); 3486 const AccessSpecDecl *LastAccessSpec = nullptr; 3487 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) { 3488 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D)) 3489 LastAccessSpec = AccessSpec; 3490 } 3491 assert(LastAccessSpec && "differing access with no access specifier"); 3492 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access) 3493 << AS; 3494 } 3495 } 3496 } 3497 3498 if (VS.isOverrideSpecified()) 3499 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(), 3500 AttributeCommonInfo::AS_Keyword)); 3501 if (VS.isFinalSpecified()) 3502 Member->addAttr(FinalAttr::Create( 3503 Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword, 3504 static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed()))); 3505 3506 if (VS.getLastLocation().isValid()) { 3507 // Update the end location of a method that has a virt-specifiers. 3508 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 3509 MD->setRangeEnd(VS.getLastLocation()); 3510 } 3511 3512 CheckOverrideControl(Member); 3513 3514 assert((Name || isInstField) && "No identifier for non-field ?"); 3515 3516 if (isInstField) { 3517 FieldDecl *FD = cast<FieldDecl>(Member); 3518 FieldCollector->Add(FD); 3519 3520 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 3521 // Remember all explicit private FieldDecls that have a name, no side 3522 // effects and are not part of a dependent type declaration. 3523 if (!FD->isImplicit() && FD->getDeclName() && 3524 FD->getAccess() == AS_private && 3525 !FD->hasAttr<UnusedAttr>() && 3526 !FD->getParent()->isDependentContext() && 3527 !InitializationHasSideEffects(*FD)) 3528 UnusedPrivateFields.insert(FD); 3529 } 3530 } 3531 3532 return Member; 3533 } 3534 3535 namespace { 3536 class UninitializedFieldVisitor 3537 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 3538 Sema &S; 3539 // List of Decls to generate a warning on. Also remove Decls that become 3540 // initialized. 3541 llvm::SmallPtrSetImpl<ValueDecl*> &Decls; 3542 // List of base classes of the record. Classes are removed after their 3543 // initializers. 3544 llvm::SmallPtrSetImpl<QualType> &BaseClasses; 3545 // Vector of decls to be removed from the Decl set prior to visiting the 3546 // nodes. These Decls may have been initialized in the prior initializer. 3547 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; 3548 // If non-null, add a note to the warning pointing back to the constructor. 3549 const CXXConstructorDecl *Constructor; 3550 // Variables to hold state when processing an initializer list. When 3551 // InitList is true, special case initialization of FieldDecls matching 3552 // InitListFieldDecl. 3553 bool InitList; 3554 FieldDecl *InitListFieldDecl; 3555 llvm::SmallVector<unsigned, 4> InitFieldIndex; 3556 3557 public: 3558 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 3559 UninitializedFieldVisitor(Sema &S, 3560 llvm::SmallPtrSetImpl<ValueDecl*> &Decls, 3561 llvm::SmallPtrSetImpl<QualType> &BaseClasses) 3562 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), 3563 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} 3564 3565 // Returns true if the use of ME is not an uninitialized use. 3566 bool IsInitListMemberExprInitialized(MemberExpr *ME, 3567 bool CheckReferenceOnly) { 3568 llvm::SmallVector<FieldDecl*, 4> Fields; 3569 bool ReferenceField = false; 3570 while (ME) { 3571 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 3572 if (!FD) 3573 return false; 3574 Fields.push_back(FD); 3575 if (FD->getType()->isReferenceType()) 3576 ReferenceField = true; 3577 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); 3578 } 3579 3580 // Binding a reference to an uninitialized field is not an 3581 // uninitialized use. 3582 if (CheckReferenceOnly && !ReferenceField) 3583 return true; 3584 3585 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 3586 // Discard the first field since it is the field decl that is being 3587 // initialized. 3588 for (const FieldDecl *FD : llvm::drop_begin(llvm::reverse(Fields))) 3589 UsedFieldIndex.push_back(FD->getFieldIndex()); 3590 3591 for (auto UsedIter = UsedFieldIndex.begin(), 3592 UsedEnd = UsedFieldIndex.end(), 3593 OrigIter = InitFieldIndex.begin(), 3594 OrigEnd = InitFieldIndex.end(); 3595 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 3596 if (*UsedIter < *OrigIter) 3597 return true; 3598 if (*UsedIter > *OrigIter) 3599 break; 3600 } 3601 3602 return false; 3603 } 3604 3605 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, 3606 bool AddressOf) { 3607 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 3608 return; 3609 3610 // FieldME is the inner-most MemberExpr that is not an anonymous struct 3611 // or union. 3612 MemberExpr *FieldME = ME; 3613 3614 bool AllPODFields = FieldME->getType().isPODType(S.Context); 3615 3616 Expr *Base = ME; 3617 while (MemberExpr *SubME = 3618 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { 3619 3620 if (isa<VarDecl>(SubME->getMemberDecl())) 3621 return; 3622 3623 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) 3624 if (!FD->isAnonymousStructOrUnion()) 3625 FieldME = SubME; 3626 3627 if (!FieldME->getType().isPODType(S.Context)) 3628 AllPODFields = false; 3629 3630 Base = SubME->getBase(); 3631 } 3632 3633 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) { 3634 Visit(Base); 3635 return; 3636 } 3637 3638 if (AddressOf && AllPODFields) 3639 return; 3640 3641 ValueDecl* FoundVD = FieldME->getMemberDecl(); 3642 3643 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { 3644 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { 3645 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); 3646 } 3647 3648 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { 3649 QualType T = BaseCast->getType(); 3650 if (T->isPointerType() && 3651 BaseClasses.count(T->getPointeeType())) { 3652 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) 3653 << T->getPointeeType() << FoundVD; 3654 } 3655 } 3656 } 3657 3658 if (!Decls.count(FoundVD)) 3659 return; 3660 3661 const bool IsReference = FoundVD->getType()->isReferenceType(); 3662 3663 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { 3664 // Special checking for initializer lists. 3665 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { 3666 return; 3667 } 3668 } else { 3669 // Prevent double warnings on use of unbounded references. 3670 if (CheckReferenceOnly && !IsReference) 3671 return; 3672 } 3673 3674 unsigned diag = IsReference 3675 ? diag::warn_reference_field_is_uninit 3676 : diag::warn_field_is_uninit; 3677 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 3678 if (Constructor) 3679 S.Diag(Constructor->getLocation(), 3680 diag::note_uninit_in_this_constructor) 3681 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 3682 3683 } 3684 3685 void HandleValue(Expr *E, bool AddressOf) { 3686 E = E->IgnoreParens(); 3687 3688 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3689 HandleMemberExpr(ME, false /*CheckReferenceOnly*/, 3690 AddressOf /*AddressOf*/); 3691 return; 3692 } 3693 3694 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 3695 Visit(CO->getCond()); 3696 HandleValue(CO->getTrueExpr(), AddressOf); 3697 HandleValue(CO->getFalseExpr(), AddressOf); 3698 return; 3699 } 3700 3701 if (BinaryConditionalOperator *BCO = 3702 dyn_cast<BinaryConditionalOperator>(E)) { 3703 Visit(BCO->getCond()); 3704 HandleValue(BCO->getFalseExpr(), AddressOf); 3705 return; 3706 } 3707 3708 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 3709 HandleValue(OVE->getSourceExpr(), AddressOf); 3710 return; 3711 } 3712 3713 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 3714 switch (BO->getOpcode()) { 3715 default: 3716 break; 3717 case(BO_PtrMemD): 3718 case(BO_PtrMemI): 3719 HandleValue(BO->getLHS(), AddressOf); 3720 Visit(BO->getRHS()); 3721 return; 3722 case(BO_Comma): 3723 Visit(BO->getLHS()); 3724 HandleValue(BO->getRHS(), AddressOf); 3725 return; 3726 } 3727 } 3728 3729 Visit(E); 3730 } 3731 3732 void CheckInitListExpr(InitListExpr *ILE) { 3733 InitFieldIndex.push_back(0); 3734 for (auto Child : ILE->children()) { 3735 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { 3736 CheckInitListExpr(SubList); 3737 } else { 3738 Visit(Child); 3739 } 3740 ++InitFieldIndex.back(); 3741 } 3742 InitFieldIndex.pop_back(); 3743 } 3744 3745 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, 3746 FieldDecl *Field, const Type *BaseClass) { 3747 // Remove Decls that may have been initialized in the previous 3748 // initializer. 3749 for (ValueDecl* VD : DeclsToRemove) 3750 Decls.erase(VD); 3751 DeclsToRemove.clear(); 3752 3753 Constructor = FieldConstructor; 3754 InitListExpr *ILE = dyn_cast<InitListExpr>(E); 3755 3756 if (ILE && Field) { 3757 InitList = true; 3758 InitListFieldDecl = Field; 3759 InitFieldIndex.clear(); 3760 CheckInitListExpr(ILE); 3761 } else { 3762 InitList = false; 3763 Visit(E); 3764 } 3765 3766 if (Field) 3767 Decls.erase(Field); 3768 if (BaseClass) 3769 BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); 3770 } 3771 3772 void VisitMemberExpr(MemberExpr *ME) { 3773 // All uses of unbounded reference fields will warn. 3774 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); 3775 } 3776 3777 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 3778 if (E->getCastKind() == CK_LValueToRValue) { 3779 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3780 return; 3781 } 3782 3783 Inherited::VisitImplicitCastExpr(E); 3784 } 3785 3786 void VisitCXXConstructExpr(CXXConstructExpr *E) { 3787 if (E->getConstructor()->isCopyConstructor()) { 3788 Expr *ArgExpr = E->getArg(0); 3789 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 3790 if (ILE->getNumInits() == 1) 3791 ArgExpr = ILE->getInit(0); 3792 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 3793 if (ICE->getCastKind() == CK_NoOp) 3794 ArgExpr = ICE->getSubExpr(); 3795 HandleValue(ArgExpr, false /*AddressOf*/); 3796 return; 3797 } 3798 Inherited::VisitCXXConstructExpr(E); 3799 } 3800 3801 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 3802 Expr *Callee = E->getCallee(); 3803 if (isa<MemberExpr>(Callee)) { 3804 HandleValue(Callee, false /*AddressOf*/); 3805 for (auto Arg : E->arguments()) 3806 Visit(Arg); 3807 return; 3808 } 3809 3810 Inherited::VisitCXXMemberCallExpr(E); 3811 } 3812 3813 void VisitCallExpr(CallExpr *E) { 3814 // Treat std::move as a use. 3815 if (E->isCallToStdMove()) { 3816 HandleValue(E->getArg(0), /*AddressOf=*/false); 3817 return; 3818 } 3819 3820 Inherited::VisitCallExpr(E); 3821 } 3822 3823 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 3824 Expr *Callee = E->getCallee(); 3825 3826 if (isa<UnresolvedLookupExpr>(Callee)) 3827 return Inherited::VisitCXXOperatorCallExpr(E); 3828 3829 Visit(Callee); 3830 for (auto Arg : E->arguments()) 3831 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); 3832 } 3833 3834 void VisitBinaryOperator(BinaryOperator *E) { 3835 // If a field assignment is detected, remove the field from the 3836 // uninitiailized field set. 3837 if (E->getOpcode() == BO_Assign) 3838 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 3839 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 3840 if (!FD->getType()->isReferenceType()) 3841 DeclsToRemove.push_back(FD); 3842 3843 if (E->isCompoundAssignmentOp()) { 3844 HandleValue(E->getLHS(), false /*AddressOf*/); 3845 Visit(E->getRHS()); 3846 return; 3847 } 3848 3849 Inherited::VisitBinaryOperator(E); 3850 } 3851 3852 void VisitUnaryOperator(UnaryOperator *E) { 3853 if (E->isIncrementDecrementOp()) { 3854 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3855 return; 3856 } 3857 if (E->getOpcode() == UO_AddrOf) { 3858 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { 3859 HandleValue(ME->getBase(), true /*AddressOf*/); 3860 return; 3861 } 3862 } 3863 3864 Inherited::VisitUnaryOperator(E); 3865 } 3866 }; 3867 3868 // Diagnose value-uses of fields to initialize themselves, e.g. 3869 // foo(foo) 3870 // where foo is not also a parameter to the constructor. 3871 // Also diagnose across field uninitialized use such as 3872 // x(y), y(x) 3873 // TODO: implement -Wuninitialized and fold this into that framework. 3874 static void DiagnoseUninitializedFields( 3875 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 3876 3877 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 3878 Constructor->getLocation())) { 3879 return; 3880 } 3881 3882 if (Constructor->isInvalidDecl()) 3883 return; 3884 3885 const CXXRecordDecl *RD = Constructor->getParent(); 3886 3887 if (RD->isDependentContext()) 3888 return; 3889 3890 // Holds fields that are uninitialized. 3891 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 3892 3893 // At the beginning, all fields are uninitialized. 3894 for (auto *I : RD->decls()) { 3895 if (auto *FD = dyn_cast<FieldDecl>(I)) { 3896 UninitializedFields.insert(FD); 3897 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 3898 UninitializedFields.insert(IFD->getAnonField()); 3899 } 3900 } 3901 3902 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; 3903 for (auto I : RD->bases()) 3904 UninitializedBaseClasses.insert(I.getType().getCanonicalType()); 3905 3906 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3907 return; 3908 3909 UninitializedFieldVisitor UninitializedChecker(SemaRef, 3910 UninitializedFields, 3911 UninitializedBaseClasses); 3912 3913 for (const auto *FieldInit : Constructor->inits()) { 3914 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3915 break; 3916 3917 Expr *InitExpr = FieldInit->getInit(); 3918 if (!InitExpr) 3919 continue; 3920 3921 if (CXXDefaultInitExpr *Default = 3922 dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 3923 InitExpr = Default->getExpr(); 3924 if (!InitExpr) 3925 continue; 3926 // In class initializers will point to the constructor. 3927 UninitializedChecker.CheckInitializer(InitExpr, Constructor, 3928 FieldInit->getAnyMember(), 3929 FieldInit->getBaseClass()); 3930 } else { 3931 UninitializedChecker.CheckInitializer(InitExpr, nullptr, 3932 FieldInit->getAnyMember(), 3933 FieldInit->getBaseClass()); 3934 } 3935 } 3936 } 3937 } // namespace 3938 3939 /// Enter a new C++ default initializer scope. After calling this, the 3940 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 3941 /// parsing or instantiating the initializer failed. 3942 void Sema::ActOnStartCXXInClassMemberInitializer() { 3943 // Create a synthetic function scope to represent the call to the constructor 3944 // that notionally surrounds a use of this initializer. 3945 PushFunctionScope(); 3946 } 3947 3948 void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) { 3949 if (!D.isFunctionDeclarator()) 3950 return; 3951 auto &FTI = D.getFunctionTypeInfo(); 3952 if (!FTI.Params) 3953 return; 3954 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params, 3955 FTI.NumParams)) { 3956 auto *ParamDecl = cast<NamedDecl>(Param.Param); 3957 if (ParamDecl->getDeclName()) 3958 PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false); 3959 } 3960 } 3961 3962 ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) { 3963 return ActOnRequiresClause(ConstraintExpr); 3964 } 3965 3966 ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) { 3967 if (ConstraintExpr.isInvalid()) 3968 return ExprError(); 3969 3970 ConstraintExpr = CorrectDelayedTyposInExpr(ConstraintExpr); 3971 if (ConstraintExpr.isInvalid()) 3972 return ExprError(); 3973 3974 if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(), 3975 UPPC_RequiresClause)) 3976 return ExprError(); 3977 3978 return ConstraintExpr; 3979 } 3980 3981 /// This is invoked after parsing an in-class initializer for a 3982 /// non-static C++ class member, and after instantiating an in-class initializer 3983 /// in a class template. Such actions are deferred until the class is complete. 3984 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 3985 SourceLocation InitLoc, 3986 Expr *InitExpr) { 3987 // Pop the notional constructor scope we created earlier. 3988 PopFunctionScopeInfo(nullptr, D); 3989 3990 FieldDecl *FD = dyn_cast<FieldDecl>(D); 3991 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && 3992 "must set init style when field is created"); 3993 3994 if (!InitExpr) { 3995 D->setInvalidDecl(); 3996 if (FD) 3997 FD->removeInClassInitializer(); 3998 return; 3999 } 4000 4001 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 4002 FD->setInvalidDecl(); 4003 FD->removeInClassInitializer(); 4004 return; 4005 } 4006 4007 ExprResult Init = InitExpr; 4008 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 4009 InitializedEntity Entity = 4010 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD); 4011 InitializationKind Kind = 4012 FD->getInClassInitStyle() == ICIS_ListInit 4013 ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(), 4014 InitExpr->getBeginLoc(), 4015 InitExpr->getEndLoc()) 4016 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc); 4017 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 4018 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 4019 if (Init.isInvalid()) { 4020 FD->setInvalidDecl(); 4021 return; 4022 } 4023 } 4024 4025 // C++11 [class.base.init]p7: 4026 // The initialization of each base and member constitutes a 4027 // full-expression. 4028 Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false); 4029 if (Init.isInvalid()) { 4030 FD->setInvalidDecl(); 4031 return; 4032 } 4033 4034 InitExpr = Init.get(); 4035 4036 FD->setInClassInitializer(InitExpr); 4037 } 4038 4039 /// Find the direct and/or virtual base specifiers that 4040 /// correspond to the given base type, for use in base initialization 4041 /// within a constructor. 4042 static bool FindBaseInitializer(Sema &SemaRef, 4043 CXXRecordDecl *ClassDecl, 4044 QualType BaseType, 4045 const CXXBaseSpecifier *&DirectBaseSpec, 4046 const CXXBaseSpecifier *&VirtualBaseSpec) { 4047 // First, check for a direct base class. 4048 DirectBaseSpec = nullptr; 4049 for (const auto &Base : ClassDecl->bases()) { 4050 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 4051 // We found a direct base of this type. That's what we're 4052 // initializing. 4053 DirectBaseSpec = &Base; 4054 break; 4055 } 4056 } 4057 4058 // Check for a virtual base class. 4059 // FIXME: We might be able to short-circuit this if we know in advance that 4060 // there are no virtual bases. 4061 VirtualBaseSpec = nullptr; 4062 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 4063 // We haven't found a base yet; search the class hierarchy for a 4064 // virtual base class. 4065 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 4066 /*DetectVirtual=*/false); 4067 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(), 4068 SemaRef.Context.getTypeDeclType(ClassDecl), 4069 BaseType, Paths)) { 4070 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 4071 Path != Paths.end(); ++Path) { 4072 if (Path->back().Base->isVirtual()) { 4073 VirtualBaseSpec = Path->back().Base; 4074 break; 4075 } 4076 } 4077 } 4078 } 4079 4080 return DirectBaseSpec || VirtualBaseSpec; 4081 } 4082 4083 /// Handle a C++ member initializer using braced-init-list syntax. 4084 MemInitResult 4085 Sema::ActOnMemInitializer(Decl *ConstructorD, 4086 Scope *S, 4087 CXXScopeSpec &SS, 4088 IdentifierInfo *MemberOrBase, 4089 ParsedType TemplateTypeTy, 4090 const DeclSpec &DS, 4091 SourceLocation IdLoc, 4092 Expr *InitList, 4093 SourceLocation EllipsisLoc) { 4094 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 4095 DS, IdLoc, InitList, 4096 EllipsisLoc); 4097 } 4098 4099 /// Handle a C++ member initializer using parentheses syntax. 4100 MemInitResult 4101 Sema::ActOnMemInitializer(Decl *ConstructorD, 4102 Scope *S, 4103 CXXScopeSpec &SS, 4104 IdentifierInfo *MemberOrBase, 4105 ParsedType TemplateTypeTy, 4106 const DeclSpec &DS, 4107 SourceLocation IdLoc, 4108 SourceLocation LParenLoc, 4109 ArrayRef<Expr *> Args, 4110 SourceLocation RParenLoc, 4111 SourceLocation EllipsisLoc) { 4112 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc); 4113 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 4114 DS, IdLoc, List, EllipsisLoc); 4115 } 4116 4117 namespace { 4118 4119 // Callback to only accept typo corrections that can be a valid C++ member 4120 // initializer: either a non-static field member or a base class. 4121 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback { 4122 public: 4123 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 4124 : ClassDecl(ClassDecl) {} 4125 4126 bool ValidateCandidate(const TypoCorrection &candidate) override { 4127 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 4128 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 4129 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 4130 return isa<TypeDecl>(ND); 4131 } 4132 return false; 4133 } 4134 4135 std::unique_ptr<CorrectionCandidateCallback> clone() override { 4136 return std::make_unique<MemInitializerValidatorCCC>(*this); 4137 } 4138 4139 private: 4140 CXXRecordDecl *ClassDecl; 4141 }; 4142 4143 } 4144 4145 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, 4146 CXXScopeSpec &SS, 4147 ParsedType TemplateTypeTy, 4148 IdentifierInfo *MemberOrBase) { 4149 if (SS.getScopeRep() || TemplateTypeTy) 4150 return nullptr; 4151 for (auto *D : ClassDecl->lookup(MemberOrBase)) 4152 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) 4153 return cast<ValueDecl>(D); 4154 return nullptr; 4155 } 4156 4157 /// Handle a C++ member initializer. 4158 MemInitResult 4159 Sema::BuildMemInitializer(Decl *ConstructorD, 4160 Scope *S, 4161 CXXScopeSpec &SS, 4162 IdentifierInfo *MemberOrBase, 4163 ParsedType TemplateTypeTy, 4164 const DeclSpec &DS, 4165 SourceLocation IdLoc, 4166 Expr *Init, 4167 SourceLocation EllipsisLoc) { 4168 ExprResult Res = CorrectDelayedTyposInExpr(Init, /*InitDecl=*/nullptr, 4169 /*RecoverUncorrectedTypos=*/true); 4170 if (!Res.isUsable()) 4171 return true; 4172 Init = Res.get(); 4173 4174 if (!ConstructorD) 4175 return true; 4176 4177 AdjustDeclIfTemplate(ConstructorD); 4178 4179 CXXConstructorDecl *Constructor 4180 = dyn_cast<CXXConstructorDecl>(ConstructorD); 4181 if (!Constructor) { 4182 // The user wrote a constructor initializer on a function that is 4183 // not a C++ constructor. Ignore the error for now, because we may 4184 // have more member initializers coming; we'll diagnose it just 4185 // once in ActOnMemInitializers. 4186 return true; 4187 } 4188 4189 CXXRecordDecl *ClassDecl = Constructor->getParent(); 4190 4191 // C++ [class.base.init]p2: 4192 // Names in a mem-initializer-id are looked up in the scope of the 4193 // constructor's class and, if not found in that scope, are looked 4194 // up in the scope containing the constructor's definition. 4195 // [Note: if the constructor's class contains a member with the 4196 // same name as a direct or virtual base class of the class, a 4197 // mem-initializer-id naming the member or base class and composed 4198 // of a single identifier refers to the class member. A 4199 // mem-initializer-id for the hidden base class may be specified 4200 // using a qualified name. ] 4201 4202 // Look for a member, first. 4203 if (ValueDecl *Member = tryLookupCtorInitMemberDecl( 4204 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) { 4205 if (EllipsisLoc.isValid()) 4206 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 4207 << MemberOrBase 4208 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 4209 4210 return BuildMemberInitializer(Member, Init, IdLoc); 4211 } 4212 // It didn't name a member, so see if it names a class. 4213 QualType BaseType; 4214 TypeSourceInfo *TInfo = nullptr; 4215 4216 if (TemplateTypeTy) { 4217 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 4218 if (BaseType.isNull()) 4219 return true; 4220 } else if (DS.getTypeSpecType() == TST_decltype) { 4221 BaseType = BuildDecltypeType(DS.getRepAsExpr()); 4222 } else if (DS.getTypeSpecType() == TST_decltype_auto) { 4223 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); 4224 return true; 4225 } else { 4226 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 4227 LookupParsedName(R, S, &SS); 4228 4229 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 4230 if (!TyD) { 4231 if (R.isAmbiguous()) return true; 4232 4233 // We don't want access-control diagnostics here. 4234 R.suppressDiagnostics(); 4235 4236 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 4237 bool NotUnknownSpecialization = false; 4238 DeclContext *DC = computeDeclContext(SS, false); 4239 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 4240 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 4241 4242 if (!NotUnknownSpecialization) { 4243 // When the scope specifier can refer to a member of an unknown 4244 // specialization, we take it as a type name. 4245 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 4246 SS.getWithLocInContext(Context), 4247 *MemberOrBase, IdLoc); 4248 if (BaseType.isNull()) 4249 return true; 4250 4251 TInfo = Context.CreateTypeSourceInfo(BaseType); 4252 DependentNameTypeLoc TL = 4253 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>(); 4254 if (!TL.isNull()) { 4255 TL.setNameLoc(IdLoc); 4256 TL.setElaboratedKeywordLoc(SourceLocation()); 4257 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4258 } 4259 4260 R.clear(); 4261 R.setLookupName(MemberOrBase); 4262 } 4263 } 4264 4265 // If no results were found, try to correct typos. 4266 TypoCorrection Corr; 4267 MemInitializerValidatorCCC CCC(ClassDecl); 4268 if (R.empty() && BaseType.isNull() && 4269 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 4270 CCC, CTK_ErrorRecovery, ClassDecl))) { 4271 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 4272 // We have found a non-static data member with a similar 4273 // name to what was typed; complain and initialize that 4274 // member. 4275 diagnoseTypo(Corr, 4276 PDiag(diag::err_mem_init_not_member_or_class_suggest) 4277 << MemberOrBase << true); 4278 return BuildMemberInitializer(Member, Init, IdLoc); 4279 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 4280 const CXXBaseSpecifier *DirectBaseSpec; 4281 const CXXBaseSpecifier *VirtualBaseSpec; 4282 if (FindBaseInitializer(*this, ClassDecl, 4283 Context.getTypeDeclType(Type), 4284 DirectBaseSpec, VirtualBaseSpec)) { 4285 // We have found a direct or virtual base class with a 4286 // similar name to what was typed; complain and initialize 4287 // that base class. 4288 diagnoseTypo(Corr, 4289 PDiag(diag::err_mem_init_not_member_or_class_suggest) 4290 << MemberOrBase << false, 4291 PDiag() /*Suppress note, we provide our own.*/); 4292 4293 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 4294 : VirtualBaseSpec; 4295 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here) 4296 << BaseSpec->getType() << BaseSpec->getSourceRange(); 4297 4298 TyD = Type; 4299 } 4300 } 4301 } 4302 4303 if (!TyD && BaseType.isNull()) { 4304 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 4305 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 4306 return true; 4307 } 4308 } 4309 4310 if (BaseType.isNull()) { 4311 BaseType = Context.getTypeDeclType(TyD); 4312 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); 4313 if (SS.isSet()) { 4314 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 4315 BaseType); 4316 TInfo = Context.CreateTypeSourceInfo(BaseType); 4317 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>(); 4318 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc); 4319 TL.setElaboratedKeywordLoc(SourceLocation()); 4320 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4321 } 4322 } 4323 } 4324 4325 if (!TInfo) 4326 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 4327 4328 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 4329 } 4330 4331 MemInitResult 4332 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 4333 SourceLocation IdLoc) { 4334 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 4335 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 4336 assert((DirectMember || IndirectMember) && 4337 "Member must be a FieldDecl or IndirectFieldDecl"); 4338 4339 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4340 return true; 4341 4342 if (Member->isInvalidDecl()) 4343 return true; 4344 4345 MultiExprArg Args; 4346 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4347 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4348 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 4349 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 4350 } else { 4351 // Template instantiation doesn't reconstruct ParenListExprs for us. 4352 Args = Init; 4353 } 4354 4355 SourceRange InitRange = Init->getSourceRange(); 4356 4357 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 4358 // Can't check initialization for a member of dependent type or when 4359 // any of the arguments are type-dependent expressions. 4360 DiscardCleanupsInEvaluationContext(); 4361 } else { 4362 bool InitList = false; 4363 if (isa<InitListExpr>(Init)) { 4364 InitList = true; 4365 Args = Init; 4366 } 4367 4368 // Initialize the member. 4369 InitializedEntity MemberEntity = 4370 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 4371 : InitializedEntity::InitializeMember(IndirectMember, 4372 nullptr); 4373 InitializationKind Kind = 4374 InitList ? InitializationKind::CreateDirectList( 4375 IdLoc, Init->getBeginLoc(), Init->getEndLoc()) 4376 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 4377 InitRange.getEnd()); 4378 4379 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 4380 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 4381 nullptr); 4382 if (!MemberInit.isInvalid()) { 4383 // C++11 [class.base.init]p7: 4384 // The initialization of each base and member constitutes a 4385 // full-expression. 4386 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(), 4387 /*DiscardedValue*/ false); 4388 } 4389 4390 if (MemberInit.isInvalid()) { 4391 // Args were sensible expressions but we couldn't initialize the member 4392 // from them. Preserve them in a RecoveryExpr instead. 4393 Init = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args, 4394 Member->getType()) 4395 .get(); 4396 if (!Init) 4397 return true; 4398 } else { 4399 Init = MemberInit.get(); 4400 } 4401 } 4402 4403 if (DirectMember) { 4404 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 4405 InitRange.getBegin(), Init, 4406 InitRange.getEnd()); 4407 } else { 4408 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 4409 InitRange.getBegin(), Init, 4410 InitRange.getEnd()); 4411 } 4412 } 4413 4414 MemInitResult 4415 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 4416 CXXRecordDecl *ClassDecl) { 4417 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4418 if (!LangOpts.CPlusPlus11) 4419 return Diag(NameLoc, diag::err_delegating_ctor) 4420 << TInfo->getTypeLoc().getLocalSourceRange(); 4421 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 4422 4423 bool InitList = true; 4424 MultiExprArg Args = Init; 4425 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4426 InitList = false; 4427 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4428 } 4429 4430 SourceRange InitRange = Init->getSourceRange(); 4431 // Initialize the object. 4432 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 4433 QualType(ClassDecl->getTypeForDecl(), 0)); 4434 InitializationKind Kind = 4435 InitList ? InitializationKind::CreateDirectList( 4436 NameLoc, Init->getBeginLoc(), Init->getEndLoc()) 4437 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 4438 InitRange.getEnd()); 4439 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 4440 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 4441 Args, nullptr); 4442 if (!DelegationInit.isInvalid()) { 4443 assert((DelegationInit.get()->containsErrors() || 4444 cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) && 4445 "Delegating constructor with no target?"); 4446 4447 // C++11 [class.base.init]p7: 4448 // The initialization of each base and member constitutes a 4449 // full-expression. 4450 DelegationInit = ActOnFinishFullExpr( 4451 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false); 4452 } 4453 4454 if (DelegationInit.isInvalid()) { 4455 DelegationInit = 4456 CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args, 4457 QualType(ClassDecl->getTypeForDecl(), 0)); 4458 if (DelegationInit.isInvalid()) 4459 return true; 4460 } else { 4461 // If we are in a dependent context, template instantiation will 4462 // perform this type-checking again. Just save the arguments that we 4463 // received in a ParenListExpr. 4464 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4465 // of the information that we have about the base 4466 // initializer. However, deconstructing the ASTs is a dicey process, 4467 // and this approach is far more likely to get the corner cases right. 4468 if (CurContext->isDependentContext()) 4469 DelegationInit = Init; 4470 } 4471 4472 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 4473 DelegationInit.getAs<Expr>(), 4474 InitRange.getEnd()); 4475 } 4476 4477 MemInitResult 4478 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 4479 Expr *Init, CXXRecordDecl *ClassDecl, 4480 SourceLocation EllipsisLoc) { 4481 SourceLocation BaseLoc 4482 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4483 4484 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 4485 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 4486 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4487 4488 // C++ [class.base.init]p2: 4489 // [...] Unless the mem-initializer-id names a nonstatic data 4490 // member of the constructor's class or a direct or virtual base 4491 // of that class, the mem-initializer is ill-formed. A 4492 // mem-initializer-list can initialize a base class using any 4493 // name that denotes that base class type. 4494 4495 // We can store the initializers in "as-written" form and delay analysis until 4496 // instantiation if the constructor is dependent. But not for dependent 4497 // (broken) code in a non-template! SetCtorInitializers does not expect this. 4498 bool Dependent = CurContext->isDependentContext() && 4499 (BaseType->isDependentType() || Init->isTypeDependent()); 4500 4501 SourceRange InitRange = Init->getSourceRange(); 4502 if (EllipsisLoc.isValid()) { 4503 // This is a pack expansion. 4504 if (!BaseType->containsUnexpandedParameterPack()) { 4505 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 4506 << SourceRange(BaseLoc, InitRange.getEnd()); 4507 4508 EllipsisLoc = SourceLocation(); 4509 } 4510 } else { 4511 // Check for any unexpanded parameter packs. 4512 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 4513 return true; 4514 4515 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4516 return true; 4517 } 4518 4519 // Check for direct and virtual base classes. 4520 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 4521 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 4522 if (!Dependent) { 4523 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 4524 BaseType)) 4525 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 4526 4527 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 4528 VirtualBaseSpec); 4529 4530 // C++ [base.class.init]p2: 4531 // Unless the mem-initializer-id names a nonstatic data member of the 4532 // constructor's class or a direct or virtual base of that class, the 4533 // mem-initializer is ill-formed. 4534 if (!DirectBaseSpec && !VirtualBaseSpec) { 4535 // If the class has any dependent bases, then it's possible that 4536 // one of those types will resolve to the same type as 4537 // BaseType. Therefore, just treat this as a dependent base 4538 // class initialization. FIXME: Should we try to check the 4539 // initialization anyway? It seems odd. 4540 if (ClassDecl->hasAnyDependentBases()) 4541 Dependent = true; 4542 else 4543 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 4544 << BaseType << Context.getTypeDeclType(ClassDecl) 4545 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4546 } 4547 } 4548 4549 if (Dependent) { 4550 DiscardCleanupsInEvaluationContext(); 4551 4552 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4553 /*IsVirtual=*/false, 4554 InitRange.getBegin(), Init, 4555 InitRange.getEnd(), EllipsisLoc); 4556 } 4557 4558 // C++ [base.class.init]p2: 4559 // If a mem-initializer-id is ambiguous because it designates both 4560 // a direct non-virtual base class and an inherited virtual base 4561 // class, the mem-initializer is ill-formed. 4562 if (DirectBaseSpec && VirtualBaseSpec) 4563 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 4564 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4565 4566 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 4567 if (!BaseSpec) 4568 BaseSpec = VirtualBaseSpec; 4569 4570 // Initialize the base. 4571 bool InitList = true; 4572 MultiExprArg Args = Init; 4573 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4574 InitList = false; 4575 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4576 } 4577 4578 InitializedEntity BaseEntity = 4579 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 4580 InitializationKind Kind = 4581 InitList ? InitializationKind::CreateDirectList(BaseLoc) 4582 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 4583 InitRange.getEnd()); 4584 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 4585 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 4586 if (!BaseInit.isInvalid()) { 4587 // C++11 [class.base.init]p7: 4588 // The initialization of each base and member constitutes a 4589 // full-expression. 4590 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(), 4591 /*DiscardedValue*/ false); 4592 } 4593 4594 if (BaseInit.isInvalid()) { 4595 BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), 4596 Args, BaseType); 4597 if (BaseInit.isInvalid()) 4598 return true; 4599 } else { 4600 // If we are in a dependent context, template instantiation will 4601 // perform this type-checking again. Just save the arguments that we 4602 // received in a ParenListExpr. 4603 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4604 // of the information that we have about the base 4605 // initializer. However, deconstructing the ASTs is a dicey process, 4606 // and this approach is far more likely to get the corner cases right. 4607 if (CurContext->isDependentContext()) 4608 BaseInit = Init; 4609 } 4610 4611 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4612 BaseSpec->isVirtual(), 4613 InitRange.getBegin(), 4614 BaseInit.getAs<Expr>(), 4615 InitRange.getEnd(), EllipsisLoc); 4616 } 4617 4618 // Create a static_cast\<T&&>(expr). 4619 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 4620 if (T.isNull()) T = E->getType(); 4621 QualType TargetType = SemaRef.BuildReferenceType( 4622 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 4623 SourceLocation ExprLoc = E->getBeginLoc(); 4624 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 4625 TargetType, ExprLoc); 4626 4627 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 4628 SourceRange(ExprLoc, ExprLoc), 4629 E->getSourceRange()).get(); 4630 } 4631 4632 /// ImplicitInitializerKind - How an implicit base or member initializer should 4633 /// initialize its base or member. 4634 enum ImplicitInitializerKind { 4635 IIK_Default, 4636 IIK_Copy, 4637 IIK_Move, 4638 IIK_Inherit 4639 }; 4640 4641 static bool 4642 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4643 ImplicitInitializerKind ImplicitInitKind, 4644 CXXBaseSpecifier *BaseSpec, 4645 bool IsInheritedVirtualBase, 4646 CXXCtorInitializer *&CXXBaseInit) { 4647 InitializedEntity InitEntity 4648 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 4649 IsInheritedVirtualBase); 4650 4651 ExprResult BaseInit; 4652 4653 switch (ImplicitInitKind) { 4654 case IIK_Inherit: 4655 case IIK_Default: { 4656 InitializationKind InitKind 4657 = InitializationKind::CreateDefault(Constructor->getLocation()); 4658 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4659 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4660 break; 4661 } 4662 4663 case IIK_Move: 4664 case IIK_Copy: { 4665 bool Moving = ImplicitInitKind == IIK_Move; 4666 ParmVarDecl *Param = Constructor->getParamDecl(0); 4667 QualType ParamType = Param->getType().getNonReferenceType(); 4668 4669 Expr *CopyCtorArg = 4670 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4671 SourceLocation(), Param, false, 4672 Constructor->getLocation(), ParamType, 4673 VK_LValue, nullptr); 4674 4675 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 4676 4677 // Cast to the base class to avoid ambiguities. 4678 QualType ArgTy = 4679 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 4680 ParamType.getQualifiers()); 4681 4682 if (Moving) { 4683 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 4684 } 4685 4686 CXXCastPath BasePath; 4687 BasePath.push_back(BaseSpec); 4688 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 4689 CK_UncheckedDerivedToBase, 4690 Moving ? VK_XValue : VK_LValue, 4691 &BasePath).get(); 4692 4693 InitializationKind InitKind 4694 = InitializationKind::CreateDirect(Constructor->getLocation(), 4695 SourceLocation(), SourceLocation()); 4696 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 4697 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 4698 break; 4699 } 4700 } 4701 4702 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 4703 if (BaseInit.isInvalid()) 4704 return true; 4705 4706 CXXBaseInit = 4707 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4708 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 4709 SourceLocation()), 4710 BaseSpec->isVirtual(), 4711 SourceLocation(), 4712 BaseInit.getAs<Expr>(), 4713 SourceLocation(), 4714 SourceLocation()); 4715 4716 return false; 4717 } 4718 4719 static bool RefersToRValueRef(Expr *MemRef) { 4720 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 4721 return Referenced->getType()->isRValueReferenceType(); 4722 } 4723 4724 static bool 4725 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4726 ImplicitInitializerKind ImplicitInitKind, 4727 FieldDecl *Field, IndirectFieldDecl *Indirect, 4728 CXXCtorInitializer *&CXXMemberInit) { 4729 if (Field->isInvalidDecl()) 4730 return true; 4731 4732 SourceLocation Loc = Constructor->getLocation(); 4733 4734 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 4735 bool Moving = ImplicitInitKind == IIK_Move; 4736 ParmVarDecl *Param = Constructor->getParamDecl(0); 4737 QualType ParamType = Param->getType().getNonReferenceType(); 4738 4739 // Suppress copying zero-width bitfields. 4740 if (Field->isZeroLengthBitField(SemaRef.Context)) 4741 return false; 4742 4743 Expr *MemberExprBase = 4744 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4745 SourceLocation(), Param, false, 4746 Loc, ParamType, VK_LValue, nullptr); 4747 4748 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 4749 4750 if (Moving) { 4751 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 4752 } 4753 4754 // Build a reference to this field within the parameter. 4755 CXXScopeSpec SS; 4756 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 4757 Sema::LookupMemberName); 4758 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 4759 : cast<ValueDecl>(Field), AS_public); 4760 MemberLookup.resolveKind(); 4761 ExprResult CtorArg 4762 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 4763 ParamType, Loc, 4764 /*IsArrow=*/false, 4765 SS, 4766 /*TemplateKWLoc=*/SourceLocation(), 4767 /*FirstQualifierInScope=*/nullptr, 4768 MemberLookup, 4769 /*TemplateArgs=*/nullptr, 4770 /*S*/nullptr); 4771 if (CtorArg.isInvalid()) 4772 return true; 4773 4774 // C++11 [class.copy]p15: 4775 // - if a member m has rvalue reference type T&&, it is direct-initialized 4776 // with static_cast<T&&>(x.m); 4777 if (RefersToRValueRef(CtorArg.get())) { 4778 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 4779 } 4780 4781 InitializedEntity Entity = 4782 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4783 /*Implicit*/ true) 4784 : InitializedEntity::InitializeMember(Field, nullptr, 4785 /*Implicit*/ true); 4786 4787 // Direct-initialize to use the copy constructor. 4788 InitializationKind InitKind = 4789 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 4790 4791 Expr *CtorArgE = CtorArg.getAs<Expr>(); 4792 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE); 4793 ExprResult MemberInit = 4794 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1)); 4795 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4796 if (MemberInit.isInvalid()) 4797 return true; 4798 4799 if (Indirect) 4800 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4801 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4802 else 4803 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4804 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4805 return false; 4806 } 4807 4808 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 4809 "Unhandled implicit init kind!"); 4810 4811 QualType FieldBaseElementType = 4812 SemaRef.Context.getBaseElementType(Field->getType()); 4813 4814 if (FieldBaseElementType->isRecordType()) { 4815 InitializedEntity InitEntity = 4816 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4817 /*Implicit*/ true) 4818 : InitializedEntity::InitializeMember(Field, nullptr, 4819 /*Implicit*/ true); 4820 InitializationKind InitKind = 4821 InitializationKind::CreateDefault(Loc); 4822 4823 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4824 ExprResult MemberInit = 4825 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4826 4827 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4828 if (MemberInit.isInvalid()) 4829 return true; 4830 4831 if (Indirect) 4832 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4833 Indirect, Loc, 4834 Loc, 4835 MemberInit.get(), 4836 Loc); 4837 else 4838 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4839 Field, Loc, Loc, 4840 MemberInit.get(), 4841 Loc); 4842 return false; 4843 } 4844 4845 if (!Field->getParent()->isUnion()) { 4846 if (FieldBaseElementType->isReferenceType()) { 4847 SemaRef.Diag(Constructor->getLocation(), 4848 diag::err_uninitialized_member_in_ctor) 4849 << (int)Constructor->isImplicit() 4850 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4851 << 0 << Field->getDeclName(); 4852 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4853 return true; 4854 } 4855 4856 if (FieldBaseElementType.isConstQualified()) { 4857 SemaRef.Diag(Constructor->getLocation(), 4858 diag::err_uninitialized_member_in_ctor) 4859 << (int)Constructor->isImplicit() 4860 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4861 << 1 << Field->getDeclName(); 4862 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4863 return true; 4864 } 4865 } 4866 4867 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) { 4868 // ARC and Weak: 4869 // Default-initialize Objective-C pointers to NULL. 4870 CXXMemberInit 4871 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 4872 Loc, Loc, 4873 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 4874 Loc); 4875 return false; 4876 } 4877 4878 // Nothing to initialize. 4879 CXXMemberInit = nullptr; 4880 return false; 4881 } 4882 4883 namespace { 4884 struct BaseAndFieldInfo { 4885 Sema &S; 4886 CXXConstructorDecl *Ctor; 4887 bool AnyErrorsInInits; 4888 ImplicitInitializerKind IIK; 4889 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 4890 SmallVector<CXXCtorInitializer*, 8> AllToInit; 4891 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 4892 4893 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 4894 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 4895 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 4896 if (Ctor->getInheritedConstructor()) 4897 IIK = IIK_Inherit; 4898 else if (Generated && Ctor->isCopyConstructor()) 4899 IIK = IIK_Copy; 4900 else if (Generated && Ctor->isMoveConstructor()) 4901 IIK = IIK_Move; 4902 else 4903 IIK = IIK_Default; 4904 } 4905 4906 bool isImplicitCopyOrMove() const { 4907 switch (IIK) { 4908 case IIK_Copy: 4909 case IIK_Move: 4910 return true; 4911 4912 case IIK_Default: 4913 case IIK_Inherit: 4914 return false; 4915 } 4916 4917 llvm_unreachable("Invalid ImplicitInitializerKind!"); 4918 } 4919 4920 bool addFieldInitializer(CXXCtorInitializer *Init) { 4921 AllToInit.push_back(Init); 4922 4923 // Check whether this initializer makes the field "used". 4924 if (Init->getInit()->HasSideEffects(S.Context)) 4925 S.UnusedPrivateFields.remove(Init->getAnyMember()); 4926 4927 return false; 4928 } 4929 4930 bool isInactiveUnionMember(FieldDecl *Field) { 4931 RecordDecl *Record = Field->getParent(); 4932 if (!Record->isUnion()) 4933 return false; 4934 4935 if (FieldDecl *Active = 4936 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 4937 return Active != Field->getCanonicalDecl(); 4938 4939 // In an implicit copy or move constructor, ignore any in-class initializer. 4940 if (isImplicitCopyOrMove()) 4941 return true; 4942 4943 // If there's no explicit initialization, the field is active only if it 4944 // has an in-class initializer... 4945 if (Field->hasInClassInitializer()) 4946 return false; 4947 // ... or it's an anonymous struct or union whose class has an in-class 4948 // initializer. 4949 if (!Field->isAnonymousStructOrUnion()) 4950 return true; 4951 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 4952 return !FieldRD->hasInClassInitializer(); 4953 } 4954 4955 /// Determine whether the given field is, or is within, a union member 4956 /// that is inactive (because there was an initializer given for a different 4957 /// member of the union, or because the union was not initialized at all). 4958 bool isWithinInactiveUnionMember(FieldDecl *Field, 4959 IndirectFieldDecl *Indirect) { 4960 if (!Indirect) 4961 return isInactiveUnionMember(Field); 4962 4963 for (auto *C : Indirect->chain()) { 4964 FieldDecl *Field = dyn_cast<FieldDecl>(C); 4965 if (Field && isInactiveUnionMember(Field)) 4966 return true; 4967 } 4968 return false; 4969 } 4970 }; 4971 } 4972 4973 /// Determine whether the given type is an incomplete or zero-lenfgth 4974 /// array type. 4975 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 4976 if (T->isIncompleteArrayType()) 4977 return true; 4978 4979 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 4980 if (!ArrayT->getSize()) 4981 return true; 4982 4983 T = ArrayT->getElementType(); 4984 } 4985 4986 return false; 4987 } 4988 4989 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 4990 FieldDecl *Field, 4991 IndirectFieldDecl *Indirect = nullptr) { 4992 if (Field->isInvalidDecl()) 4993 return false; 4994 4995 // Overwhelmingly common case: we have a direct initializer for this field. 4996 if (CXXCtorInitializer *Init = 4997 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 4998 return Info.addFieldInitializer(Init); 4999 5000 // C++11 [class.base.init]p8: 5001 // if the entity is a non-static data member that has a 5002 // brace-or-equal-initializer and either 5003 // -- the constructor's class is a union and no other variant member of that 5004 // union is designated by a mem-initializer-id or 5005 // -- the constructor's class is not a union, and, if the entity is a member 5006 // of an anonymous union, no other member of that union is designated by 5007 // a mem-initializer-id, 5008 // the entity is initialized as specified in [dcl.init]. 5009 // 5010 // We also apply the same rules to handle anonymous structs within anonymous 5011 // unions. 5012 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 5013 return false; 5014 5015 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 5016 ExprResult DIE = 5017 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); 5018 if (DIE.isInvalid()) 5019 return true; 5020 5021 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true); 5022 SemaRef.checkInitializerLifetime(Entity, DIE.get()); 5023 5024 CXXCtorInitializer *Init; 5025 if (Indirect) 5026 Init = new (SemaRef.Context) 5027 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), 5028 SourceLocation(), DIE.get(), SourceLocation()); 5029 else 5030 Init = new (SemaRef.Context) 5031 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), 5032 SourceLocation(), DIE.get(), SourceLocation()); 5033 return Info.addFieldInitializer(Init); 5034 } 5035 5036 // Don't initialize incomplete or zero-length arrays. 5037 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 5038 return false; 5039 5040 // Don't try to build an implicit initializer if there were semantic 5041 // errors in any of the initializers (and therefore we might be 5042 // missing some that the user actually wrote). 5043 if (Info.AnyErrorsInInits) 5044 return false; 5045 5046 CXXCtorInitializer *Init = nullptr; 5047 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 5048 Indirect, Init)) 5049 return true; 5050 5051 if (!Init) 5052 return false; 5053 5054 return Info.addFieldInitializer(Init); 5055 } 5056 5057 bool 5058 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 5059 CXXCtorInitializer *Initializer) { 5060 assert(Initializer->isDelegatingInitializer()); 5061 Constructor->setNumCtorInitializers(1); 5062 CXXCtorInitializer **initializer = 5063 new (Context) CXXCtorInitializer*[1]; 5064 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 5065 Constructor->setCtorInitializers(initializer); 5066 5067 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 5068 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 5069 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 5070 } 5071 5072 DelegatingCtorDecls.push_back(Constructor); 5073 5074 DiagnoseUninitializedFields(*this, Constructor); 5075 5076 return false; 5077 } 5078 5079 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 5080 ArrayRef<CXXCtorInitializer *> Initializers) { 5081 if (Constructor->isDependentContext()) { 5082 // Just store the initializers as written, they will be checked during 5083 // instantiation. 5084 if (!Initializers.empty()) { 5085 Constructor->setNumCtorInitializers(Initializers.size()); 5086 CXXCtorInitializer **baseOrMemberInitializers = 5087 new (Context) CXXCtorInitializer*[Initializers.size()]; 5088 memcpy(baseOrMemberInitializers, Initializers.data(), 5089 Initializers.size() * sizeof(CXXCtorInitializer*)); 5090 Constructor->setCtorInitializers(baseOrMemberInitializers); 5091 } 5092 5093 // Let template instantiation know whether we had errors. 5094 if (AnyErrors) 5095 Constructor->setInvalidDecl(); 5096 5097 return false; 5098 } 5099 5100 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 5101 5102 // We need to build the initializer AST according to order of construction 5103 // and not what user specified in the Initializers list. 5104 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 5105 if (!ClassDecl) 5106 return true; 5107 5108 bool HadError = false; 5109 5110 for (unsigned i = 0; i < Initializers.size(); i++) { 5111 CXXCtorInitializer *Member = Initializers[i]; 5112 5113 if (Member->isBaseInitializer()) 5114 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 5115 else { 5116 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 5117 5118 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 5119 for (auto *C : F->chain()) { 5120 FieldDecl *FD = dyn_cast<FieldDecl>(C); 5121 if (FD && FD->getParent()->isUnion()) 5122 Info.ActiveUnionMember.insert(std::make_pair( 5123 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 5124 } 5125 } else if (FieldDecl *FD = Member->getMember()) { 5126 if (FD->getParent()->isUnion()) 5127 Info.ActiveUnionMember.insert(std::make_pair( 5128 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 5129 } 5130 } 5131 } 5132 5133 // Keep track of the direct virtual bases. 5134 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 5135 for (auto &I : ClassDecl->bases()) { 5136 if (I.isVirtual()) 5137 DirectVBases.insert(&I); 5138 } 5139 5140 // Push virtual bases before others. 5141 for (auto &VBase : ClassDecl->vbases()) { 5142 if (CXXCtorInitializer *Value 5143 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 5144 // [class.base.init]p7, per DR257: 5145 // A mem-initializer where the mem-initializer-id names a virtual base 5146 // class is ignored during execution of a constructor of any class that 5147 // is not the most derived class. 5148 if (ClassDecl->isAbstract()) { 5149 // FIXME: Provide a fixit to remove the base specifier. This requires 5150 // tracking the location of the associated comma for a base specifier. 5151 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 5152 << VBase.getType() << ClassDecl; 5153 DiagnoseAbstractType(ClassDecl); 5154 } 5155 5156 Info.AllToInit.push_back(Value); 5157 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 5158 // [class.base.init]p8, per DR257: 5159 // If a given [...] base class is not named by a mem-initializer-id 5160 // [...] and the entity is not a virtual base class of an abstract 5161 // class, then [...] the entity is default-initialized. 5162 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 5163 CXXCtorInitializer *CXXBaseInit; 5164 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 5165 &VBase, IsInheritedVirtualBase, 5166 CXXBaseInit)) { 5167 HadError = true; 5168 continue; 5169 } 5170 5171 Info.AllToInit.push_back(CXXBaseInit); 5172 } 5173 } 5174 5175 // Non-virtual bases. 5176 for (auto &Base : ClassDecl->bases()) { 5177 // Virtuals are in the virtual base list and already constructed. 5178 if (Base.isVirtual()) 5179 continue; 5180 5181 if (CXXCtorInitializer *Value 5182 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 5183 Info.AllToInit.push_back(Value); 5184 } else if (!AnyErrors) { 5185 CXXCtorInitializer *CXXBaseInit; 5186 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 5187 &Base, /*IsInheritedVirtualBase=*/false, 5188 CXXBaseInit)) { 5189 HadError = true; 5190 continue; 5191 } 5192 5193 Info.AllToInit.push_back(CXXBaseInit); 5194 } 5195 } 5196 5197 // Fields. 5198 for (auto *Mem : ClassDecl->decls()) { 5199 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 5200 // C++ [class.bit]p2: 5201 // A declaration for a bit-field that omits the identifier declares an 5202 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 5203 // initialized. 5204 if (F->isUnnamedBitfield()) 5205 continue; 5206 5207 // If we're not generating the implicit copy/move constructor, then we'll 5208 // handle anonymous struct/union fields based on their individual 5209 // indirect fields. 5210 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 5211 continue; 5212 5213 if (CollectFieldInitializer(*this, Info, F)) 5214 HadError = true; 5215 continue; 5216 } 5217 5218 // Beyond this point, we only consider default initialization. 5219 if (Info.isImplicitCopyOrMove()) 5220 continue; 5221 5222 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 5223 if (F->getType()->isIncompleteArrayType()) { 5224 assert(ClassDecl->hasFlexibleArrayMember() && 5225 "Incomplete array type is not valid"); 5226 continue; 5227 } 5228 5229 // Initialize each field of an anonymous struct individually. 5230 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 5231 HadError = true; 5232 5233 continue; 5234 } 5235 } 5236 5237 unsigned NumInitializers = Info.AllToInit.size(); 5238 if (NumInitializers > 0) { 5239 Constructor->setNumCtorInitializers(NumInitializers); 5240 CXXCtorInitializer **baseOrMemberInitializers = 5241 new (Context) CXXCtorInitializer*[NumInitializers]; 5242 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 5243 NumInitializers * sizeof(CXXCtorInitializer*)); 5244 Constructor->setCtorInitializers(baseOrMemberInitializers); 5245 5246 // Constructors implicitly reference the base and member 5247 // destructors. 5248 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 5249 Constructor->getParent()); 5250 } 5251 5252 return HadError; 5253 } 5254 5255 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 5256 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 5257 const RecordDecl *RD = RT->getDecl(); 5258 if (RD->isAnonymousStructOrUnion()) { 5259 for (auto *Field : RD->fields()) 5260 PopulateKeysForFields(Field, IdealInits); 5261 return; 5262 } 5263 } 5264 IdealInits.push_back(Field->getCanonicalDecl()); 5265 } 5266 5267 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 5268 return Context.getCanonicalType(BaseType).getTypePtr(); 5269 } 5270 5271 static const void *GetKeyForMember(ASTContext &Context, 5272 CXXCtorInitializer *Member) { 5273 if (!Member->isAnyMemberInitializer()) 5274 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 5275 5276 return Member->getAnyMember()->getCanonicalDecl(); 5277 } 5278 5279 static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag, 5280 const CXXCtorInitializer *Previous, 5281 const CXXCtorInitializer *Current) { 5282 if (Previous->isAnyMemberInitializer()) 5283 Diag << 0 << Previous->getAnyMember(); 5284 else 5285 Diag << 1 << Previous->getTypeSourceInfo()->getType(); 5286 5287 if (Current->isAnyMemberInitializer()) 5288 Diag << 0 << Current->getAnyMember(); 5289 else 5290 Diag << 1 << Current->getTypeSourceInfo()->getType(); 5291 } 5292 5293 static void DiagnoseBaseOrMemInitializerOrder( 5294 Sema &SemaRef, const CXXConstructorDecl *Constructor, 5295 ArrayRef<CXXCtorInitializer *> Inits) { 5296 if (Constructor->getDeclContext()->isDependentContext()) 5297 return; 5298 5299 // Don't check initializers order unless the warning is enabled at the 5300 // location of at least one initializer. 5301 bool ShouldCheckOrder = false; 5302 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 5303 CXXCtorInitializer *Init = Inits[InitIndex]; 5304 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 5305 Init->getSourceLocation())) { 5306 ShouldCheckOrder = true; 5307 break; 5308 } 5309 } 5310 if (!ShouldCheckOrder) 5311 return; 5312 5313 // Build the list of bases and members in the order that they'll 5314 // actually be initialized. The explicit initializers should be in 5315 // this same order but may be missing things. 5316 SmallVector<const void*, 32> IdealInitKeys; 5317 5318 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 5319 5320 // 1. Virtual bases. 5321 for (const auto &VBase : ClassDecl->vbases()) 5322 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 5323 5324 // 2. Non-virtual bases. 5325 for (const auto &Base : ClassDecl->bases()) { 5326 if (Base.isVirtual()) 5327 continue; 5328 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 5329 } 5330 5331 // 3. Direct fields. 5332 for (auto *Field : ClassDecl->fields()) { 5333 if (Field->isUnnamedBitfield()) 5334 continue; 5335 5336 PopulateKeysForFields(Field, IdealInitKeys); 5337 } 5338 5339 unsigned NumIdealInits = IdealInitKeys.size(); 5340 unsigned IdealIndex = 0; 5341 5342 // Track initializers that are in an incorrect order for either a warning or 5343 // note if multiple ones occur. 5344 SmallVector<unsigned> WarnIndexes; 5345 // Correlates the index of an initializer in the init-list to the index of 5346 // the field/base in the class. 5347 SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder; 5348 5349 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 5350 const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]); 5351 5352 // Scan forward to try to find this initializer in the idealized 5353 // initializers list. 5354 for (; IdealIndex != NumIdealInits; ++IdealIndex) 5355 if (InitKey == IdealInitKeys[IdealIndex]) 5356 break; 5357 5358 // If we didn't find this initializer, it must be because we 5359 // scanned past it on a previous iteration. That can only 5360 // happen if we're out of order; emit a warning. 5361 if (IdealIndex == NumIdealInits && InitIndex) { 5362 WarnIndexes.push_back(InitIndex); 5363 5364 // Move back to the initializer's location in the ideal list. 5365 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 5366 if (InitKey == IdealInitKeys[IdealIndex]) 5367 break; 5368 5369 assert(IdealIndex < NumIdealInits && 5370 "initializer not found in initializer list"); 5371 } 5372 CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex); 5373 } 5374 5375 if (WarnIndexes.empty()) 5376 return; 5377 5378 // Sort based on the ideal order, first in the pair. 5379 llvm::sort(CorrelatedInitOrder, 5380 [](auto &LHS, auto &RHS) { return LHS.first < RHS.first; }); 5381 5382 // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to 5383 // emit the diagnostic before we can try adding notes. 5384 { 5385 Sema::SemaDiagnosticBuilder D = SemaRef.Diag( 5386 Inits[WarnIndexes.front() - 1]->getSourceLocation(), 5387 WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order 5388 : diag::warn_some_initializers_out_of_order); 5389 5390 for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) { 5391 if (CorrelatedInitOrder[I].second == I) 5392 continue; 5393 // Ideally we would be using InsertFromRange here, but clang doesn't 5394 // appear to handle InsertFromRange correctly when the source range is 5395 // modified by another fix-it. 5396 D << FixItHint::CreateReplacement( 5397 Inits[I]->getSourceRange(), 5398 Lexer::getSourceText( 5399 CharSourceRange::getTokenRange( 5400 Inits[CorrelatedInitOrder[I].second]->getSourceRange()), 5401 SemaRef.getSourceManager(), SemaRef.getLangOpts())); 5402 } 5403 5404 // If there is only 1 item out of order, the warning expects the name and 5405 // type of each being added to it. 5406 if (WarnIndexes.size() == 1) { 5407 AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1], 5408 Inits[WarnIndexes.front()]); 5409 return; 5410 } 5411 } 5412 // More than 1 item to warn, create notes letting the user know which ones 5413 // are bad. 5414 for (unsigned WarnIndex : WarnIndexes) { 5415 const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1]; 5416 auto D = SemaRef.Diag(PrevInit->getSourceLocation(), 5417 diag::note_initializer_out_of_order); 5418 AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]); 5419 D << PrevInit->getSourceRange(); 5420 } 5421 } 5422 5423 namespace { 5424 bool CheckRedundantInit(Sema &S, 5425 CXXCtorInitializer *Init, 5426 CXXCtorInitializer *&PrevInit) { 5427 if (!PrevInit) { 5428 PrevInit = Init; 5429 return false; 5430 } 5431 5432 if (FieldDecl *Field = Init->getAnyMember()) 5433 S.Diag(Init->getSourceLocation(), 5434 diag::err_multiple_mem_initialization) 5435 << Field->getDeclName() 5436 << Init->getSourceRange(); 5437 else { 5438 const Type *BaseClass = Init->getBaseClass(); 5439 assert(BaseClass && "neither field nor base"); 5440 S.Diag(Init->getSourceLocation(), 5441 diag::err_multiple_base_initialization) 5442 << QualType(BaseClass, 0) 5443 << Init->getSourceRange(); 5444 } 5445 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 5446 << 0 << PrevInit->getSourceRange(); 5447 5448 return true; 5449 } 5450 5451 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 5452 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 5453 5454 bool CheckRedundantUnionInit(Sema &S, 5455 CXXCtorInitializer *Init, 5456 RedundantUnionMap &Unions) { 5457 FieldDecl *Field = Init->getAnyMember(); 5458 RecordDecl *Parent = Field->getParent(); 5459 NamedDecl *Child = Field; 5460 5461 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 5462 if (Parent->isUnion()) { 5463 UnionEntry &En = Unions[Parent]; 5464 if (En.first && En.first != Child) { 5465 S.Diag(Init->getSourceLocation(), 5466 diag::err_multiple_mem_union_initialization) 5467 << Field->getDeclName() 5468 << Init->getSourceRange(); 5469 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 5470 << 0 << En.second->getSourceRange(); 5471 return true; 5472 } 5473 if (!En.first) { 5474 En.first = Child; 5475 En.second = Init; 5476 } 5477 if (!Parent->isAnonymousStructOrUnion()) 5478 return false; 5479 } 5480 5481 Child = Parent; 5482 Parent = cast<RecordDecl>(Parent->getDeclContext()); 5483 } 5484 5485 return false; 5486 } 5487 } // namespace 5488 5489 /// ActOnMemInitializers - Handle the member initializers for a constructor. 5490 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 5491 SourceLocation ColonLoc, 5492 ArrayRef<CXXCtorInitializer*> MemInits, 5493 bool AnyErrors) { 5494 if (!ConstructorDecl) 5495 return; 5496 5497 AdjustDeclIfTemplate(ConstructorDecl); 5498 5499 CXXConstructorDecl *Constructor 5500 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 5501 5502 if (!Constructor) { 5503 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 5504 return; 5505 } 5506 5507 // Mapping for the duplicate initializers check. 5508 // For member initializers, this is keyed with a FieldDecl*. 5509 // For base initializers, this is keyed with a Type*. 5510 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 5511 5512 // Mapping for the inconsistent anonymous-union initializers check. 5513 RedundantUnionMap MemberUnions; 5514 5515 bool HadError = false; 5516 for (unsigned i = 0; i < MemInits.size(); i++) { 5517 CXXCtorInitializer *Init = MemInits[i]; 5518 5519 // Set the source order index. 5520 Init->setSourceOrder(i); 5521 5522 if (Init->isAnyMemberInitializer()) { 5523 const void *Key = GetKeyForMember(Context, Init); 5524 if (CheckRedundantInit(*this, Init, Members[Key]) || 5525 CheckRedundantUnionInit(*this, Init, MemberUnions)) 5526 HadError = true; 5527 } else if (Init->isBaseInitializer()) { 5528 const void *Key = GetKeyForMember(Context, Init); 5529 if (CheckRedundantInit(*this, Init, Members[Key])) 5530 HadError = true; 5531 } else { 5532 assert(Init->isDelegatingInitializer()); 5533 // This must be the only initializer 5534 if (MemInits.size() != 1) { 5535 Diag(Init->getSourceLocation(), 5536 diag::err_delegating_initializer_alone) 5537 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 5538 // We will treat this as being the only initializer. 5539 } 5540 SetDelegatingInitializer(Constructor, MemInits[i]); 5541 // Return immediately as the initializer is set. 5542 return; 5543 } 5544 } 5545 5546 if (HadError) 5547 return; 5548 5549 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 5550 5551 SetCtorInitializers(Constructor, AnyErrors, MemInits); 5552 5553 DiagnoseUninitializedFields(*this, Constructor); 5554 } 5555 5556 void 5557 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 5558 CXXRecordDecl *ClassDecl) { 5559 // Ignore dependent contexts. Also ignore unions, since their members never 5560 // have destructors implicitly called. 5561 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 5562 return; 5563 5564 // FIXME: all the access-control diagnostics are positioned on the 5565 // field/base declaration. That's probably good; that said, the 5566 // user might reasonably want to know why the destructor is being 5567 // emitted, and we currently don't say. 5568 5569 // Non-static data members. 5570 for (auto *Field : ClassDecl->fields()) { 5571 if (Field->isInvalidDecl()) 5572 continue; 5573 5574 // Don't destroy incomplete or zero-length arrays. 5575 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 5576 continue; 5577 5578 QualType FieldType = Context.getBaseElementType(Field->getType()); 5579 5580 const RecordType* RT = FieldType->getAs<RecordType>(); 5581 if (!RT) 5582 continue; 5583 5584 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5585 if (FieldClassDecl->isInvalidDecl()) 5586 continue; 5587 if (FieldClassDecl->hasIrrelevantDestructor()) 5588 continue; 5589 // The destructor for an implicit anonymous union member is never invoked. 5590 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 5591 continue; 5592 5593 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 5594 assert(Dtor && "No dtor found for FieldClassDecl!"); 5595 CheckDestructorAccess(Field->getLocation(), Dtor, 5596 PDiag(diag::err_access_dtor_field) 5597 << Field->getDeclName() 5598 << FieldType); 5599 5600 MarkFunctionReferenced(Location, Dtor); 5601 DiagnoseUseOfDecl(Dtor, Location); 5602 } 5603 5604 // We only potentially invoke the destructors of potentially constructed 5605 // subobjects. 5606 bool VisitVirtualBases = !ClassDecl->isAbstract(); 5607 5608 // If the destructor exists and has already been marked used in the MS ABI, 5609 // then virtual base destructors have already been checked and marked used. 5610 // Skip checking them again to avoid duplicate diagnostics. 5611 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 5612 CXXDestructorDecl *Dtor = ClassDecl->getDestructor(); 5613 if (Dtor && Dtor->isUsed()) 5614 VisitVirtualBases = false; 5615 } 5616 5617 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 5618 5619 // Bases. 5620 for (const auto &Base : ClassDecl->bases()) { 5621 const RecordType *RT = Base.getType()->getAs<RecordType>(); 5622 if (!RT) 5623 continue; 5624 5625 // Remember direct virtual bases. 5626 if (Base.isVirtual()) { 5627 if (!VisitVirtualBases) 5628 continue; 5629 DirectVirtualBases.insert(RT); 5630 } 5631 5632 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5633 // If our base class is invalid, we probably can't get its dtor anyway. 5634 if (BaseClassDecl->isInvalidDecl()) 5635 continue; 5636 if (BaseClassDecl->hasIrrelevantDestructor()) 5637 continue; 5638 5639 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5640 assert(Dtor && "No dtor found for BaseClassDecl!"); 5641 5642 // FIXME: caret should be on the start of the class name 5643 CheckDestructorAccess(Base.getBeginLoc(), Dtor, 5644 PDiag(diag::err_access_dtor_base) 5645 << Base.getType() << Base.getSourceRange(), 5646 Context.getTypeDeclType(ClassDecl)); 5647 5648 MarkFunctionReferenced(Location, Dtor); 5649 DiagnoseUseOfDecl(Dtor, Location); 5650 } 5651 5652 if (VisitVirtualBases) 5653 MarkVirtualBaseDestructorsReferenced(Location, ClassDecl, 5654 &DirectVirtualBases); 5655 } 5656 5657 void Sema::MarkVirtualBaseDestructorsReferenced( 5658 SourceLocation Location, CXXRecordDecl *ClassDecl, 5659 llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) { 5660 // Virtual bases. 5661 for (const auto &VBase : ClassDecl->vbases()) { 5662 // Bases are always records in a well-formed non-dependent class. 5663 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 5664 5665 // Ignore already visited direct virtual bases. 5666 if (DirectVirtualBases && DirectVirtualBases->count(RT)) 5667 continue; 5668 5669 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5670 // If our base class is invalid, we probably can't get its dtor anyway. 5671 if (BaseClassDecl->isInvalidDecl()) 5672 continue; 5673 if (BaseClassDecl->hasIrrelevantDestructor()) 5674 continue; 5675 5676 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5677 assert(Dtor && "No dtor found for BaseClassDecl!"); 5678 if (CheckDestructorAccess( 5679 ClassDecl->getLocation(), Dtor, 5680 PDiag(diag::err_access_dtor_vbase) 5681 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 5682 Context.getTypeDeclType(ClassDecl)) == 5683 AR_accessible) { 5684 CheckDerivedToBaseConversion( 5685 Context.getTypeDeclType(ClassDecl), VBase.getType(), 5686 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 5687 SourceRange(), DeclarationName(), nullptr); 5688 } 5689 5690 MarkFunctionReferenced(Location, Dtor); 5691 DiagnoseUseOfDecl(Dtor, Location); 5692 } 5693 } 5694 5695 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 5696 if (!CDtorDecl) 5697 return; 5698 5699 if (CXXConstructorDecl *Constructor 5700 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 5701 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 5702 DiagnoseUninitializedFields(*this, Constructor); 5703 } 5704 } 5705 5706 bool Sema::isAbstractType(SourceLocation Loc, QualType T) { 5707 if (!getLangOpts().CPlusPlus) 5708 return false; 5709 5710 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl(); 5711 if (!RD) 5712 return false; 5713 5714 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a 5715 // class template specialization here, but doing so breaks a lot of code. 5716 5717 // We can't answer whether something is abstract until it has a 5718 // definition. If it's currently being defined, we'll walk back 5719 // over all the declarations when we have a full definition. 5720 const CXXRecordDecl *Def = RD->getDefinition(); 5721 if (!Def || Def->isBeingDefined()) 5722 return false; 5723 5724 return RD->isAbstract(); 5725 } 5726 5727 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 5728 TypeDiagnoser &Diagnoser) { 5729 if (!isAbstractType(Loc, T)) 5730 return false; 5731 5732 T = Context.getBaseElementType(T); 5733 Diagnoser.diagnose(*this, Loc, T); 5734 DiagnoseAbstractType(T->getAsCXXRecordDecl()); 5735 return true; 5736 } 5737 5738 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 5739 // Check if we've already emitted the list of pure virtual functions 5740 // for this class. 5741 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 5742 return; 5743 5744 // If the diagnostic is suppressed, don't emit the notes. We're only 5745 // going to emit them once, so try to attach them to a diagnostic we're 5746 // actually going to show. 5747 if (Diags.isLastDiagnosticIgnored()) 5748 return; 5749 5750 CXXFinalOverriderMap FinalOverriders; 5751 RD->getFinalOverriders(FinalOverriders); 5752 5753 // Keep a set of seen pure methods so we won't diagnose the same method 5754 // more than once. 5755 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 5756 5757 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 5758 MEnd = FinalOverriders.end(); 5759 M != MEnd; 5760 ++M) { 5761 for (OverridingMethods::iterator SO = M->second.begin(), 5762 SOEnd = M->second.end(); 5763 SO != SOEnd; ++SO) { 5764 // C++ [class.abstract]p4: 5765 // A class is abstract if it contains or inherits at least one 5766 // pure virtual function for which the final overrider is pure 5767 // virtual. 5768 5769 // 5770 if (SO->second.size() != 1) 5771 continue; 5772 5773 if (!SO->second.front().Method->isPure()) 5774 continue; 5775 5776 if (!SeenPureMethods.insert(SO->second.front().Method).second) 5777 continue; 5778 5779 Diag(SO->second.front().Method->getLocation(), 5780 diag::note_pure_virtual_function) 5781 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 5782 } 5783 } 5784 5785 if (!PureVirtualClassDiagSet) 5786 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 5787 PureVirtualClassDiagSet->insert(RD); 5788 } 5789 5790 namespace { 5791 struct AbstractUsageInfo { 5792 Sema &S; 5793 CXXRecordDecl *Record; 5794 CanQualType AbstractType; 5795 bool Invalid; 5796 5797 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 5798 : S(S), Record(Record), 5799 AbstractType(S.Context.getCanonicalType( 5800 S.Context.getTypeDeclType(Record))), 5801 Invalid(false) {} 5802 5803 void DiagnoseAbstractType() { 5804 if (Invalid) return; 5805 S.DiagnoseAbstractType(Record); 5806 Invalid = true; 5807 } 5808 5809 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 5810 }; 5811 5812 struct CheckAbstractUsage { 5813 AbstractUsageInfo &Info; 5814 const NamedDecl *Ctx; 5815 5816 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 5817 : Info(Info), Ctx(Ctx) {} 5818 5819 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5820 switch (TL.getTypeLocClass()) { 5821 #define ABSTRACT_TYPELOC(CLASS, PARENT) 5822 #define TYPELOC(CLASS, PARENT) \ 5823 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 5824 #include "clang/AST/TypeLocNodes.def" 5825 } 5826 } 5827 5828 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5829 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 5830 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 5831 if (!TL.getParam(I)) 5832 continue; 5833 5834 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 5835 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 5836 } 5837 } 5838 5839 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5840 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 5841 } 5842 5843 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5844 // Visit the type parameters from a permissive context. 5845 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 5846 TemplateArgumentLoc TAL = TL.getArgLoc(I); 5847 if (TAL.getArgument().getKind() == TemplateArgument::Type) 5848 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 5849 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 5850 // TODO: other template argument types? 5851 } 5852 } 5853 5854 // Visit pointee types from a permissive context. 5855 #define CheckPolymorphic(Type) \ 5856 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 5857 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 5858 } 5859 CheckPolymorphic(PointerTypeLoc) 5860 CheckPolymorphic(ReferenceTypeLoc) 5861 CheckPolymorphic(MemberPointerTypeLoc) 5862 CheckPolymorphic(BlockPointerTypeLoc) 5863 CheckPolymorphic(AtomicTypeLoc) 5864 5865 /// Handle all the types we haven't given a more specific 5866 /// implementation for above. 5867 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5868 // Every other kind of type that we haven't called out already 5869 // that has an inner type is either (1) sugar or (2) contains that 5870 // inner type in some way as a subobject. 5871 if (TypeLoc Next = TL.getNextTypeLoc()) 5872 return Visit(Next, Sel); 5873 5874 // If there's no inner type and we're in a permissive context, 5875 // don't diagnose. 5876 if (Sel == Sema::AbstractNone) return; 5877 5878 // Check whether the type matches the abstract type. 5879 QualType T = TL.getType(); 5880 if (T->isArrayType()) { 5881 Sel = Sema::AbstractArrayType; 5882 T = Info.S.Context.getBaseElementType(T); 5883 } 5884 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 5885 if (CT != Info.AbstractType) return; 5886 5887 // It matched; do some magic. 5888 // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646. 5889 if (Sel == Sema::AbstractArrayType) { 5890 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 5891 << T << TL.getSourceRange(); 5892 } else { 5893 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 5894 << Sel << T << TL.getSourceRange(); 5895 } 5896 Info.DiagnoseAbstractType(); 5897 } 5898 }; 5899 5900 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 5901 Sema::AbstractDiagSelID Sel) { 5902 CheckAbstractUsage(*this, D).Visit(TL, Sel); 5903 } 5904 5905 } 5906 5907 /// Check for invalid uses of an abstract type in a function declaration. 5908 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5909 FunctionDecl *FD) { 5910 // No need to do the check on definitions, which require that 5911 // the return/param types be complete. 5912 if (FD->doesThisDeclarationHaveABody()) 5913 return; 5914 5915 // For safety's sake, just ignore it if we don't have type source 5916 // information. This should never happen for non-implicit methods, 5917 // but... 5918 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 5919 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractNone); 5920 } 5921 5922 /// Check for invalid uses of an abstract type in a variable0 declaration. 5923 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5924 VarDecl *VD) { 5925 // No need to do the check on definitions, which require that 5926 // the type is complete. 5927 if (VD->isThisDeclarationADefinition()) 5928 return; 5929 5930 Info.CheckType(VD, VD->getTypeSourceInfo()->getTypeLoc(), 5931 Sema::AbstractVariableType); 5932 } 5933 5934 /// Check for invalid uses of an abstract type within a class definition. 5935 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5936 CXXRecordDecl *RD) { 5937 for (auto *D : RD->decls()) { 5938 if (D->isImplicit()) continue; 5939 5940 // Step through friends to the befriended declaration. 5941 if (auto *FD = dyn_cast<FriendDecl>(D)) { 5942 D = FD->getFriendDecl(); 5943 if (!D) continue; 5944 } 5945 5946 // Functions and function templates. 5947 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 5948 CheckAbstractClassUsage(Info, FD); 5949 } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) { 5950 CheckAbstractClassUsage(Info, FTD->getTemplatedDecl()); 5951 5952 // Fields and static variables. 5953 } else if (auto *FD = dyn_cast<FieldDecl>(D)) { 5954 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 5955 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 5956 } else if (auto *VD = dyn_cast<VarDecl>(D)) { 5957 CheckAbstractClassUsage(Info, VD); 5958 } else if (auto *VTD = dyn_cast<VarTemplateDecl>(D)) { 5959 CheckAbstractClassUsage(Info, VTD->getTemplatedDecl()); 5960 5961 // Nested classes and class templates. 5962 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 5963 CheckAbstractClassUsage(Info, RD); 5964 } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(D)) { 5965 CheckAbstractClassUsage(Info, CTD->getTemplatedDecl()); 5966 } 5967 } 5968 } 5969 5970 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) { 5971 Attr *ClassAttr = getDLLAttr(Class); 5972 if (!ClassAttr) 5973 return; 5974 5975 assert(ClassAttr->getKind() == attr::DLLExport); 5976 5977 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5978 5979 if (TSK == TSK_ExplicitInstantiationDeclaration) 5980 // Don't go any further if this is just an explicit instantiation 5981 // declaration. 5982 return; 5983 5984 // Add a context note to explain how we got to any diagnostics produced below. 5985 struct MarkingClassDllexported { 5986 Sema &S; 5987 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class, 5988 SourceLocation AttrLoc) 5989 : S(S) { 5990 Sema::CodeSynthesisContext Ctx; 5991 Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported; 5992 Ctx.PointOfInstantiation = AttrLoc; 5993 Ctx.Entity = Class; 5994 S.pushCodeSynthesisContext(Ctx); 5995 } 5996 ~MarkingClassDllexported() { 5997 S.popCodeSynthesisContext(); 5998 } 5999 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation()); 6000 6001 if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) 6002 S.MarkVTableUsed(Class->getLocation(), Class, true); 6003 6004 for (Decl *Member : Class->decls()) { 6005 // Skip members that were not marked exported. 6006 if (!Member->hasAttr<DLLExportAttr>()) 6007 continue; 6008 6009 // Defined static variables that are members of an exported base 6010 // class must be marked export too. 6011 auto *VD = dyn_cast<VarDecl>(Member); 6012 if (VD && VD->getStorageClass() == SC_Static && 6013 TSK == TSK_ImplicitInstantiation) 6014 S.MarkVariableReferenced(VD->getLocation(), VD); 6015 6016 auto *MD = dyn_cast<CXXMethodDecl>(Member); 6017 if (!MD) 6018 continue; 6019 6020 if (MD->isUserProvided()) { 6021 // Instantiate non-default class member functions ... 6022 6023 // .. except for certain kinds of template specializations. 6024 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 6025 continue; 6026 6027 // If this is an MS ABI dllexport default constructor, instantiate any 6028 // default arguments. 6029 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) { 6030 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 6031 if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) { 6032 S.InstantiateDefaultCtorDefaultArgs(CD); 6033 } 6034 } 6035 6036 S.MarkFunctionReferenced(Class->getLocation(), MD); 6037 6038 // The function will be passed to the consumer when its definition is 6039 // encountered. 6040 } else if (MD->isExplicitlyDefaulted()) { 6041 // Synthesize and instantiate explicitly defaulted methods. 6042 S.MarkFunctionReferenced(Class->getLocation(), MD); 6043 6044 if (TSK != TSK_ExplicitInstantiationDefinition) { 6045 // Except for explicit instantiation defs, we will not see the 6046 // definition again later, so pass it to the consumer now. 6047 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 6048 } 6049 } else if (!MD->isTrivial() || 6050 MD->isCopyAssignmentOperator() || 6051 MD->isMoveAssignmentOperator()) { 6052 // Synthesize and instantiate non-trivial implicit methods, and the copy 6053 // and move assignment operators. The latter are exported even if they 6054 // are trivial, because the address of an operator can be taken and 6055 // should compare equal across libraries. 6056 S.MarkFunctionReferenced(Class->getLocation(), MD); 6057 6058 // There is no later point when we will see the definition of this 6059 // function, so pass it to the consumer now. 6060 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 6061 } 6062 } 6063 } 6064 6065 static void checkForMultipleExportedDefaultConstructors(Sema &S, 6066 CXXRecordDecl *Class) { 6067 // Only the MS ABI has default constructor closures, so we don't need to do 6068 // this semantic checking anywhere else. 6069 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft()) 6070 return; 6071 6072 CXXConstructorDecl *LastExportedDefaultCtor = nullptr; 6073 for (Decl *Member : Class->decls()) { 6074 // Look for exported default constructors. 6075 auto *CD = dyn_cast<CXXConstructorDecl>(Member); 6076 if (!CD || !CD->isDefaultConstructor()) 6077 continue; 6078 auto *Attr = CD->getAttr<DLLExportAttr>(); 6079 if (!Attr) 6080 continue; 6081 6082 // If the class is non-dependent, mark the default arguments as ODR-used so 6083 // that we can properly codegen the constructor closure. 6084 if (!Class->isDependentContext()) { 6085 for (ParmVarDecl *PD : CD->parameters()) { 6086 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD); 6087 S.DiscardCleanupsInEvaluationContext(); 6088 } 6089 } 6090 6091 if (LastExportedDefaultCtor) { 6092 S.Diag(LastExportedDefaultCtor->getLocation(), 6093 diag::err_attribute_dll_ambiguous_default_ctor) 6094 << Class; 6095 S.Diag(CD->getLocation(), diag::note_entity_declared_at) 6096 << CD->getDeclName(); 6097 return; 6098 } 6099 LastExportedDefaultCtor = CD; 6100 } 6101 } 6102 6103 static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S, 6104 CXXRecordDecl *Class) { 6105 bool ErrorReported = false; 6106 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S, 6107 ClassTemplateDecl *TD) { 6108 if (ErrorReported) 6109 return; 6110 S.Diag(TD->getLocation(), 6111 diag::err_cuda_device_builtin_surftex_cls_template) 6112 << /*surface*/ 0 << TD; 6113 ErrorReported = true; 6114 }; 6115 6116 ClassTemplateDecl *TD = Class->getDescribedClassTemplate(); 6117 if (!TD) { 6118 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class); 6119 if (!SD) { 6120 S.Diag(Class->getLocation(), 6121 diag::err_cuda_device_builtin_surftex_ref_decl) 6122 << /*surface*/ 0 << Class; 6123 S.Diag(Class->getLocation(), 6124 diag::note_cuda_device_builtin_surftex_should_be_template_class) 6125 << Class; 6126 return; 6127 } 6128 TD = SD->getSpecializedTemplate(); 6129 } 6130 6131 TemplateParameterList *Params = TD->getTemplateParameters(); 6132 unsigned N = Params->size(); 6133 6134 if (N != 2) { 6135 reportIllegalClassTemplate(S, TD); 6136 S.Diag(TD->getLocation(), 6137 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args) 6138 << TD << 2; 6139 } 6140 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 6141 reportIllegalClassTemplate(S, TD); 6142 S.Diag(TD->getLocation(), 6143 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6144 << TD << /*1st*/ 0 << /*type*/ 0; 6145 } 6146 if (N > 1) { 6147 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 6148 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 6149 reportIllegalClassTemplate(S, TD); 6150 S.Diag(TD->getLocation(), 6151 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6152 << TD << /*2nd*/ 1 << /*integer*/ 1; 6153 } 6154 } 6155 } 6156 6157 static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S, 6158 CXXRecordDecl *Class) { 6159 bool ErrorReported = false; 6160 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S, 6161 ClassTemplateDecl *TD) { 6162 if (ErrorReported) 6163 return; 6164 S.Diag(TD->getLocation(), 6165 diag::err_cuda_device_builtin_surftex_cls_template) 6166 << /*texture*/ 1 << TD; 6167 ErrorReported = true; 6168 }; 6169 6170 ClassTemplateDecl *TD = Class->getDescribedClassTemplate(); 6171 if (!TD) { 6172 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class); 6173 if (!SD) { 6174 S.Diag(Class->getLocation(), 6175 diag::err_cuda_device_builtin_surftex_ref_decl) 6176 << /*texture*/ 1 << Class; 6177 S.Diag(Class->getLocation(), 6178 diag::note_cuda_device_builtin_surftex_should_be_template_class) 6179 << Class; 6180 return; 6181 } 6182 TD = SD->getSpecializedTemplate(); 6183 } 6184 6185 TemplateParameterList *Params = TD->getTemplateParameters(); 6186 unsigned N = Params->size(); 6187 6188 if (N != 3) { 6189 reportIllegalClassTemplate(S, TD); 6190 S.Diag(TD->getLocation(), 6191 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args) 6192 << TD << 3; 6193 } 6194 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 6195 reportIllegalClassTemplate(S, TD); 6196 S.Diag(TD->getLocation(), 6197 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6198 << TD << /*1st*/ 0 << /*type*/ 0; 6199 } 6200 if (N > 1) { 6201 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 6202 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 6203 reportIllegalClassTemplate(S, TD); 6204 S.Diag(TD->getLocation(), 6205 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6206 << TD << /*2nd*/ 1 << /*integer*/ 1; 6207 } 6208 } 6209 if (N > 2) { 6210 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2)); 6211 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 6212 reportIllegalClassTemplate(S, TD); 6213 S.Diag(TD->getLocation(), 6214 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6215 << TD << /*3rd*/ 2 << /*integer*/ 1; 6216 } 6217 } 6218 } 6219 6220 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) { 6221 // Mark any compiler-generated routines with the implicit code_seg attribute. 6222 for (auto *Method : Class->methods()) { 6223 if (Method->isUserProvided()) 6224 continue; 6225 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true)) 6226 Method->addAttr(A); 6227 } 6228 } 6229 6230 /// Check class-level dllimport/dllexport attribute. 6231 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) { 6232 Attr *ClassAttr = getDLLAttr(Class); 6233 6234 // MSVC inherits DLL attributes to partial class template specializations. 6235 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) { 6236 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 6237 if (Attr *TemplateAttr = 6238 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 6239 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext())); 6240 A->setInherited(true); 6241 ClassAttr = A; 6242 } 6243 } 6244 } 6245 6246 if (!ClassAttr) 6247 return; 6248 6249 if (!Class->isExternallyVisible()) { 6250 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) 6251 << Class << ClassAttr; 6252 return; 6253 } 6254 6255 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && 6256 !ClassAttr->isInherited()) { 6257 // Diagnose dll attributes on members of class with dll attribute. 6258 for (Decl *Member : Class->decls()) { 6259 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 6260 continue; 6261 InheritableAttr *MemberAttr = getDLLAttr(Member); 6262 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 6263 continue; 6264 6265 Diag(MemberAttr->getLocation(), 6266 diag::err_attribute_dll_member_of_dll_class) 6267 << MemberAttr << ClassAttr; 6268 Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 6269 Member->setInvalidDecl(); 6270 } 6271 } 6272 6273 if (Class->getDescribedClassTemplate()) 6274 // Don't inherit dll attribute until the template is instantiated. 6275 return; 6276 6277 // The class is either imported or exported. 6278 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 6279 6280 // Check if this was a dllimport attribute propagated from a derived class to 6281 // a base class template specialization. We don't apply these attributes to 6282 // static data members. 6283 const bool PropagatedImport = 6284 !ClassExported && 6285 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate(); 6286 6287 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 6288 6289 // Ignore explicit dllexport on explicit class template instantiation 6290 // declarations, except in MinGW mode. 6291 if (ClassExported && !ClassAttr->isInherited() && 6292 TSK == TSK_ExplicitInstantiationDeclaration && 6293 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) { 6294 Class->dropAttr<DLLExportAttr>(); 6295 return; 6296 } 6297 6298 // Force declaration of implicit members so they can inherit the attribute. 6299 ForceDeclarationOfImplicitMembers(Class); 6300 6301 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 6302 // seem to be true in practice? 6303 6304 for (Decl *Member : Class->decls()) { 6305 VarDecl *VD = dyn_cast<VarDecl>(Member); 6306 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 6307 6308 // Only methods and static fields inherit the attributes. 6309 if (!VD && !MD) 6310 continue; 6311 6312 if (MD) { 6313 // Don't process deleted methods. 6314 if (MD->isDeleted()) 6315 continue; 6316 6317 if (MD->isInlined()) { 6318 // MinGW does not import or export inline methods. But do it for 6319 // template instantiations. 6320 if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() && 6321 TSK != TSK_ExplicitInstantiationDeclaration && 6322 TSK != TSK_ExplicitInstantiationDefinition) 6323 continue; 6324 6325 // MSVC versions before 2015 don't export the move assignment operators 6326 // and move constructor, so don't attempt to import/export them if 6327 // we have a definition. 6328 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD); 6329 if ((MD->isMoveAssignmentOperator() || 6330 (Ctor && Ctor->isMoveConstructor())) && 6331 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015)) 6332 continue; 6333 6334 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign 6335 // operator is exported anyway. 6336 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 6337 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial()) 6338 continue; 6339 } 6340 } 6341 6342 // Don't apply dllimport attributes to static data members of class template 6343 // instantiations when the attribute is propagated from a derived class. 6344 if (VD && PropagatedImport) 6345 continue; 6346 6347 if (!cast<NamedDecl>(Member)->isExternallyVisible()) 6348 continue; 6349 6350 if (!getDLLAttr(Member)) { 6351 InheritableAttr *NewAttr = nullptr; 6352 6353 // Do not export/import inline function when -fno-dllexport-inlines is 6354 // passed. But add attribute for later local static var check. 6355 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() && 6356 TSK != TSK_ExplicitInstantiationDeclaration && 6357 TSK != TSK_ExplicitInstantiationDefinition) { 6358 if (ClassExported) { 6359 NewAttr = ::new (getASTContext()) 6360 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr); 6361 } else { 6362 NewAttr = ::new (getASTContext()) 6363 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr); 6364 } 6365 } else { 6366 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6367 } 6368 6369 NewAttr->setInherited(true); 6370 Member->addAttr(NewAttr); 6371 6372 if (MD) { 6373 // Propagate DLLAttr to friend re-declarations of MD that have already 6374 // been constructed. 6375 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD; 6376 FD = FD->getPreviousDecl()) { 6377 if (FD->getFriendObjectKind() == Decl::FOK_None) 6378 continue; 6379 assert(!getDLLAttr(FD) && 6380 "friend re-decl should not already have a DLLAttr"); 6381 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6382 NewAttr->setInherited(true); 6383 FD->addAttr(NewAttr); 6384 } 6385 } 6386 } 6387 } 6388 6389 if (ClassExported) 6390 DelayedDllExportClasses.push_back(Class); 6391 } 6392 6393 /// Perform propagation of DLL attributes from a derived class to a 6394 /// templated base class for MS compatibility. 6395 void Sema::propagateDLLAttrToBaseClassTemplate( 6396 CXXRecordDecl *Class, Attr *ClassAttr, 6397 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 6398 if (getDLLAttr( 6399 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 6400 // If the base class template has a DLL attribute, don't try to change it. 6401 return; 6402 } 6403 6404 auto TSK = BaseTemplateSpec->getSpecializationKind(); 6405 if (!getDLLAttr(BaseTemplateSpec) && 6406 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration || 6407 TSK == TSK_ImplicitInstantiation)) { 6408 // The template hasn't been instantiated yet (or it has, but only as an 6409 // explicit instantiation declaration or implicit instantiation, which means 6410 // we haven't codegenned any members yet), so propagate the attribute. 6411 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6412 NewAttr->setInherited(true); 6413 BaseTemplateSpec->addAttr(NewAttr); 6414 6415 // If this was an import, mark that we propagated it from a derived class to 6416 // a base class template specialization. 6417 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr)) 6418 ImportAttr->setPropagatedToBaseTemplate(); 6419 6420 // If the template is already instantiated, checkDLLAttributeRedeclaration() 6421 // needs to be run again to work see the new attribute. Otherwise this will 6422 // get run whenever the template is instantiated. 6423 if (TSK != TSK_Undeclared) 6424 checkClassLevelDLLAttribute(BaseTemplateSpec); 6425 6426 return; 6427 } 6428 6429 if (getDLLAttr(BaseTemplateSpec)) { 6430 // The template has already been specialized or instantiated with an 6431 // attribute, explicitly or through propagation. We should not try to change 6432 // it. 6433 return; 6434 } 6435 6436 // The template was previously instantiated or explicitly specialized without 6437 // a dll attribute, It's too late for us to add an attribute, so warn that 6438 // this is unsupported. 6439 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 6440 << BaseTemplateSpec->isExplicitSpecialization(); 6441 Diag(ClassAttr->getLocation(), diag::note_attribute); 6442 if (BaseTemplateSpec->isExplicitSpecialization()) { 6443 Diag(BaseTemplateSpec->getLocation(), 6444 diag::note_template_class_explicit_specialization_was_here) 6445 << BaseTemplateSpec; 6446 } else { 6447 Diag(BaseTemplateSpec->getPointOfInstantiation(), 6448 diag::note_template_class_instantiation_was_here) 6449 << BaseTemplateSpec; 6450 } 6451 } 6452 6453 /// Determine the kind of defaulting that would be done for a given function. 6454 /// 6455 /// If the function is both a default constructor and a copy / move constructor 6456 /// (due to having a default argument for the first parameter), this picks 6457 /// CXXDefaultConstructor. 6458 /// 6459 /// FIXME: Check that case is properly handled by all callers. 6460 Sema::DefaultedFunctionKind 6461 Sema::getDefaultedFunctionKind(const FunctionDecl *FD) { 6462 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 6463 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 6464 if (Ctor->isDefaultConstructor()) 6465 return Sema::CXXDefaultConstructor; 6466 6467 if (Ctor->isCopyConstructor()) 6468 return Sema::CXXCopyConstructor; 6469 6470 if (Ctor->isMoveConstructor()) 6471 return Sema::CXXMoveConstructor; 6472 } 6473 6474 if (MD->isCopyAssignmentOperator()) 6475 return Sema::CXXCopyAssignment; 6476 6477 if (MD->isMoveAssignmentOperator()) 6478 return Sema::CXXMoveAssignment; 6479 6480 if (isa<CXXDestructorDecl>(FD)) 6481 return Sema::CXXDestructor; 6482 } 6483 6484 switch (FD->getDeclName().getCXXOverloadedOperator()) { 6485 case OO_EqualEqual: 6486 return DefaultedComparisonKind::Equal; 6487 6488 case OO_ExclaimEqual: 6489 return DefaultedComparisonKind::NotEqual; 6490 6491 case OO_Spaceship: 6492 // No point allowing this if <=> doesn't exist in the current language mode. 6493 if (!getLangOpts().CPlusPlus20) 6494 break; 6495 return DefaultedComparisonKind::ThreeWay; 6496 6497 case OO_Less: 6498 case OO_LessEqual: 6499 case OO_Greater: 6500 case OO_GreaterEqual: 6501 // No point allowing this if <=> doesn't exist in the current language mode. 6502 if (!getLangOpts().CPlusPlus20) 6503 break; 6504 return DefaultedComparisonKind::Relational; 6505 6506 default: 6507 break; 6508 } 6509 6510 // Not defaultable. 6511 return DefaultedFunctionKind(); 6512 } 6513 6514 static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD, 6515 SourceLocation DefaultLoc) { 6516 Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD); 6517 if (DFK.isComparison()) 6518 return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison()); 6519 6520 switch (DFK.asSpecialMember()) { 6521 case Sema::CXXDefaultConstructor: 6522 S.DefineImplicitDefaultConstructor(DefaultLoc, 6523 cast<CXXConstructorDecl>(FD)); 6524 break; 6525 case Sema::CXXCopyConstructor: 6526 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD)); 6527 break; 6528 case Sema::CXXCopyAssignment: 6529 S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD)); 6530 break; 6531 case Sema::CXXDestructor: 6532 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD)); 6533 break; 6534 case Sema::CXXMoveConstructor: 6535 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD)); 6536 break; 6537 case Sema::CXXMoveAssignment: 6538 S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD)); 6539 break; 6540 case Sema::CXXInvalid: 6541 llvm_unreachable("Invalid special member."); 6542 } 6543 } 6544 6545 /// Determine whether a type is permitted to be passed or returned in 6546 /// registers, per C++ [class.temporary]p3. 6547 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D, 6548 TargetInfo::CallingConvKind CCK) { 6549 if (D->isDependentType() || D->isInvalidDecl()) 6550 return false; 6551 6552 // Clang <= 4 used the pre-C++11 rule, which ignores move operations. 6553 // The PS4 platform ABI follows the behavior of Clang 3.2. 6554 if (CCK == TargetInfo::CCK_ClangABI4OrPS4) 6555 return !D->hasNonTrivialDestructorForCall() && 6556 !D->hasNonTrivialCopyConstructorForCall(); 6557 6558 if (CCK == TargetInfo::CCK_MicrosoftWin64) { 6559 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false; 6560 bool DtorIsTrivialForCall = false; 6561 6562 // If a class has at least one non-deleted, trivial copy constructor, it 6563 // is passed according to the C ABI. Otherwise, it is passed indirectly. 6564 // 6565 // Note: This permits classes with non-trivial copy or move ctors to be 6566 // passed in registers, so long as they *also* have a trivial copy ctor, 6567 // which is non-conforming. 6568 if (D->needsImplicitCopyConstructor()) { 6569 if (!D->defaultedCopyConstructorIsDeleted()) { 6570 if (D->hasTrivialCopyConstructor()) 6571 CopyCtorIsTrivial = true; 6572 if (D->hasTrivialCopyConstructorForCall()) 6573 CopyCtorIsTrivialForCall = true; 6574 } 6575 } else { 6576 for (const CXXConstructorDecl *CD : D->ctors()) { 6577 if (CD->isCopyConstructor() && !CD->isDeleted()) { 6578 if (CD->isTrivial()) 6579 CopyCtorIsTrivial = true; 6580 if (CD->isTrivialForCall()) 6581 CopyCtorIsTrivialForCall = true; 6582 } 6583 } 6584 } 6585 6586 if (D->needsImplicitDestructor()) { 6587 if (!D->defaultedDestructorIsDeleted() && 6588 D->hasTrivialDestructorForCall()) 6589 DtorIsTrivialForCall = true; 6590 } else if (const auto *DD = D->getDestructor()) { 6591 if (!DD->isDeleted() && DD->isTrivialForCall()) 6592 DtorIsTrivialForCall = true; 6593 } 6594 6595 // If the copy ctor and dtor are both trivial-for-calls, pass direct. 6596 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall) 6597 return true; 6598 6599 // If a class has a destructor, we'd really like to pass it indirectly 6600 // because it allows us to elide copies. Unfortunately, MSVC makes that 6601 // impossible for small types, which it will pass in a single register or 6602 // stack slot. Most objects with dtors are large-ish, so handle that early. 6603 // We can't call out all large objects as being indirect because there are 6604 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate 6605 // how we pass large POD types. 6606 6607 // Note: This permits small classes with nontrivial destructors to be 6608 // passed in registers, which is non-conforming. 6609 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64(); 6610 uint64_t TypeSize = isAArch64 ? 128 : 64; 6611 6612 if (CopyCtorIsTrivial && 6613 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize) 6614 return true; 6615 return false; 6616 } 6617 6618 // Per C++ [class.temporary]p3, the relevant condition is: 6619 // each copy constructor, move constructor, and destructor of X is 6620 // either trivial or deleted, and X has at least one non-deleted copy 6621 // or move constructor 6622 bool HasNonDeletedCopyOrMove = false; 6623 6624 if (D->needsImplicitCopyConstructor() && 6625 !D->defaultedCopyConstructorIsDeleted()) { 6626 if (!D->hasTrivialCopyConstructorForCall()) 6627 return false; 6628 HasNonDeletedCopyOrMove = true; 6629 } 6630 6631 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() && 6632 !D->defaultedMoveConstructorIsDeleted()) { 6633 if (!D->hasTrivialMoveConstructorForCall()) 6634 return false; 6635 HasNonDeletedCopyOrMove = true; 6636 } 6637 6638 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() && 6639 !D->hasTrivialDestructorForCall()) 6640 return false; 6641 6642 for (const CXXMethodDecl *MD : D->methods()) { 6643 if (MD->isDeleted()) 6644 continue; 6645 6646 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 6647 if (CD && CD->isCopyOrMoveConstructor()) 6648 HasNonDeletedCopyOrMove = true; 6649 else if (!isa<CXXDestructorDecl>(MD)) 6650 continue; 6651 6652 if (!MD->isTrivialForCall()) 6653 return false; 6654 } 6655 6656 return HasNonDeletedCopyOrMove; 6657 } 6658 6659 /// Report an error regarding overriding, along with any relevant 6660 /// overridden methods. 6661 /// 6662 /// \param DiagID the primary error to report. 6663 /// \param MD the overriding method. 6664 static bool 6665 ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD, 6666 llvm::function_ref<bool(const CXXMethodDecl *)> Report) { 6667 bool IssuedDiagnostic = false; 6668 for (const CXXMethodDecl *O : MD->overridden_methods()) { 6669 if (Report(O)) { 6670 if (!IssuedDiagnostic) { 6671 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 6672 IssuedDiagnostic = true; 6673 } 6674 S.Diag(O->getLocation(), diag::note_overridden_virtual_function); 6675 } 6676 } 6677 return IssuedDiagnostic; 6678 } 6679 6680 /// Perform semantic checks on a class definition that has been 6681 /// completing, introducing implicitly-declared members, checking for 6682 /// abstract types, etc. 6683 /// 6684 /// \param S The scope in which the class was parsed. Null if we didn't just 6685 /// parse a class definition. 6686 /// \param Record The completed class. 6687 void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) { 6688 if (!Record) 6689 return; 6690 6691 if (Record->isAbstract() && !Record->isInvalidDecl()) { 6692 AbstractUsageInfo Info(*this, Record); 6693 CheckAbstractClassUsage(Info, Record); 6694 } 6695 6696 // If this is not an aggregate type and has no user-declared constructor, 6697 // complain about any non-static data members of reference or const scalar 6698 // type, since they will never get initializers. 6699 if (!Record->isInvalidDecl() && !Record->isDependentType() && 6700 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 6701 !Record->isLambda()) { 6702 bool Complained = false; 6703 for (const auto *F : Record->fields()) { 6704 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 6705 continue; 6706 6707 if (F->getType()->isReferenceType() || 6708 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 6709 if (!Complained) { 6710 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 6711 << Record->getTagKind() << Record; 6712 Complained = true; 6713 } 6714 6715 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 6716 << F->getType()->isReferenceType() 6717 << F->getDeclName(); 6718 } 6719 } 6720 } 6721 6722 if (Record->getIdentifier()) { 6723 // C++ [class.mem]p13: 6724 // If T is the name of a class, then each of the following shall have a 6725 // name different from T: 6726 // - every member of every anonymous union that is a member of class T. 6727 // 6728 // C++ [class.mem]p14: 6729 // In addition, if class T has a user-declared constructor (12.1), every 6730 // non-static data member of class T shall have a name different from T. 6731 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 6732 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 6733 ++I) { 6734 NamedDecl *D = (*I)->getUnderlyingDecl(); 6735 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) && 6736 Record->hasUserDeclaredConstructor()) || 6737 isa<IndirectFieldDecl>(D)) { 6738 Diag((*I)->getLocation(), diag::err_member_name_of_class) 6739 << D->getDeclName(); 6740 break; 6741 } 6742 } 6743 } 6744 6745 // Warn if the class has virtual methods but non-virtual public destructor. 6746 if (Record->isPolymorphic() && !Record->isDependentType()) { 6747 CXXDestructorDecl *dtor = Record->getDestructor(); 6748 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 6749 !Record->hasAttr<FinalAttr>()) 6750 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 6751 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 6752 } 6753 6754 if (Record->isAbstract()) { 6755 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 6756 Diag(Record->getLocation(), diag::warn_abstract_final_class) 6757 << FA->isSpelledAsSealed(); 6758 DiagnoseAbstractType(Record); 6759 } 6760 } 6761 6762 // Warn if the class has a final destructor but is not itself marked final. 6763 if (!Record->hasAttr<FinalAttr>()) { 6764 if (const CXXDestructorDecl *dtor = Record->getDestructor()) { 6765 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) { 6766 Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class) 6767 << FA->isSpelledAsSealed() 6768 << FixItHint::CreateInsertion( 6769 getLocForEndOfToken(Record->getLocation()), 6770 (FA->isSpelledAsSealed() ? " sealed" : " final")); 6771 Diag(Record->getLocation(), 6772 diag::note_final_dtor_non_final_class_silence) 6773 << Context.getRecordType(Record) << FA->isSpelledAsSealed(); 6774 } 6775 } 6776 } 6777 6778 // See if trivial_abi has to be dropped. 6779 if (Record->hasAttr<TrivialABIAttr>()) 6780 checkIllFormedTrivialABIStruct(*Record); 6781 6782 // Set HasTrivialSpecialMemberForCall if the record has attribute 6783 // "trivial_abi". 6784 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>(); 6785 6786 if (HasTrivialABI) 6787 Record->setHasTrivialSpecialMemberForCall(); 6788 6789 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=). 6790 // We check these last because they can depend on the properties of the 6791 // primary comparison functions (==, <=>). 6792 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons; 6793 6794 // Perform checks that can't be done until we know all the properties of a 6795 // member function (whether it's defaulted, deleted, virtual, overriding, 6796 // ...). 6797 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) { 6798 // A static function cannot override anything. 6799 if (MD->getStorageClass() == SC_Static) { 6800 if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD, 6801 [](const CXXMethodDecl *) { return true; })) 6802 return; 6803 } 6804 6805 // A deleted function cannot override a non-deleted function and vice 6806 // versa. 6807 if (ReportOverrides(*this, 6808 MD->isDeleted() ? diag::err_deleted_override 6809 : diag::err_non_deleted_override, 6810 MD, [&](const CXXMethodDecl *V) { 6811 return MD->isDeleted() != V->isDeleted(); 6812 })) { 6813 if (MD->isDefaulted() && MD->isDeleted()) 6814 // Explain why this defaulted function was deleted. 6815 DiagnoseDeletedDefaultedFunction(MD); 6816 return; 6817 } 6818 6819 // A consteval function cannot override a non-consteval function and vice 6820 // versa. 6821 if (ReportOverrides(*this, 6822 MD->isConsteval() ? diag::err_consteval_override 6823 : diag::err_non_consteval_override, 6824 MD, [&](const CXXMethodDecl *V) { 6825 return MD->isConsteval() != V->isConsteval(); 6826 })) { 6827 if (MD->isDefaulted() && MD->isDeleted()) 6828 // Explain why this defaulted function was deleted. 6829 DiagnoseDeletedDefaultedFunction(MD); 6830 return; 6831 } 6832 }; 6833 6834 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool { 6835 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted()) 6836 return false; 6837 6838 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD); 6839 if (DFK.asComparison() == DefaultedComparisonKind::NotEqual || 6840 DFK.asComparison() == DefaultedComparisonKind::Relational) { 6841 DefaultedSecondaryComparisons.push_back(FD); 6842 return true; 6843 } 6844 6845 CheckExplicitlyDefaultedFunction(S, FD); 6846 return false; 6847 }; 6848 6849 auto CompleteMemberFunction = [&](CXXMethodDecl *M) { 6850 // Check whether the explicitly-defaulted members are valid. 6851 bool Incomplete = CheckForDefaultedFunction(M); 6852 6853 // Skip the rest of the checks for a member of a dependent class. 6854 if (Record->isDependentType()) 6855 return; 6856 6857 // For an explicitly defaulted or deleted special member, we defer 6858 // determining triviality until the class is complete. That time is now! 6859 CXXSpecialMember CSM = getSpecialMember(M); 6860 if (!M->isImplicit() && !M->isUserProvided()) { 6861 if (CSM != CXXInvalid) { 6862 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 6863 // Inform the class that we've finished declaring this member. 6864 Record->finishedDefaultedOrDeletedMember(M); 6865 M->setTrivialForCall( 6866 HasTrivialABI || 6867 SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI)); 6868 Record->setTrivialForCallFlags(M); 6869 } 6870 } 6871 6872 // Set triviality for the purpose of calls if this is a user-provided 6873 // copy/move constructor or destructor. 6874 if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor || 6875 CSM == CXXDestructor) && M->isUserProvided()) { 6876 M->setTrivialForCall(HasTrivialABI); 6877 Record->setTrivialForCallFlags(M); 6878 } 6879 6880 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() && 6881 M->hasAttr<DLLExportAttr>()) { 6882 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 6883 M->isTrivial() && 6884 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor || 6885 CSM == CXXDestructor)) 6886 M->dropAttr<DLLExportAttr>(); 6887 6888 if (M->hasAttr<DLLExportAttr>()) { 6889 // Define after any fields with in-class initializers have been parsed. 6890 DelayedDllExportMemberFunctions.push_back(M); 6891 } 6892 } 6893 6894 // Define defaulted constexpr virtual functions that override a base class 6895 // function right away. 6896 // FIXME: We can defer doing this until the vtable is marked as used. 6897 if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods()) 6898 DefineDefaultedFunction(*this, M, M->getLocation()); 6899 6900 if (!Incomplete) 6901 CheckCompletedMemberFunction(M); 6902 }; 6903 6904 // Check the destructor before any other member function. We need to 6905 // determine whether it's trivial in order to determine whether the claas 6906 // type is a literal type, which is a prerequisite for determining whether 6907 // other special member functions are valid and whether they're implicitly 6908 // 'constexpr'. 6909 if (CXXDestructorDecl *Dtor = Record->getDestructor()) 6910 CompleteMemberFunction(Dtor); 6911 6912 bool HasMethodWithOverrideControl = false, 6913 HasOverridingMethodWithoutOverrideControl = false; 6914 for (auto *D : Record->decls()) { 6915 if (auto *M = dyn_cast<CXXMethodDecl>(D)) { 6916 // FIXME: We could do this check for dependent types with non-dependent 6917 // bases. 6918 if (!Record->isDependentType()) { 6919 // See if a method overloads virtual methods in a base 6920 // class without overriding any. 6921 if (!M->isStatic()) 6922 DiagnoseHiddenVirtualMethods(M); 6923 if (M->hasAttr<OverrideAttr>()) 6924 HasMethodWithOverrideControl = true; 6925 else if (M->size_overridden_methods() > 0) 6926 HasOverridingMethodWithoutOverrideControl = true; 6927 } 6928 6929 if (!isa<CXXDestructorDecl>(M)) 6930 CompleteMemberFunction(M); 6931 } else if (auto *F = dyn_cast<FriendDecl>(D)) { 6932 CheckForDefaultedFunction( 6933 dyn_cast_or_null<FunctionDecl>(F->getFriendDecl())); 6934 } 6935 } 6936 6937 if (HasOverridingMethodWithoutOverrideControl) { 6938 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl; 6939 for (auto *M : Record->methods()) 6940 DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl); 6941 } 6942 6943 // Check the defaulted secondary comparisons after any other member functions. 6944 for (FunctionDecl *FD : DefaultedSecondaryComparisons) { 6945 CheckExplicitlyDefaultedFunction(S, FD); 6946 6947 // If this is a member function, we deferred checking it until now. 6948 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) 6949 CheckCompletedMemberFunction(MD); 6950 } 6951 6952 // ms_struct is a request to use the same ABI rules as MSVC. Check 6953 // whether this class uses any C++ features that are implemented 6954 // completely differently in MSVC, and if so, emit a diagnostic. 6955 // That diagnostic defaults to an error, but we allow projects to 6956 // map it down to a warning (or ignore it). It's a fairly common 6957 // practice among users of the ms_struct pragma to mass-annotate 6958 // headers, sweeping up a bunch of types that the project doesn't 6959 // really rely on MSVC-compatible layout for. We must therefore 6960 // support "ms_struct except for C++ stuff" as a secondary ABI. 6961 // Don't emit this diagnostic if the feature was enabled as a 6962 // language option (as opposed to via a pragma or attribute), as 6963 // the option -mms-bitfields otherwise essentially makes it impossible 6964 // to build C++ code, unless this diagnostic is turned off. 6965 if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields && 6966 (Record->isPolymorphic() || Record->getNumBases())) { 6967 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 6968 } 6969 6970 checkClassLevelDLLAttribute(Record); 6971 checkClassLevelCodeSegAttribute(Record); 6972 6973 bool ClangABICompat4 = 6974 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4; 6975 TargetInfo::CallingConvKind CCK = 6976 Context.getTargetInfo().getCallingConvKind(ClangABICompat4); 6977 bool CanPass = canPassInRegisters(*this, Record, CCK); 6978 6979 // Do not change ArgPassingRestrictions if it has already been set to 6980 // APK_CanNeverPassInRegs. 6981 if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs) 6982 Record->setArgPassingRestrictions(CanPass 6983 ? RecordDecl::APK_CanPassInRegs 6984 : RecordDecl::APK_CannotPassInRegs); 6985 6986 // If canPassInRegisters returns true despite the record having a non-trivial 6987 // destructor, the record is destructed in the callee. This happens only when 6988 // the record or one of its subobjects has a field annotated with trivial_abi 6989 // or a field qualified with ObjC __strong/__weak. 6990 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee()) 6991 Record->setParamDestroyedInCallee(true); 6992 else if (Record->hasNonTrivialDestructor()) 6993 Record->setParamDestroyedInCallee(CanPass); 6994 6995 if (getLangOpts().ForceEmitVTables) { 6996 // If we want to emit all the vtables, we need to mark it as used. This 6997 // is especially required for cases like vtable assumption loads. 6998 MarkVTableUsed(Record->getInnerLocStart(), Record); 6999 } 7000 7001 if (getLangOpts().CUDA) { 7002 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>()) 7003 checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record); 7004 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>()) 7005 checkCUDADeviceBuiltinTextureClassTemplate(*this, Record); 7006 } 7007 } 7008 7009 /// Look up the special member function that would be called by a special 7010 /// member function for a subobject of class type. 7011 /// 7012 /// \param Class The class type of the subobject. 7013 /// \param CSM The kind of special member function. 7014 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 7015 /// \param ConstRHS True if this is a copy operation with a const object 7016 /// on its RHS, that is, if the argument to the outer special member 7017 /// function is 'const' and this is not a field marked 'mutable'. 7018 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember( 7019 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 7020 unsigned FieldQuals, bool ConstRHS) { 7021 unsigned LHSQuals = 0; 7022 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 7023 LHSQuals = FieldQuals; 7024 7025 unsigned RHSQuals = FieldQuals; 7026 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 7027 RHSQuals = 0; 7028 else if (ConstRHS) 7029 RHSQuals |= Qualifiers::Const; 7030 7031 return S.LookupSpecialMember(Class, CSM, 7032 RHSQuals & Qualifiers::Const, 7033 RHSQuals & Qualifiers::Volatile, 7034 false, 7035 LHSQuals & Qualifiers::Const, 7036 LHSQuals & Qualifiers::Volatile); 7037 } 7038 7039 class Sema::InheritedConstructorInfo { 7040 Sema &S; 7041 SourceLocation UseLoc; 7042 7043 /// A mapping from the base classes through which the constructor was 7044 /// inherited to the using shadow declaration in that base class (or a null 7045 /// pointer if the constructor was declared in that base class). 7046 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *> 7047 InheritedFromBases; 7048 7049 public: 7050 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, 7051 ConstructorUsingShadowDecl *Shadow) 7052 : S(S), UseLoc(UseLoc) { 7053 bool DiagnosedMultipleConstructedBases = false; 7054 CXXRecordDecl *ConstructedBase = nullptr; 7055 BaseUsingDecl *ConstructedBaseIntroducer = nullptr; 7056 7057 // Find the set of such base class subobjects and check that there's a 7058 // unique constructed subobject. 7059 for (auto *D : Shadow->redecls()) { 7060 auto *DShadow = cast<ConstructorUsingShadowDecl>(D); 7061 auto *DNominatedBase = DShadow->getNominatedBaseClass(); 7062 auto *DConstructedBase = DShadow->getConstructedBaseClass(); 7063 7064 InheritedFromBases.insert( 7065 std::make_pair(DNominatedBase->getCanonicalDecl(), 7066 DShadow->getNominatedBaseClassShadowDecl())); 7067 if (DShadow->constructsVirtualBase()) 7068 InheritedFromBases.insert( 7069 std::make_pair(DConstructedBase->getCanonicalDecl(), 7070 DShadow->getConstructedBaseClassShadowDecl())); 7071 else 7072 assert(DNominatedBase == DConstructedBase); 7073 7074 // [class.inhctor.init]p2: 7075 // If the constructor was inherited from multiple base class subobjects 7076 // of type B, the program is ill-formed. 7077 if (!ConstructedBase) { 7078 ConstructedBase = DConstructedBase; 7079 ConstructedBaseIntroducer = D->getIntroducer(); 7080 } else if (ConstructedBase != DConstructedBase && 7081 !Shadow->isInvalidDecl()) { 7082 if (!DiagnosedMultipleConstructedBases) { 7083 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor) 7084 << Shadow->getTargetDecl(); 7085 S.Diag(ConstructedBaseIntroducer->getLocation(), 7086 diag::note_ambiguous_inherited_constructor_using) 7087 << ConstructedBase; 7088 DiagnosedMultipleConstructedBases = true; 7089 } 7090 S.Diag(D->getIntroducer()->getLocation(), 7091 diag::note_ambiguous_inherited_constructor_using) 7092 << DConstructedBase; 7093 } 7094 } 7095 7096 if (DiagnosedMultipleConstructedBases) 7097 Shadow->setInvalidDecl(); 7098 } 7099 7100 /// Find the constructor to use for inherited construction of a base class, 7101 /// and whether that base class constructor inherits the constructor from a 7102 /// virtual base class (in which case it won't actually invoke it). 7103 std::pair<CXXConstructorDecl *, bool> 7104 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const { 7105 auto It = InheritedFromBases.find(Base->getCanonicalDecl()); 7106 if (It == InheritedFromBases.end()) 7107 return std::make_pair(nullptr, false); 7108 7109 // This is an intermediary class. 7110 if (It->second) 7111 return std::make_pair( 7112 S.findInheritingConstructor(UseLoc, Ctor, It->second), 7113 It->second->constructsVirtualBase()); 7114 7115 // This is the base class from which the constructor was inherited. 7116 return std::make_pair(Ctor, false); 7117 } 7118 }; 7119 7120 /// Is the special member function which would be selected to perform the 7121 /// specified operation on the specified class type a constexpr constructor? 7122 static bool 7123 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 7124 Sema::CXXSpecialMember CSM, unsigned Quals, 7125 bool ConstRHS, 7126 CXXConstructorDecl *InheritedCtor = nullptr, 7127 Sema::InheritedConstructorInfo *Inherited = nullptr) { 7128 // If we're inheriting a constructor, see if we need to call it for this base 7129 // class. 7130 if (InheritedCtor) { 7131 assert(CSM == Sema::CXXDefaultConstructor); 7132 auto BaseCtor = 7133 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first; 7134 if (BaseCtor) 7135 return BaseCtor->isConstexpr(); 7136 } 7137 7138 if (CSM == Sema::CXXDefaultConstructor) 7139 return ClassDecl->hasConstexprDefaultConstructor(); 7140 if (CSM == Sema::CXXDestructor) 7141 return ClassDecl->hasConstexprDestructor(); 7142 7143 Sema::SpecialMemberOverloadResult SMOR = 7144 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 7145 if (!SMOR.getMethod()) 7146 // A constructor we wouldn't select can't be "involved in initializing" 7147 // anything. 7148 return true; 7149 return SMOR.getMethod()->isConstexpr(); 7150 } 7151 7152 /// Determine whether the specified special member function would be constexpr 7153 /// if it were implicitly defined. 7154 static bool defaultedSpecialMemberIsConstexpr( 7155 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, 7156 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr, 7157 Sema::InheritedConstructorInfo *Inherited = nullptr) { 7158 if (!S.getLangOpts().CPlusPlus11) 7159 return false; 7160 7161 // C++11 [dcl.constexpr]p4: 7162 // In the definition of a constexpr constructor [...] 7163 bool Ctor = true; 7164 switch (CSM) { 7165 case Sema::CXXDefaultConstructor: 7166 if (Inherited) 7167 break; 7168 // Since default constructor lookup is essentially trivial (and cannot 7169 // involve, for instance, template instantiation), we compute whether a 7170 // defaulted default constructor is constexpr directly within CXXRecordDecl. 7171 // 7172 // This is important for performance; we need to know whether the default 7173 // constructor is constexpr to determine whether the type is a literal type. 7174 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 7175 7176 case Sema::CXXCopyConstructor: 7177 case Sema::CXXMoveConstructor: 7178 // For copy or move constructors, we need to perform overload resolution. 7179 break; 7180 7181 case Sema::CXXCopyAssignment: 7182 case Sema::CXXMoveAssignment: 7183 if (!S.getLangOpts().CPlusPlus14) 7184 return false; 7185 // In C++1y, we need to perform overload resolution. 7186 Ctor = false; 7187 break; 7188 7189 case Sema::CXXDestructor: 7190 return ClassDecl->defaultedDestructorIsConstexpr(); 7191 7192 case Sema::CXXInvalid: 7193 return false; 7194 } 7195 7196 // -- if the class is a non-empty union, or for each non-empty anonymous 7197 // union member of a non-union class, exactly one non-static data member 7198 // shall be initialized; [DR1359] 7199 // 7200 // If we squint, this is guaranteed, since exactly one non-static data member 7201 // will be initialized (if the constructor isn't deleted), we just don't know 7202 // which one. 7203 if (Ctor && ClassDecl->isUnion()) 7204 return CSM == Sema::CXXDefaultConstructor 7205 ? ClassDecl->hasInClassInitializer() || 7206 !ClassDecl->hasVariantMembers() 7207 : true; 7208 7209 // -- the class shall not have any virtual base classes; 7210 if (Ctor && ClassDecl->getNumVBases()) 7211 return false; 7212 7213 // C++1y [class.copy]p26: 7214 // -- [the class] is a literal type, and 7215 if (!Ctor && !ClassDecl->isLiteral()) 7216 return false; 7217 7218 // -- every constructor involved in initializing [...] base class 7219 // sub-objects shall be a constexpr constructor; 7220 // -- the assignment operator selected to copy/move each direct base 7221 // class is a constexpr function, and 7222 for (const auto &B : ClassDecl->bases()) { 7223 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 7224 if (!BaseType) continue; 7225 7226 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7227 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg, 7228 InheritedCtor, Inherited)) 7229 return false; 7230 } 7231 7232 // -- every constructor involved in initializing non-static data members 7233 // [...] shall be a constexpr constructor; 7234 // -- every non-static data member and base class sub-object shall be 7235 // initialized 7236 // -- for each non-static data member of X that is of class type (or array 7237 // thereof), the assignment operator selected to copy/move that member is 7238 // a constexpr function 7239 for (const auto *F : ClassDecl->fields()) { 7240 if (F->isInvalidDecl()) 7241 continue; 7242 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer()) 7243 continue; 7244 QualType BaseType = S.Context.getBaseElementType(F->getType()); 7245 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 7246 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 7247 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 7248 BaseType.getCVRQualifiers(), 7249 ConstArg && !F->isMutable())) 7250 return false; 7251 } else if (CSM == Sema::CXXDefaultConstructor) { 7252 return false; 7253 } 7254 } 7255 7256 // All OK, it's constexpr! 7257 return true; 7258 } 7259 7260 namespace { 7261 /// RAII object to register a defaulted function as having its exception 7262 /// specification computed. 7263 struct ComputingExceptionSpec { 7264 Sema &S; 7265 7266 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc) 7267 : S(S) { 7268 Sema::CodeSynthesisContext Ctx; 7269 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation; 7270 Ctx.PointOfInstantiation = Loc; 7271 Ctx.Entity = FD; 7272 S.pushCodeSynthesisContext(Ctx); 7273 } 7274 ~ComputingExceptionSpec() { 7275 S.popCodeSynthesisContext(); 7276 } 7277 }; 7278 } 7279 7280 static Sema::ImplicitExceptionSpecification 7281 ComputeDefaultedSpecialMemberExceptionSpec( 7282 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 7283 Sema::InheritedConstructorInfo *ICI); 7284 7285 static Sema::ImplicitExceptionSpecification 7286 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, 7287 FunctionDecl *FD, 7288 Sema::DefaultedComparisonKind DCK); 7289 7290 static Sema::ImplicitExceptionSpecification 7291 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) { 7292 auto DFK = S.getDefaultedFunctionKind(FD); 7293 if (DFK.isSpecialMember()) 7294 return ComputeDefaultedSpecialMemberExceptionSpec( 7295 S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr); 7296 if (DFK.isComparison()) 7297 return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD, 7298 DFK.asComparison()); 7299 7300 auto *CD = cast<CXXConstructorDecl>(FD); 7301 assert(CD->getInheritedConstructor() && 7302 "only defaulted functions and inherited constructors have implicit " 7303 "exception specs"); 7304 Sema::InheritedConstructorInfo ICI( 7305 S, Loc, CD->getInheritedConstructor().getShadowDecl()); 7306 return ComputeDefaultedSpecialMemberExceptionSpec( 7307 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI); 7308 } 7309 7310 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 7311 CXXMethodDecl *MD) { 7312 FunctionProtoType::ExtProtoInfo EPI; 7313 7314 // Build an exception specification pointing back at this member. 7315 EPI.ExceptionSpec.Type = EST_Unevaluated; 7316 EPI.ExceptionSpec.SourceDecl = MD; 7317 7318 // Set the calling convention to the default for C++ instance methods. 7319 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 7320 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 7321 /*IsCXXMethod=*/true)); 7322 return EPI; 7323 } 7324 7325 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) { 7326 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>(); 7327 if (FPT->getExceptionSpecType() != EST_Unevaluated) 7328 return; 7329 7330 // Evaluate the exception specification. 7331 auto IES = computeImplicitExceptionSpec(*this, Loc, FD); 7332 auto ESI = IES.getExceptionSpec(); 7333 7334 // Update the type of the special member to use it. 7335 UpdateExceptionSpec(FD, ESI); 7336 } 7337 7338 void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) { 7339 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted"); 7340 7341 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD); 7342 if (!DefKind) { 7343 assert(FD->getDeclContext()->isDependentContext()); 7344 return; 7345 } 7346 7347 if (DefKind.isComparison()) 7348 UnusedPrivateFields.clear(); 7349 7350 if (DefKind.isSpecialMember() 7351 ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD), 7352 DefKind.asSpecialMember()) 7353 : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison())) 7354 FD->setInvalidDecl(); 7355 } 7356 7357 bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD, 7358 CXXSpecialMember CSM) { 7359 CXXRecordDecl *RD = MD->getParent(); 7360 7361 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 7362 "not an explicitly-defaulted special member"); 7363 7364 // Defer all checking for special members of a dependent type. 7365 if (RD->isDependentType()) 7366 return false; 7367 7368 // Whether this was the first-declared instance of the constructor. 7369 // This affects whether we implicitly add an exception spec and constexpr. 7370 bool First = MD == MD->getCanonicalDecl(); 7371 7372 bool HadError = false; 7373 7374 // C++11 [dcl.fct.def.default]p1: 7375 // A function that is explicitly defaulted shall 7376 // -- be a special member function [...] (checked elsewhere), 7377 // -- have the same type (except for ref-qualifiers, and except that a 7378 // copy operation can take a non-const reference) as an implicit 7379 // declaration, and 7380 // -- not have default arguments. 7381 // C++2a changes the second bullet to instead delete the function if it's 7382 // defaulted on its first declaration, unless it's "an assignment operator, 7383 // and its return type differs or its parameter type is not a reference". 7384 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First; 7385 bool ShouldDeleteForTypeMismatch = false; 7386 unsigned ExpectedParams = 1; 7387 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 7388 ExpectedParams = 0; 7389 if (MD->getNumParams() != ExpectedParams) { 7390 // This checks for default arguments: a copy or move constructor with a 7391 // default argument is classified as a default constructor, and assignment 7392 // operations and destructors can't have default arguments. 7393 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 7394 << CSM << MD->getSourceRange(); 7395 HadError = true; 7396 } else if (MD->isVariadic()) { 7397 if (DeleteOnTypeMismatch) 7398 ShouldDeleteForTypeMismatch = true; 7399 else { 7400 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 7401 << CSM << MD->getSourceRange(); 7402 HadError = true; 7403 } 7404 } 7405 7406 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 7407 7408 bool CanHaveConstParam = false; 7409 if (CSM == CXXCopyConstructor) 7410 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 7411 else if (CSM == CXXCopyAssignment) 7412 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 7413 7414 QualType ReturnType = Context.VoidTy; 7415 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 7416 // Check for return type matching. 7417 ReturnType = Type->getReturnType(); 7418 7419 QualType DeclType = Context.getTypeDeclType(RD); 7420 DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace()); 7421 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType); 7422 7423 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 7424 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 7425 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 7426 HadError = true; 7427 } 7428 7429 // A defaulted special member cannot have cv-qualifiers. 7430 if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) { 7431 if (DeleteOnTypeMismatch) 7432 ShouldDeleteForTypeMismatch = true; 7433 else { 7434 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 7435 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 7436 HadError = true; 7437 } 7438 } 7439 } 7440 7441 // Check for parameter type matching. 7442 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 7443 bool HasConstParam = false; 7444 if (ExpectedParams && ArgType->isReferenceType()) { 7445 // Argument must be reference to possibly-const T. 7446 QualType ReferentType = ArgType->getPointeeType(); 7447 HasConstParam = ReferentType.isConstQualified(); 7448 7449 if (ReferentType.isVolatileQualified()) { 7450 if (DeleteOnTypeMismatch) 7451 ShouldDeleteForTypeMismatch = true; 7452 else { 7453 Diag(MD->getLocation(), 7454 diag::err_defaulted_special_member_volatile_param) << CSM; 7455 HadError = true; 7456 } 7457 } 7458 7459 if (HasConstParam && !CanHaveConstParam) { 7460 if (DeleteOnTypeMismatch) 7461 ShouldDeleteForTypeMismatch = true; 7462 else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 7463 Diag(MD->getLocation(), 7464 diag::err_defaulted_special_member_copy_const_param) 7465 << (CSM == CXXCopyAssignment); 7466 // FIXME: Explain why this special member can't be const. 7467 HadError = true; 7468 } else { 7469 Diag(MD->getLocation(), 7470 diag::err_defaulted_special_member_move_const_param) 7471 << (CSM == CXXMoveAssignment); 7472 HadError = true; 7473 } 7474 } 7475 } else if (ExpectedParams) { 7476 // A copy assignment operator can take its argument by value, but a 7477 // defaulted one cannot. 7478 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 7479 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 7480 HadError = true; 7481 } 7482 7483 // C++11 [dcl.fct.def.default]p2: 7484 // An explicitly-defaulted function may be declared constexpr only if it 7485 // would have been implicitly declared as constexpr, 7486 // Do not apply this rule to members of class templates, since core issue 1358 7487 // makes such functions always instantiate to constexpr functions. For 7488 // functions which cannot be constexpr (for non-constructors in C++11 and for 7489 // destructors in C++14 and C++17), this is checked elsewhere. 7490 // 7491 // FIXME: This should not apply if the member is deleted. 7492 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 7493 HasConstParam); 7494 if ((getLangOpts().CPlusPlus20 || 7495 (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 7496 : isa<CXXConstructorDecl>(MD))) && 7497 MD->isConstexpr() && !Constexpr && 7498 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 7499 Diag(MD->getBeginLoc(), MD->isConsteval() 7500 ? diag::err_incorrect_defaulted_consteval 7501 : diag::err_incorrect_defaulted_constexpr) 7502 << CSM; 7503 // FIXME: Explain why the special member can't be constexpr. 7504 HadError = true; 7505 } 7506 7507 if (First) { 7508 // C++2a [dcl.fct.def.default]p3: 7509 // If a function is explicitly defaulted on its first declaration, it is 7510 // implicitly considered to be constexpr if the implicit declaration 7511 // would be. 7512 MD->setConstexprKind(Constexpr ? (MD->isConsteval() 7513 ? ConstexprSpecKind::Consteval 7514 : ConstexprSpecKind::Constexpr) 7515 : ConstexprSpecKind::Unspecified); 7516 7517 if (!Type->hasExceptionSpec()) { 7518 // C++2a [except.spec]p3: 7519 // If a declaration of a function does not have a noexcept-specifier 7520 // [and] is defaulted on its first declaration, [...] the exception 7521 // specification is as specified below 7522 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 7523 EPI.ExceptionSpec.Type = EST_Unevaluated; 7524 EPI.ExceptionSpec.SourceDecl = MD; 7525 MD->setType(Context.getFunctionType(ReturnType, 7526 llvm::makeArrayRef(&ArgType, 7527 ExpectedParams), 7528 EPI)); 7529 } 7530 } 7531 7532 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) { 7533 if (First) { 7534 SetDeclDeleted(MD, MD->getLocation()); 7535 if (!inTemplateInstantiation() && !HadError) { 7536 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM; 7537 if (ShouldDeleteForTypeMismatch) { 7538 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM; 7539 } else { 7540 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 7541 } 7542 } 7543 if (ShouldDeleteForTypeMismatch && !HadError) { 7544 Diag(MD->getLocation(), 7545 diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM; 7546 } 7547 } else { 7548 // C++11 [dcl.fct.def.default]p4: 7549 // [For a] user-provided explicitly-defaulted function [...] if such a 7550 // function is implicitly defined as deleted, the program is ill-formed. 7551 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 7552 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl"); 7553 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 7554 HadError = true; 7555 } 7556 } 7557 7558 return HadError; 7559 } 7560 7561 namespace { 7562 /// Helper class for building and checking a defaulted comparison. 7563 /// 7564 /// Defaulted functions are built in two phases: 7565 /// 7566 /// * First, the set of operations that the function will perform are 7567 /// identified, and some of them are checked. If any of the checked 7568 /// operations is invalid in certain ways, the comparison function is 7569 /// defined as deleted and no body is built. 7570 /// * Then, if the function is not defined as deleted, the body is built. 7571 /// 7572 /// This is accomplished by performing two visitation steps over the eventual 7573 /// body of the function. 7574 template<typename Derived, typename ResultList, typename Result, 7575 typename Subobject> 7576 class DefaultedComparisonVisitor { 7577 public: 7578 using DefaultedComparisonKind = Sema::DefaultedComparisonKind; 7579 7580 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7581 DefaultedComparisonKind DCK) 7582 : S(S), RD(RD), FD(FD), DCK(DCK) { 7583 if (auto *Info = FD->getDefaultedFunctionInfo()) { 7584 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an 7585 // UnresolvedSet to avoid this copy. 7586 Fns.assign(Info->getUnqualifiedLookups().begin(), 7587 Info->getUnqualifiedLookups().end()); 7588 } 7589 } 7590 7591 ResultList visit() { 7592 // The type of an lvalue naming a parameter of this function. 7593 QualType ParamLvalType = 7594 FD->getParamDecl(0)->getType().getNonReferenceType(); 7595 7596 ResultList Results; 7597 7598 switch (DCK) { 7599 case DefaultedComparisonKind::None: 7600 llvm_unreachable("not a defaulted comparison"); 7601 7602 case DefaultedComparisonKind::Equal: 7603 case DefaultedComparisonKind::ThreeWay: 7604 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers()); 7605 return Results; 7606 7607 case DefaultedComparisonKind::NotEqual: 7608 case DefaultedComparisonKind::Relational: 7609 Results.add(getDerived().visitExpandedSubobject( 7610 ParamLvalType, getDerived().getCompleteObject())); 7611 return Results; 7612 } 7613 llvm_unreachable(""); 7614 } 7615 7616 protected: 7617 Derived &getDerived() { return static_cast<Derived&>(*this); } 7618 7619 /// Visit the expanded list of subobjects of the given type, as specified in 7620 /// C++2a [class.compare.default]. 7621 /// 7622 /// \return \c true if the ResultList object said we're done, \c false if not. 7623 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record, 7624 Qualifiers Quals) { 7625 // C++2a [class.compare.default]p4: 7626 // The direct base class subobjects of C 7627 for (CXXBaseSpecifier &Base : Record->bases()) 7628 if (Results.add(getDerived().visitSubobject( 7629 S.Context.getQualifiedType(Base.getType(), Quals), 7630 getDerived().getBase(&Base)))) 7631 return true; 7632 7633 // followed by the non-static data members of C 7634 for (FieldDecl *Field : Record->fields()) { 7635 // Recursively expand anonymous structs. 7636 if (Field->isAnonymousStructOrUnion()) { 7637 if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(), 7638 Quals)) 7639 return true; 7640 continue; 7641 } 7642 7643 // Figure out the type of an lvalue denoting this field. 7644 Qualifiers FieldQuals = Quals; 7645 if (Field->isMutable()) 7646 FieldQuals.removeConst(); 7647 QualType FieldType = 7648 S.Context.getQualifiedType(Field->getType(), FieldQuals); 7649 7650 if (Results.add(getDerived().visitSubobject( 7651 FieldType, getDerived().getField(Field)))) 7652 return true; 7653 } 7654 7655 // form a list of subobjects. 7656 return false; 7657 } 7658 7659 Result visitSubobject(QualType Type, Subobject Subobj) { 7660 // In that list, any subobject of array type is recursively expanded 7661 const ArrayType *AT = S.Context.getAsArrayType(Type); 7662 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT)) 7663 return getDerived().visitSubobjectArray(CAT->getElementType(), 7664 CAT->getSize(), Subobj); 7665 return getDerived().visitExpandedSubobject(Type, Subobj); 7666 } 7667 7668 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size, 7669 Subobject Subobj) { 7670 return getDerived().visitSubobject(Type, Subobj); 7671 } 7672 7673 protected: 7674 Sema &S; 7675 CXXRecordDecl *RD; 7676 FunctionDecl *FD; 7677 DefaultedComparisonKind DCK; 7678 UnresolvedSet<16> Fns; 7679 }; 7680 7681 /// Information about a defaulted comparison, as determined by 7682 /// DefaultedComparisonAnalyzer. 7683 struct DefaultedComparisonInfo { 7684 bool Deleted = false; 7685 bool Constexpr = true; 7686 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering; 7687 7688 static DefaultedComparisonInfo deleted() { 7689 DefaultedComparisonInfo Deleted; 7690 Deleted.Deleted = true; 7691 return Deleted; 7692 } 7693 7694 bool add(const DefaultedComparisonInfo &R) { 7695 Deleted |= R.Deleted; 7696 Constexpr &= R.Constexpr; 7697 Category = commonComparisonType(Category, R.Category); 7698 return Deleted; 7699 } 7700 }; 7701 7702 /// An element in the expanded list of subobjects of a defaulted comparison, as 7703 /// specified in C++2a [class.compare.default]p4. 7704 struct DefaultedComparisonSubobject { 7705 enum { CompleteObject, Member, Base } Kind; 7706 NamedDecl *Decl; 7707 SourceLocation Loc; 7708 }; 7709 7710 /// A visitor over the notional body of a defaulted comparison that determines 7711 /// whether that body would be deleted or constexpr. 7712 class DefaultedComparisonAnalyzer 7713 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer, 7714 DefaultedComparisonInfo, 7715 DefaultedComparisonInfo, 7716 DefaultedComparisonSubobject> { 7717 public: 7718 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr }; 7719 7720 private: 7721 DiagnosticKind Diagnose; 7722 7723 public: 7724 using Base = DefaultedComparisonVisitor; 7725 using Result = DefaultedComparisonInfo; 7726 using Subobject = DefaultedComparisonSubobject; 7727 7728 friend Base; 7729 7730 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7731 DefaultedComparisonKind DCK, 7732 DiagnosticKind Diagnose = NoDiagnostics) 7733 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {} 7734 7735 Result visit() { 7736 if ((DCK == DefaultedComparisonKind::Equal || 7737 DCK == DefaultedComparisonKind::ThreeWay) && 7738 RD->hasVariantMembers()) { 7739 // C++2a [class.compare.default]p2 [P2002R0]: 7740 // A defaulted comparison operator function for class C is defined as 7741 // deleted if [...] C has variant members. 7742 if (Diagnose == ExplainDeleted) { 7743 S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union) 7744 << FD << RD->isUnion() << RD; 7745 } 7746 return Result::deleted(); 7747 } 7748 7749 return Base::visit(); 7750 } 7751 7752 private: 7753 Subobject getCompleteObject() { 7754 return Subobject{Subobject::CompleteObject, RD, FD->getLocation()}; 7755 } 7756 7757 Subobject getBase(CXXBaseSpecifier *Base) { 7758 return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(), 7759 Base->getBaseTypeLoc()}; 7760 } 7761 7762 Subobject getField(FieldDecl *Field) { 7763 return Subobject{Subobject::Member, Field, Field->getLocation()}; 7764 } 7765 7766 Result visitExpandedSubobject(QualType Type, Subobject Subobj) { 7767 // C++2a [class.compare.default]p2 [P2002R0]: 7768 // A defaulted <=> or == operator function for class C is defined as 7769 // deleted if any non-static data member of C is of reference type 7770 if (Type->isReferenceType()) { 7771 if (Diagnose == ExplainDeleted) { 7772 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member) 7773 << FD << RD; 7774 } 7775 return Result::deleted(); 7776 } 7777 7778 // [...] Let xi be an lvalue denoting the ith element [...] 7779 OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue); 7780 Expr *Args[] = {&Xi, &Xi}; 7781 7782 // All operators start by trying to apply that same operator recursively. 7783 OverloadedOperatorKind OO = FD->getOverloadedOperator(); 7784 assert(OO != OO_None && "not an overloaded operator!"); 7785 return visitBinaryOperator(OO, Args, Subobj); 7786 } 7787 7788 Result 7789 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args, 7790 Subobject Subobj, 7791 OverloadCandidateSet *SpaceshipCandidates = nullptr) { 7792 // Note that there is no need to consider rewritten candidates here if 7793 // we've already found there is no viable 'operator<=>' candidate (and are 7794 // considering synthesizing a '<=>' from '==' and '<'). 7795 OverloadCandidateSet CandidateSet( 7796 FD->getLocation(), OverloadCandidateSet::CSK_Operator, 7797 OverloadCandidateSet::OperatorRewriteInfo( 7798 OO, /*AllowRewrittenCandidates=*/!SpaceshipCandidates)); 7799 7800 /// C++2a [class.compare.default]p1 [P2002R0]: 7801 /// [...] the defaulted function itself is never a candidate for overload 7802 /// resolution [...] 7803 CandidateSet.exclude(FD); 7804 7805 if (Args[0]->getType()->isOverloadableType()) 7806 S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args); 7807 else 7808 // FIXME: We determine whether this is a valid expression by checking to 7809 // see if there's a viable builtin operator candidate for it. That isn't 7810 // really what the rules ask us to do, but should give the right results. 7811 S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet); 7812 7813 Result R; 7814 7815 OverloadCandidateSet::iterator Best; 7816 switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) { 7817 case OR_Success: { 7818 // C++2a [class.compare.secondary]p2 [P2002R0]: 7819 // The operator function [...] is defined as deleted if [...] the 7820 // candidate selected by overload resolution is not a rewritten 7821 // candidate. 7822 if ((DCK == DefaultedComparisonKind::NotEqual || 7823 DCK == DefaultedComparisonKind::Relational) && 7824 !Best->RewriteKind) { 7825 if (Diagnose == ExplainDeleted) { 7826 if (Best->Function) { 7827 S.Diag(Best->Function->getLocation(), 7828 diag::note_defaulted_comparison_not_rewritten_callee) 7829 << FD; 7830 } else { 7831 assert(Best->Conversions.size() == 2 && 7832 Best->Conversions[0].isUserDefined() && 7833 "non-user-defined conversion from class to built-in " 7834 "comparison"); 7835 S.Diag(Best->Conversions[0] 7836 .UserDefined.FoundConversionFunction.getDecl() 7837 ->getLocation(), 7838 diag::note_defaulted_comparison_not_rewritten_conversion) 7839 << FD; 7840 } 7841 } 7842 return Result::deleted(); 7843 } 7844 7845 // Throughout C++2a [class.compare]: if overload resolution does not 7846 // result in a usable function, the candidate function is defined as 7847 // deleted. This requires that we selected an accessible function. 7848 // 7849 // Note that this only considers the access of the function when named 7850 // within the type of the subobject, and not the access path for any 7851 // derived-to-base conversion. 7852 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl(); 7853 if (ArgClass && Best->FoundDecl.getDecl() && 7854 Best->FoundDecl.getDecl()->isCXXClassMember()) { 7855 QualType ObjectType = Subobj.Kind == Subobject::Member 7856 ? Args[0]->getType() 7857 : S.Context.getRecordType(RD); 7858 if (!S.isMemberAccessibleForDeletion( 7859 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc, 7860 Diagnose == ExplainDeleted 7861 ? S.PDiag(diag::note_defaulted_comparison_inaccessible) 7862 << FD << Subobj.Kind << Subobj.Decl 7863 : S.PDiag())) 7864 return Result::deleted(); 7865 } 7866 7867 bool NeedsDeducing = 7868 OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType(); 7869 7870 if (FunctionDecl *BestFD = Best->Function) { 7871 // C++2a [class.compare.default]p3 [P2002R0]: 7872 // A defaulted comparison function is constexpr-compatible if 7873 // [...] no overlod resolution performed [...] results in a 7874 // non-constexpr function. 7875 assert(!BestFD->isDeleted() && "wrong overload resolution result"); 7876 // If it's not constexpr, explain why not. 7877 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) { 7878 if (Subobj.Kind != Subobject::CompleteObject) 7879 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr) 7880 << Subobj.Kind << Subobj.Decl; 7881 S.Diag(BestFD->getLocation(), 7882 diag::note_defaulted_comparison_not_constexpr_here); 7883 // Bail out after explaining; we don't want any more notes. 7884 return Result::deleted(); 7885 } 7886 R.Constexpr &= BestFD->isConstexpr(); 7887 7888 if (NeedsDeducing) { 7889 // If any callee has an undeduced return type, deduce it now. 7890 // FIXME: It's not clear how a failure here should be handled. For 7891 // now, we produce an eager diagnostic, because that is forward 7892 // compatible with most (all?) other reasonable options. 7893 if (BestFD->getReturnType()->isUndeducedType() && 7894 S.DeduceReturnType(BestFD, FD->getLocation(), 7895 /*Diagnose=*/false)) { 7896 // Don't produce a duplicate error when asked to explain why the 7897 // comparison is deleted: we diagnosed that when initially checking 7898 // the defaulted operator. 7899 if (Diagnose == NoDiagnostics) { 7900 S.Diag( 7901 FD->getLocation(), 7902 diag::err_defaulted_comparison_cannot_deduce_undeduced_auto) 7903 << Subobj.Kind << Subobj.Decl; 7904 S.Diag( 7905 Subobj.Loc, 7906 diag::note_defaulted_comparison_cannot_deduce_undeduced_auto) 7907 << Subobj.Kind << Subobj.Decl; 7908 S.Diag(BestFD->getLocation(), 7909 diag::note_defaulted_comparison_cannot_deduce_callee) 7910 << Subobj.Kind << Subobj.Decl; 7911 } 7912 return Result::deleted(); 7913 } 7914 auto *Info = S.Context.CompCategories.lookupInfoForType( 7915 BestFD->getCallResultType()); 7916 if (!Info) { 7917 if (Diagnose == ExplainDeleted) { 7918 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce) 7919 << Subobj.Kind << Subobj.Decl 7920 << BestFD->getCallResultType().withoutLocalFastQualifiers(); 7921 S.Diag(BestFD->getLocation(), 7922 diag::note_defaulted_comparison_cannot_deduce_callee) 7923 << Subobj.Kind << Subobj.Decl; 7924 } 7925 return Result::deleted(); 7926 } 7927 R.Category = Info->Kind; 7928 } 7929 } else { 7930 QualType T = Best->BuiltinParamTypes[0]; 7931 assert(T == Best->BuiltinParamTypes[1] && 7932 "builtin comparison for different types?"); 7933 assert(Best->BuiltinParamTypes[2].isNull() && 7934 "invalid builtin comparison"); 7935 7936 if (NeedsDeducing) { 7937 Optional<ComparisonCategoryType> Cat = 7938 getComparisonCategoryForBuiltinCmp(T); 7939 assert(Cat && "no category for builtin comparison?"); 7940 R.Category = *Cat; 7941 } 7942 } 7943 7944 // Note that we might be rewriting to a different operator. That call is 7945 // not considered until we come to actually build the comparison function. 7946 break; 7947 } 7948 7949 case OR_Ambiguous: 7950 if (Diagnose == ExplainDeleted) { 7951 unsigned Kind = 0; 7952 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship) 7953 Kind = OO == OO_EqualEqual ? 1 : 2; 7954 CandidateSet.NoteCandidates( 7955 PartialDiagnosticAt( 7956 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous) 7957 << FD << Kind << Subobj.Kind << Subobj.Decl), 7958 S, OCD_AmbiguousCandidates, Args); 7959 } 7960 R = Result::deleted(); 7961 break; 7962 7963 case OR_Deleted: 7964 if (Diagnose == ExplainDeleted) { 7965 if ((DCK == DefaultedComparisonKind::NotEqual || 7966 DCK == DefaultedComparisonKind::Relational) && 7967 !Best->RewriteKind) { 7968 S.Diag(Best->Function->getLocation(), 7969 diag::note_defaulted_comparison_not_rewritten_callee) 7970 << FD; 7971 } else { 7972 S.Diag(Subobj.Loc, 7973 diag::note_defaulted_comparison_calls_deleted) 7974 << FD << Subobj.Kind << Subobj.Decl; 7975 S.NoteDeletedFunction(Best->Function); 7976 } 7977 } 7978 R = Result::deleted(); 7979 break; 7980 7981 case OR_No_Viable_Function: 7982 // If there's no usable candidate, we're done unless we can rewrite a 7983 // '<=>' in terms of '==' and '<'. 7984 if (OO == OO_Spaceship && 7985 S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) { 7986 // For any kind of comparison category return type, we need a usable 7987 // '==' and a usable '<'. 7988 if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj, 7989 &CandidateSet))) 7990 R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet)); 7991 break; 7992 } 7993 7994 if (Diagnose == ExplainDeleted) { 7995 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function) 7996 << FD << (OO == OO_ExclaimEqual) << Subobj.Kind << Subobj.Decl; 7997 7998 // For a three-way comparison, list both the candidates for the 7999 // original operator and the candidates for the synthesized operator. 8000 if (SpaceshipCandidates) { 8001 SpaceshipCandidates->NoteCandidates( 8002 S, Args, 8003 SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates, 8004 Args, FD->getLocation())); 8005 S.Diag(Subobj.Loc, 8006 diag::note_defaulted_comparison_no_viable_function_synthesized) 8007 << (OO == OO_EqualEqual ? 0 : 1); 8008 } 8009 8010 CandidateSet.NoteCandidates( 8011 S, Args, 8012 CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args, 8013 FD->getLocation())); 8014 } 8015 R = Result::deleted(); 8016 break; 8017 } 8018 8019 return R; 8020 } 8021 }; 8022 8023 /// A list of statements. 8024 struct StmtListResult { 8025 bool IsInvalid = false; 8026 llvm::SmallVector<Stmt*, 16> Stmts; 8027 8028 bool add(const StmtResult &S) { 8029 IsInvalid |= S.isInvalid(); 8030 if (IsInvalid) 8031 return true; 8032 Stmts.push_back(S.get()); 8033 return false; 8034 } 8035 }; 8036 8037 /// A visitor over the notional body of a defaulted comparison that synthesizes 8038 /// the actual body. 8039 class DefaultedComparisonSynthesizer 8040 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer, 8041 StmtListResult, StmtResult, 8042 std::pair<ExprResult, ExprResult>> { 8043 SourceLocation Loc; 8044 unsigned ArrayDepth = 0; 8045 8046 public: 8047 using Base = DefaultedComparisonVisitor; 8048 using ExprPair = std::pair<ExprResult, ExprResult>; 8049 8050 friend Base; 8051 8052 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 8053 DefaultedComparisonKind DCK, 8054 SourceLocation BodyLoc) 8055 : Base(S, RD, FD, DCK), Loc(BodyLoc) {} 8056 8057 /// Build a suitable function body for this defaulted comparison operator. 8058 StmtResult build() { 8059 Sema::CompoundScopeRAII CompoundScope(S); 8060 8061 StmtListResult Stmts = visit(); 8062 if (Stmts.IsInvalid) 8063 return StmtError(); 8064 8065 ExprResult RetVal; 8066 switch (DCK) { 8067 case DefaultedComparisonKind::None: 8068 llvm_unreachable("not a defaulted comparison"); 8069 8070 case DefaultedComparisonKind::Equal: { 8071 // C++2a [class.eq]p3: 8072 // [...] compar[e] the corresponding elements [...] until the first 8073 // index i where xi == yi yields [...] false. If no such index exists, 8074 // V is true. Otherwise, V is false. 8075 // 8076 // Join the comparisons with '&&'s and return the result. Use a right 8077 // fold (traversing the conditions right-to-left), because that 8078 // short-circuits more naturally. 8079 auto OldStmts = std::move(Stmts.Stmts); 8080 Stmts.Stmts.clear(); 8081 ExprResult CmpSoFar; 8082 // Finish a particular comparison chain. 8083 auto FinishCmp = [&] { 8084 if (Expr *Prior = CmpSoFar.get()) { 8085 // Convert the last expression to 'return ...;' 8086 if (RetVal.isUnset() && Stmts.Stmts.empty()) 8087 RetVal = CmpSoFar; 8088 // Convert any prior comparison to 'if (!(...)) return false;' 8089 else if (Stmts.add(buildIfNotCondReturnFalse(Prior))) 8090 return true; 8091 CmpSoFar = ExprResult(); 8092 } 8093 return false; 8094 }; 8095 for (Stmt *EAsStmt : llvm::reverse(OldStmts)) { 8096 Expr *E = dyn_cast<Expr>(EAsStmt); 8097 if (!E) { 8098 // Found an array comparison. 8099 if (FinishCmp() || Stmts.add(EAsStmt)) 8100 return StmtError(); 8101 continue; 8102 } 8103 8104 if (CmpSoFar.isUnset()) { 8105 CmpSoFar = E; 8106 continue; 8107 } 8108 CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get()); 8109 if (CmpSoFar.isInvalid()) 8110 return StmtError(); 8111 } 8112 if (FinishCmp()) 8113 return StmtError(); 8114 std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end()); 8115 // If no such index exists, V is true. 8116 if (RetVal.isUnset()) 8117 RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true); 8118 break; 8119 } 8120 8121 case DefaultedComparisonKind::ThreeWay: { 8122 // Per C++2a [class.spaceship]p3, as a fallback add: 8123 // return static_cast<R>(std::strong_ordering::equal); 8124 QualType StrongOrdering = S.CheckComparisonCategoryType( 8125 ComparisonCategoryType::StrongOrdering, Loc, 8126 Sema::ComparisonCategoryUsage::DefaultedOperator); 8127 if (StrongOrdering.isNull()) 8128 return StmtError(); 8129 VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering) 8130 .getValueInfo(ComparisonCategoryResult::Equal) 8131 ->VD; 8132 RetVal = getDecl(EqualVD); 8133 if (RetVal.isInvalid()) 8134 return StmtError(); 8135 RetVal = buildStaticCastToR(RetVal.get()); 8136 break; 8137 } 8138 8139 case DefaultedComparisonKind::NotEqual: 8140 case DefaultedComparisonKind::Relational: 8141 RetVal = cast<Expr>(Stmts.Stmts.pop_back_val()); 8142 break; 8143 } 8144 8145 // Build the final return statement. 8146 if (RetVal.isInvalid()) 8147 return StmtError(); 8148 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get()); 8149 if (ReturnStmt.isInvalid()) 8150 return StmtError(); 8151 Stmts.Stmts.push_back(ReturnStmt.get()); 8152 8153 return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false); 8154 } 8155 8156 private: 8157 ExprResult getDecl(ValueDecl *VD) { 8158 return S.BuildDeclarationNameExpr( 8159 CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD); 8160 } 8161 8162 ExprResult getParam(unsigned I) { 8163 ParmVarDecl *PD = FD->getParamDecl(I); 8164 return getDecl(PD); 8165 } 8166 8167 ExprPair getCompleteObject() { 8168 unsigned Param = 0; 8169 ExprResult LHS; 8170 if (isa<CXXMethodDecl>(FD)) { 8171 // LHS is '*this'. 8172 LHS = S.ActOnCXXThis(Loc); 8173 if (!LHS.isInvalid()) 8174 LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get()); 8175 } else { 8176 LHS = getParam(Param++); 8177 } 8178 ExprResult RHS = getParam(Param++); 8179 assert(Param == FD->getNumParams()); 8180 return {LHS, RHS}; 8181 } 8182 8183 ExprPair getBase(CXXBaseSpecifier *Base) { 8184 ExprPair Obj = getCompleteObject(); 8185 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 8186 return {ExprError(), ExprError()}; 8187 CXXCastPath Path = {Base}; 8188 return {S.ImpCastExprToType(Obj.first.get(), Base->getType(), 8189 CK_DerivedToBase, VK_LValue, &Path), 8190 S.ImpCastExprToType(Obj.second.get(), Base->getType(), 8191 CK_DerivedToBase, VK_LValue, &Path)}; 8192 } 8193 8194 ExprPair getField(FieldDecl *Field) { 8195 ExprPair Obj = getCompleteObject(); 8196 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 8197 return {ExprError(), ExprError()}; 8198 8199 DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess()); 8200 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc); 8201 return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc, 8202 CXXScopeSpec(), Field, Found, NameInfo), 8203 S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc, 8204 CXXScopeSpec(), Field, Found, NameInfo)}; 8205 } 8206 8207 // FIXME: When expanding a subobject, register a note in the code synthesis 8208 // stack to say which subobject we're comparing. 8209 8210 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) { 8211 if (Cond.isInvalid()) 8212 return StmtError(); 8213 8214 ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get()); 8215 if (NotCond.isInvalid()) 8216 return StmtError(); 8217 8218 ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false); 8219 assert(!False.isInvalid() && "should never fail"); 8220 StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get()); 8221 if (ReturnFalse.isInvalid()) 8222 return StmtError(); 8223 8224 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, nullptr, 8225 S.ActOnCondition(nullptr, Loc, NotCond.get(), 8226 Sema::ConditionKind::Boolean), 8227 Loc, ReturnFalse.get(), SourceLocation(), nullptr); 8228 } 8229 8230 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size, 8231 ExprPair Subobj) { 8232 QualType SizeType = S.Context.getSizeType(); 8233 Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType)); 8234 8235 // Build 'size_t i$n = 0'. 8236 IdentifierInfo *IterationVarName = nullptr; 8237 { 8238 SmallString<8> Str; 8239 llvm::raw_svector_ostream OS(Str); 8240 OS << "i" << ArrayDepth; 8241 IterationVarName = &S.Context.Idents.get(OS.str()); 8242 } 8243 VarDecl *IterationVar = VarDecl::Create( 8244 S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType, 8245 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None); 8246 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 8247 IterationVar->setInit( 8248 IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 8249 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc); 8250 8251 auto IterRef = [&] { 8252 ExprResult Ref = S.BuildDeclarationNameExpr( 8253 CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc), 8254 IterationVar); 8255 assert(!Ref.isInvalid() && "can't reference our own variable?"); 8256 return Ref.get(); 8257 }; 8258 8259 // Build 'i$n != Size'. 8260 ExprResult Cond = S.CreateBuiltinBinOp( 8261 Loc, BO_NE, IterRef(), 8262 IntegerLiteral::Create(S.Context, Size, SizeType, Loc)); 8263 assert(!Cond.isInvalid() && "should never fail"); 8264 8265 // Build '++i$n'. 8266 ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef()); 8267 assert(!Inc.isInvalid() && "should never fail"); 8268 8269 // Build 'a[i$n]' and 'b[i$n]'. 8270 auto Index = [&](ExprResult E) { 8271 if (E.isInvalid()) 8272 return ExprError(); 8273 return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc); 8274 }; 8275 Subobj.first = Index(Subobj.first); 8276 Subobj.second = Index(Subobj.second); 8277 8278 // Compare the array elements. 8279 ++ArrayDepth; 8280 StmtResult Substmt = visitSubobject(Type, Subobj); 8281 --ArrayDepth; 8282 8283 if (Substmt.isInvalid()) 8284 return StmtError(); 8285 8286 // For the inner level of an 'operator==', build 'if (!cmp) return false;'. 8287 // For outer levels or for an 'operator<=>' we already have a suitable 8288 // statement that returns as necessary. 8289 if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) { 8290 assert(DCK == DefaultedComparisonKind::Equal && 8291 "should have non-expression statement"); 8292 Substmt = buildIfNotCondReturnFalse(ElemCmp); 8293 if (Substmt.isInvalid()) 8294 return StmtError(); 8295 } 8296 8297 // Build 'for (...) ...' 8298 return S.ActOnForStmt(Loc, Loc, Init, 8299 S.ActOnCondition(nullptr, Loc, Cond.get(), 8300 Sema::ConditionKind::Boolean), 8301 S.MakeFullDiscardedValueExpr(Inc.get()), Loc, 8302 Substmt.get()); 8303 } 8304 8305 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) { 8306 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 8307 return StmtError(); 8308 8309 OverloadedOperatorKind OO = FD->getOverloadedOperator(); 8310 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO); 8311 ExprResult Op; 8312 if (Type->isOverloadableType()) 8313 Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(), 8314 Obj.second.get(), /*PerformADL=*/true, 8315 /*AllowRewrittenCandidates=*/true, FD); 8316 else 8317 Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get()); 8318 if (Op.isInvalid()) 8319 return StmtError(); 8320 8321 switch (DCK) { 8322 case DefaultedComparisonKind::None: 8323 llvm_unreachable("not a defaulted comparison"); 8324 8325 case DefaultedComparisonKind::Equal: 8326 // Per C++2a [class.eq]p2, each comparison is individually contextually 8327 // converted to bool. 8328 Op = S.PerformContextuallyConvertToBool(Op.get()); 8329 if (Op.isInvalid()) 8330 return StmtError(); 8331 return Op.get(); 8332 8333 case DefaultedComparisonKind::ThreeWay: { 8334 // Per C++2a [class.spaceship]p3, form: 8335 // if (R cmp = static_cast<R>(op); cmp != 0) 8336 // return cmp; 8337 QualType R = FD->getReturnType(); 8338 Op = buildStaticCastToR(Op.get()); 8339 if (Op.isInvalid()) 8340 return StmtError(); 8341 8342 // R cmp = ...; 8343 IdentifierInfo *Name = &S.Context.Idents.get("cmp"); 8344 VarDecl *VD = 8345 VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R, 8346 S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None); 8347 S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false); 8348 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc); 8349 8350 // cmp != 0 8351 ExprResult VDRef = getDecl(VD); 8352 if (VDRef.isInvalid()) 8353 return StmtError(); 8354 llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0); 8355 Expr *Zero = 8356 IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc); 8357 ExprResult Comp; 8358 if (VDRef.get()->getType()->isOverloadableType()) 8359 Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true, 8360 true, FD); 8361 else 8362 Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero); 8363 if (Comp.isInvalid()) 8364 return StmtError(); 8365 Sema::ConditionResult Cond = S.ActOnCondition( 8366 nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean); 8367 if (Cond.isInvalid()) 8368 return StmtError(); 8369 8370 // return cmp; 8371 VDRef = getDecl(VD); 8372 if (VDRef.isInvalid()) 8373 return StmtError(); 8374 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get()); 8375 if (ReturnStmt.isInvalid()) 8376 return StmtError(); 8377 8378 // if (...) 8379 return S.ActOnIfStmt(Loc, IfStatementKind::Ordinary, Loc, InitStmt, Cond, 8380 Loc, ReturnStmt.get(), 8381 /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr); 8382 } 8383 8384 case DefaultedComparisonKind::NotEqual: 8385 case DefaultedComparisonKind::Relational: 8386 // C++2a [class.compare.secondary]p2: 8387 // Otherwise, the operator function yields x @ y. 8388 return Op.get(); 8389 } 8390 llvm_unreachable(""); 8391 } 8392 8393 /// Build "static_cast<R>(E)". 8394 ExprResult buildStaticCastToR(Expr *E) { 8395 QualType R = FD->getReturnType(); 8396 assert(!R->isUndeducedType() && "type should have been deduced already"); 8397 8398 // Don't bother forming a no-op cast in the common case. 8399 if (E->isPRValue() && S.Context.hasSameType(E->getType(), R)) 8400 return E; 8401 return S.BuildCXXNamedCast(Loc, tok::kw_static_cast, 8402 S.Context.getTrivialTypeSourceInfo(R, Loc), E, 8403 SourceRange(Loc, Loc), SourceRange(Loc, Loc)); 8404 } 8405 }; 8406 } 8407 8408 /// Perform the unqualified lookups that might be needed to form a defaulted 8409 /// comparison function for the given operator. 8410 static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S, 8411 UnresolvedSetImpl &Operators, 8412 OverloadedOperatorKind Op) { 8413 auto Lookup = [&](OverloadedOperatorKind OO) { 8414 Self.LookupOverloadedOperatorName(OO, S, Operators); 8415 }; 8416 8417 // Every defaulted operator looks up itself. 8418 Lookup(Op); 8419 // ... and the rewritten form of itself, if any. 8420 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op)) 8421 Lookup(ExtraOp); 8422 8423 // For 'operator<=>', we also form a 'cmp != 0' expression, and might 8424 // synthesize a three-way comparison from '<' and '=='. In a dependent 8425 // context, we also need to look up '==' in case we implicitly declare a 8426 // defaulted 'operator=='. 8427 if (Op == OO_Spaceship) { 8428 Lookup(OO_ExclaimEqual); 8429 Lookup(OO_Less); 8430 Lookup(OO_EqualEqual); 8431 } 8432 } 8433 8434 bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD, 8435 DefaultedComparisonKind DCK) { 8436 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison"); 8437 8438 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()); 8439 assert(RD && "defaulted comparison is not defaulted in a class"); 8440 8441 // Perform any unqualified lookups we're going to need to default this 8442 // function. 8443 if (S) { 8444 UnresolvedSet<32> Operators; 8445 lookupOperatorsForDefaultedComparison(*this, S, Operators, 8446 FD->getOverloadedOperator()); 8447 FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create( 8448 Context, Operators.pairs())); 8449 } 8450 8451 // C++2a [class.compare.default]p1: 8452 // A defaulted comparison operator function for some class C shall be a 8453 // non-template function declared in the member-specification of C that is 8454 // -- a non-static const member of C having one parameter of type 8455 // const C&, or 8456 // -- a friend of C having two parameters of type const C& or two 8457 // parameters of type C. 8458 QualType ExpectedParmType1 = Context.getRecordType(RD); 8459 QualType ExpectedParmType2 = 8460 Context.getLValueReferenceType(ExpectedParmType1.withConst()); 8461 if (isa<CXXMethodDecl>(FD)) 8462 ExpectedParmType1 = ExpectedParmType2; 8463 for (const ParmVarDecl *Param : FD->parameters()) { 8464 if (!Param->getType()->isDependentType() && 8465 !Context.hasSameType(Param->getType(), ExpectedParmType1) && 8466 !Context.hasSameType(Param->getType(), ExpectedParmType2)) { 8467 // Don't diagnose an implicit 'operator=='; we will have diagnosed the 8468 // corresponding defaulted 'operator<=>' already. 8469 if (!FD->isImplicit()) { 8470 Diag(FD->getLocation(), diag::err_defaulted_comparison_param) 8471 << (int)DCK << Param->getType() << ExpectedParmType1 8472 << !isa<CXXMethodDecl>(FD) 8473 << ExpectedParmType2 << Param->getSourceRange(); 8474 } 8475 return true; 8476 } 8477 } 8478 if (FD->getNumParams() == 2 && 8479 !Context.hasSameType(FD->getParamDecl(0)->getType(), 8480 FD->getParamDecl(1)->getType())) { 8481 if (!FD->isImplicit()) { 8482 Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch) 8483 << (int)DCK 8484 << FD->getParamDecl(0)->getType() 8485 << FD->getParamDecl(0)->getSourceRange() 8486 << FD->getParamDecl(1)->getType() 8487 << FD->getParamDecl(1)->getSourceRange(); 8488 } 8489 return true; 8490 } 8491 8492 // ... non-static const member ... 8493 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 8494 assert(!MD->isStatic() && "comparison function cannot be a static member"); 8495 if (!MD->isConst()) { 8496 SourceLocation InsertLoc; 8497 if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc()) 8498 InsertLoc = getLocForEndOfToken(Loc.getRParenLoc()); 8499 // Don't diagnose an implicit 'operator=='; we will have diagnosed the 8500 // corresponding defaulted 'operator<=>' already. 8501 if (!MD->isImplicit()) { 8502 Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const) 8503 << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const"); 8504 } 8505 8506 // Add the 'const' to the type to recover. 8507 const auto *FPT = MD->getType()->castAs<FunctionProtoType>(); 8508 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8509 EPI.TypeQuals.addConst(); 8510 MD->setType(Context.getFunctionType(FPT->getReturnType(), 8511 FPT->getParamTypes(), EPI)); 8512 } 8513 } else { 8514 // A non-member function declared in a class must be a friend. 8515 assert(FD->getFriendObjectKind() && "expected a friend declaration"); 8516 } 8517 8518 // C++2a [class.eq]p1, [class.rel]p1: 8519 // A [defaulted comparison other than <=>] shall have a declared return 8520 // type bool. 8521 if (DCK != DefaultedComparisonKind::ThreeWay && 8522 !FD->getDeclaredReturnType()->isDependentType() && 8523 !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) { 8524 Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool) 8525 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy 8526 << FD->getReturnTypeSourceRange(); 8527 return true; 8528 } 8529 // C++2a [class.spaceship]p2 [P2002R0]: 8530 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise, 8531 // R shall not contain a placeholder type. 8532 if (DCK == DefaultedComparisonKind::ThreeWay && 8533 FD->getDeclaredReturnType()->getContainedDeducedType() && 8534 !Context.hasSameType(FD->getDeclaredReturnType(), 8535 Context.getAutoDeductType())) { 8536 Diag(FD->getLocation(), 8537 diag::err_defaulted_comparison_deduced_return_type_not_auto) 8538 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy 8539 << FD->getReturnTypeSourceRange(); 8540 return true; 8541 } 8542 8543 // For a defaulted function in a dependent class, defer all remaining checks 8544 // until instantiation. 8545 if (RD->isDependentType()) 8546 return false; 8547 8548 // Determine whether the function should be defined as deleted. 8549 DefaultedComparisonInfo Info = 8550 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit(); 8551 8552 bool First = FD == FD->getCanonicalDecl(); 8553 8554 // If we want to delete the function, then do so; there's nothing else to 8555 // check in that case. 8556 if (Info.Deleted) { 8557 if (!First) { 8558 // C++11 [dcl.fct.def.default]p4: 8559 // [For a] user-provided explicitly-defaulted function [...] if such a 8560 // function is implicitly defined as deleted, the program is ill-formed. 8561 // 8562 // This is really just a consequence of the general rule that you can 8563 // only delete a function on its first declaration. 8564 Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes) 8565 << FD->isImplicit() << (int)DCK; 8566 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8567 DefaultedComparisonAnalyzer::ExplainDeleted) 8568 .visit(); 8569 return true; 8570 } 8571 8572 SetDeclDeleted(FD, FD->getLocation()); 8573 if (!inTemplateInstantiation() && !FD->isImplicit()) { 8574 Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted) 8575 << (int)DCK; 8576 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8577 DefaultedComparisonAnalyzer::ExplainDeleted) 8578 .visit(); 8579 } 8580 return false; 8581 } 8582 8583 // C++2a [class.spaceship]p2: 8584 // The return type is deduced as the common comparison type of R0, R1, ... 8585 if (DCK == DefaultedComparisonKind::ThreeWay && 8586 FD->getDeclaredReturnType()->isUndeducedAutoType()) { 8587 SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin(); 8588 if (RetLoc.isInvalid()) 8589 RetLoc = FD->getBeginLoc(); 8590 // FIXME: Should we really care whether we have the complete type and the 8591 // 'enumerator' constants here? A forward declaration seems sufficient. 8592 QualType Cat = CheckComparisonCategoryType( 8593 Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator); 8594 if (Cat.isNull()) 8595 return true; 8596 Context.adjustDeducedFunctionResultType( 8597 FD, SubstAutoType(FD->getDeclaredReturnType(), Cat)); 8598 } 8599 8600 // C++2a [dcl.fct.def.default]p3 [P2002R0]: 8601 // An explicitly-defaulted function that is not defined as deleted may be 8602 // declared constexpr or consteval only if it is constexpr-compatible. 8603 // C++2a [class.compare.default]p3 [P2002R0]: 8604 // A defaulted comparison function is constexpr-compatible if it satisfies 8605 // the requirements for a constexpr function [...] 8606 // The only relevant requirements are that the parameter and return types are 8607 // literal types. The remaining conditions are checked by the analyzer. 8608 if (FD->isConstexpr()) { 8609 if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) && 8610 CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) && 8611 !Info.Constexpr) { 8612 Diag(FD->getBeginLoc(), 8613 diag::err_incorrect_defaulted_comparison_constexpr) 8614 << FD->isImplicit() << (int)DCK << FD->isConsteval(); 8615 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8616 DefaultedComparisonAnalyzer::ExplainConstexpr) 8617 .visit(); 8618 } 8619 } 8620 8621 // C++2a [dcl.fct.def.default]p3 [P2002R0]: 8622 // If a constexpr-compatible function is explicitly defaulted on its first 8623 // declaration, it is implicitly considered to be constexpr. 8624 // FIXME: Only applying this to the first declaration seems problematic, as 8625 // simple reorderings can affect the meaning of the program. 8626 if (First && !FD->isConstexpr() && Info.Constexpr) 8627 FD->setConstexprKind(ConstexprSpecKind::Constexpr); 8628 8629 // C++2a [except.spec]p3: 8630 // If a declaration of a function does not have a noexcept-specifier 8631 // [and] is defaulted on its first declaration, [...] the exception 8632 // specification is as specified below 8633 if (FD->getExceptionSpecType() == EST_None) { 8634 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 8635 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8636 EPI.ExceptionSpec.Type = EST_Unevaluated; 8637 EPI.ExceptionSpec.SourceDecl = FD; 8638 FD->setType(Context.getFunctionType(FPT->getReturnType(), 8639 FPT->getParamTypes(), EPI)); 8640 } 8641 8642 return false; 8643 } 8644 8645 void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD, 8646 FunctionDecl *Spaceship) { 8647 Sema::CodeSynthesisContext Ctx; 8648 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison; 8649 Ctx.PointOfInstantiation = Spaceship->getEndLoc(); 8650 Ctx.Entity = Spaceship; 8651 pushCodeSynthesisContext(Ctx); 8652 8653 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship)) 8654 EqualEqual->setImplicit(); 8655 8656 popCodeSynthesisContext(); 8657 } 8658 8659 void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD, 8660 DefaultedComparisonKind DCK) { 8661 assert(FD->isDefaulted() && !FD->isDeleted() && 8662 !FD->doesThisDeclarationHaveABody()); 8663 if (FD->willHaveBody() || FD->isInvalidDecl()) 8664 return; 8665 8666 SynthesizedFunctionScope Scope(*this, FD); 8667 8668 // Add a context note for diagnostics produced after this point. 8669 Scope.addContextNote(UseLoc); 8670 8671 { 8672 // Build and set up the function body. 8673 CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent()); 8674 SourceLocation BodyLoc = 8675 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation(); 8676 StmtResult Body = 8677 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build(); 8678 if (Body.isInvalid()) { 8679 FD->setInvalidDecl(); 8680 return; 8681 } 8682 FD->setBody(Body.get()); 8683 FD->markUsed(Context); 8684 } 8685 8686 // The exception specification is needed because we are defining the 8687 // function. Note that this will reuse the body we just built. 8688 ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>()); 8689 8690 if (ASTMutationListener *L = getASTMutationListener()) 8691 L->CompletedImplicitDefinition(FD); 8692 } 8693 8694 static Sema::ImplicitExceptionSpecification 8695 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, 8696 FunctionDecl *FD, 8697 Sema::DefaultedComparisonKind DCK) { 8698 ComputingExceptionSpec CES(S, FD, Loc); 8699 Sema::ImplicitExceptionSpecification ExceptSpec(S); 8700 8701 if (FD->isInvalidDecl()) 8702 return ExceptSpec; 8703 8704 // The common case is that we just defined the comparison function. In that 8705 // case, just look at whether the body can throw. 8706 if (FD->hasBody()) { 8707 ExceptSpec.CalledStmt(FD->getBody()); 8708 } else { 8709 // Otherwise, build a body so we can check it. This should ideally only 8710 // happen when we're not actually marking the function referenced. (This is 8711 // only really important for efficiency: we don't want to build and throw 8712 // away bodies for comparison functions more than we strictly need to.) 8713 8714 // Pretend to synthesize the function body in an unevaluated context. 8715 // Note that we can't actually just go ahead and define the function here: 8716 // we are not permitted to mark its callees as referenced. 8717 Sema::SynthesizedFunctionScope Scope(S, FD); 8718 EnterExpressionEvaluationContext Context( 8719 S, Sema::ExpressionEvaluationContext::Unevaluated); 8720 8721 CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent()); 8722 SourceLocation BodyLoc = 8723 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation(); 8724 StmtResult Body = 8725 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build(); 8726 if (!Body.isInvalid()) 8727 ExceptSpec.CalledStmt(Body.get()); 8728 8729 // FIXME: Can we hold onto this body and just transform it to potentially 8730 // evaluated when we're asked to define the function rather than rebuilding 8731 // it? Either that, or we should only build the bits of the body that we 8732 // need (the expressions, not the statements). 8733 } 8734 8735 return ExceptSpec; 8736 } 8737 8738 void Sema::CheckDelayedMemberExceptionSpecs() { 8739 decltype(DelayedOverridingExceptionSpecChecks) Overriding; 8740 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent; 8741 8742 std::swap(Overriding, DelayedOverridingExceptionSpecChecks); 8743 std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks); 8744 8745 // Perform any deferred checking of exception specifications for virtual 8746 // destructors. 8747 for (auto &Check : Overriding) 8748 CheckOverridingFunctionExceptionSpec(Check.first, Check.second); 8749 8750 // Perform any deferred checking of exception specifications for befriended 8751 // special members. 8752 for (auto &Check : Equivalent) 8753 CheckEquivalentExceptionSpec(Check.second, Check.first); 8754 } 8755 8756 namespace { 8757 /// CRTP base class for visiting operations performed by a special member 8758 /// function (or inherited constructor). 8759 template<typename Derived> 8760 struct SpecialMemberVisitor { 8761 Sema &S; 8762 CXXMethodDecl *MD; 8763 Sema::CXXSpecialMember CSM; 8764 Sema::InheritedConstructorInfo *ICI; 8765 8766 // Properties of the special member, computed for convenience. 8767 bool IsConstructor = false, IsAssignment = false, ConstArg = false; 8768 8769 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 8770 Sema::InheritedConstructorInfo *ICI) 8771 : S(S), MD(MD), CSM(CSM), ICI(ICI) { 8772 switch (CSM) { 8773 case Sema::CXXDefaultConstructor: 8774 case Sema::CXXCopyConstructor: 8775 case Sema::CXXMoveConstructor: 8776 IsConstructor = true; 8777 break; 8778 case Sema::CXXCopyAssignment: 8779 case Sema::CXXMoveAssignment: 8780 IsAssignment = true; 8781 break; 8782 case Sema::CXXDestructor: 8783 break; 8784 case Sema::CXXInvalid: 8785 llvm_unreachable("invalid special member kind"); 8786 } 8787 8788 if (MD->getNumParams()) { 8789 if (const ReferenceType *RT = 8790 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 8791 ConstArg = RT->getPointeeType().isConstQualified(); 8792 } 8793 } 8794 8795 Derived &getDerived() { return static_cast<Derived&>(*this); } 8796 8797 /// Is this a "move" special member? 8798 bool isMove() const { 8799 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment; 8800 } 8801 8802 /// Look up the corresponding special member in the given class. 8803 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class, 8804 unsigned Quals, bool IsMutable) { 8805 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 8806 ConstArg && !IsMutable); 8807 } 8808 8809 /// Look up the constructor for the specified base class to see if it's 8810 /// overridden due to this being an inherited constructor. 8811 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) { 8812 if (!ICI) 8813 return {}; 8814 assert(CSM == Sema::CXXDefaultConstructor); 8815 auto *BaseCtor = 8816 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor(); 8817 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first) 8818 return MD; 8819 return {}; 8820 } 8821 8822 /// A base or member subobject. 8823 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 8824 8825 /// Get the location to use for a subobject in diagnostics. 8826 static SourceLocation getSubobjectLoc(Subobject Subobj) { 8827 // FIXME: For an indirect virtual base, the direct base leading to 8828 // the indirect virtual base would be a more useful choice. 8829 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>()) 8830 return B->getBaseTypeLoc(); 8831 else 8832 return Subobj.get<FieldDecl*>()->getLocation(); 8833 } 8834 8835 enum BasesToVisit { 8836 /// Visit all non-virtual (direct) bases. 8837 VisitNonVirtualBases, 8838 /// Visit all direct bases, virtual or not. 8839 VisitDirectBases, 8840 /// Visit all non-virtual bases, and all virtual bases if the class 8841 /// is not abstract. 8842 VisitPotentiallyConstructedBases, 8843 /// Visit all direct or virtual bases. 8844 VisitAllBases 8845 }; 8846 8847 // Visit the bases and members of the class. 8848 bool visit(BasesToVisit Bases) { 8849 CXXRecordDecl *RD = MD->getParent(); 8850 8851 if (Bases == VisitPotentiallyConstructedBases) 8852 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases; 8853 8854 for (auto &B : RD->bases()) 8855 if ((Bases == VisitDirectBases || !B.isVirtual()) && 8856 getDerived().visitBase(&B)) 8857 return true; 8858 8859 if (Bases == VisitAllBases) 8860 for (auto &B : RD->vbases()) 8861 if (getDerived().visitBase(&B)) 8862 return true; 8863 8864 for (auto *F : RD->fields()) 8865 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() && 8866 getDerived().visitField(F)) 8867 return true; 8868 8869 return false; 8870 } 8871 }; 8872 } 8873 8874 namespace { 8875 struct SpecialMemberDeletionInfo 8876 : SpecialMemberVisitor<SpecialMemberDeletionInfo> { 8877 bool Diagnose; 8878 8879 SourceLocation Loc; 8880 8881 bool AllFieldsAreConst; 8882 8883 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 8884 Sema::CXXSpecialMember CSM, 8885 Sema::InheritedConstructorInfo *ICI, bool Diagnose) 8886 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose), 8887 Loc(MD->getLocation()), AllFieldsAreConst(true) {} 8888 8889 bool inUnion() const { return MD->getParent()->isUnion(); } 8890 8891 Sema::CXXSpecialMember getEffectiveCSM() { 8892 return ICI ? Sema::CXXInvalid : CSM; 8893 } 8894 8895 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType); 8896 8897 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); } 8898 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); } 8899 8900 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 8901 bool shouldDeleteForField(FieldDecl *FD); 8902 bool shouldDeleteForAllConstMembers(); 8903 8904 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 8905 unsigned Quals); 8906 bool shouldDeleteForSubobjectCall(Subobject Subobj, 8907 Sema::SpecialMemberOverloadResult SMOR, 8908 bool IsDtorCallInCtor); 8909 8910 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 8911 }; 8912 } 8913 8914 /// Is the given special member inaccessible when used on the given 8915 /// sub-object. 8916 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 8917 CXXMethodDecl *target) { 8918 /// If we're operating on a base class, the object type is the 8919 /// type of this special member. 8920 QualType objectTy; 8921 AccessSpecifier access = target->getAccess(); 8922 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 8923 objectTy = S.Context.getTypeDeclType(MD->getParent()); 8924 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 8925 8926 // If we're operating on a field, the object type is the type of the field. 8927 } else { 8928 objectTy = S.Context.getTypeDeclType(target->getParent()); 8929 } 8930 8931 return S.isMemberAccessibleForDeletion( 8932 target->getParent(), DeclAccessPair::make(target, access), objectTy); 8933 } 8934 8935 /// Check whether we should delete a special member due to the implicit 8936 /// definition containing a call to a special member of a subobject. 8937 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 8938 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR, 8939 bool IsDtorCallInCtor) { 8940 CXXMethodDecl *Decl = SMOR.getMethod(); 8941 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 8942 8943 int DiagKind = -1; 8944 8945 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 8946 DiagKind = !Decl ? 0 : 1; 8947 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 8948 DiagKind = 2; 8949 else if (!isAccessible(Subobj, Decl)) 8950 DiagKind = 3; 8951 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 8952 !Decl->isTrivial()) { 8953 // A member of a union must have a trivial corresponding special member. 8954 // As a weird special case, a destructor call from a union's constructor 8955 // must be accessible and non-deleted, but need not be trivial. Such a 8956 // destructor is never actually called, but is semantically checked as 8957 // if it were. 8958 DiagKind = 4; 8959 } 8960 8961 if (DiagKind == -1) 8962 return false; 8963 8964 if (Diagnose) { 8965 if (Field) { 8966 S.Diag(Field->getLocation(), 8967 diag::note_deleted_special_member_class_subobject) 8968 << getEffectiveCSM() << MD->getParent() << /*IsField*/true 8969 << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false; 8970 } else { 8971 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 8972 S.Diag(Base->getBeginLoc(), 8973 diag::note_deleted_special_member_class_subobject) 8974 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 8975 << Base->getType() << DiagKind << IsDtorCallInCtor 8976 << /*IsObjCPtr*/false; 8977 } 8978 8979 if (DiagKind == 1) 8980 S.NoteDeletedFunction(Decl); 8981 // FIXME: Explain inaccessibility if DiagKind == 3. 8982 } 8983 8984 return true; 8985 } 8986 8987 /// Check whether we should delete a special member function due to having a 8988 /// direct or virtual base class or non-static data member of class type M. 8989 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 8990 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 8991 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 8992 bool IsMutable = Field && Field->isMutable(); 8993 8994 // C++11 [class.ctor]p5: 8995 // -- any direct or virtual base class, or non-static data member with no 8996 // brace-or-equal-initializer, has class type M (or array thereof) and 8997 // either M has no default constructor or overload resolution as applied 8998 // to M's default constructor results in an ambiguity or in a function 8999 // that is deleted or inaccessible 9000 // C++11 [class.copy]p11, C++11 [class.copy]p23: 9001 // -- a direct or virtual base class B that cannot be copied/moved because 9002 // overload resolution, as applied to B's corresponding special member, 9003 // results in an ambiguity or a function that is deleted or inaccessible 9004 // from the defaulted special member 9005 // C++11 [class.dtor]p5: 9006 // -- any direct or virtual base class [...] has a type with a destructor 9007 // that is deleted or inaccessible 9008 if (!(CSM == Sema::CXXDefaultConstructor && 9009 Field && Field->hasInClassInitializer()) && 9010 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 9011 false)) 9012 return true; 9013 9014 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 9015 // -- any direct or virtual base class or non-static data member has a 9016 // type with a destructor that is deleted or inaccessible 9017 if (IsConstructor) { 9018 Sema::SpecialMemberOverloadResult SMOR = 9019 S.LookupSpecialMember(Class, Sema::CXXDestructor, 9020 false, false, false, false, false); 9021 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 9022 return true; 9023 } 9024 9025 return false; 9026 } 9027 9028 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember( 9029 FieldDecl *FD, QualType FieldType) { 9030 // The defaulted special functions are defined as deleted if this is a variant 9031 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak 9032 // type under ARC. 9033 if (!FieldType.hasNonTrivialObjCLifetime()) 9034 return false; 9035 9036 // Don't make the defaulted default constructor defined as deleted if the 9037 // member has an in-class initializer. 9038 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) 9039 return false; 9040 9041 if (Diagnose) { 9042 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent()); 9043 S.Diag(FD->getLocation(), 9044 diag::note_deleted_special_member_class_subobject) 9045 << getEffectiveCSM() << ParentClass << /*IsField*/true 9046 << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true; 9047 } 9048 9049 return true; 9050 } 9051 9052 /// Check whether we should delete a special member function due to the class 9053 /// having a particular direct or virtual base class. 9054 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 9055 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 9056 // If program is correct, BaseClass cannot be null, but if it is, the error 9057 // must be reported elsewhere. 9058 if (!BaseClass) 9059 return false; 9060 // If we have an inheriting constructor, check whether we're calling an 9061 // inherited constructor instead of a default constructor. 9062 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 9063 if (auto *BaseCtor = SMOR.getMethod()) { 9064 // Note that we do not check access along this path; other than that, 9065 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false); 9066 // FIXME: Check that the base has a usable destructor! Sink this into 9067 // shouldDeleteForClassSubobject. 9068 if (BaseCtor->isDeleted() && Diagnose) { 9069 S.Diag(Base->getBeginLoc(), 9070 diag::note_deleted_special_member_class_subobject) 9071 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 9072 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false 9073 << /*IsObjCPtr*/false; 9074 S.NoteDeletedFunction(BaseCtor); 9075 } 9076 return BaseCtor->isDeleted(); 9077 } 9078 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 9079 } 9080 9081 /// Check whether we should delete a special member function due to the class 9082 /// having a particular non-static data member. 9083 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 9084 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 9085 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 9086 9087 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType)) 9088 return true; 9089 9090 if (CSM == Sema::CXXDefaultConstructor) { 9091 // For a default constructor, all references must be initialized in-class 9092 // and, if a union, it must have a non-const member. 9093 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 9094 if (Diagnose) 9095 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 9096 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0; 9097 return true; 9098 } 9099 // C++11 [class.ctor]p5: any non-variant non-static data member of 9100 // const-qualified type (or array thereof) with no 9101 // brace-or-equal-initializer does not have a user-provided default 9102 // constructor. 9103 if (!inUnion() && FieldType.isConstQualified() && 9104 !FD->hasInClassInitializer() && 9105 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 9106 if (Diagnose) 9107 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 9108 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1; 9109 return true; 9110 } 9111 9112 if (inUnion() && !FieldType.isConstQualified()) 9113 AllFieldsAreConst = false; 9114 } else if (CSM == Sema::CXXCopyConstructor) { 9115 // For a copy constructor, data members must not be of rvalue reference 9116 // type. 9117 if (FieldType->isRValueReferenceType()) { 9118 if (Diagnose) 9119 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 9120 << MD->getParent() << FD << FieldType; 9121 return true; 9122 } 9123 } else if (IsAssignment) { 9124 // For an assignment operator, data members must not be of reference type. 9125 if (FieldType->isReferenceType()) { 9126 if (Diagnose) 9127 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 9128 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0; 9129 return true; 9130 } 9131 if (!FieldRecord && FieldType.isConstQualified()) { 9132 // C++11 [class.copy]p23: 9133 // -- a non-static data member of const non-class type (or array thereof) 9134 if (Diagnose) 9135 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 9136 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1; 9137 return true; 9138 } 9139 } 9140 9141 if (FieldRecord) { 9142 // Some additional restrictions exist on the variant members. 9143 if (!inUnion() && FieldRecord->isUnion() && 9144 FieldRecord->isAnonymousStructOrUnion()) { 9145 bool AllVariantFieldsAreConst = true; 9146 9147 // FIXME: Handle anonymous unions declared within anonymous unions. 9148 for (auto *UI : FieldRecord->fields()) { 9149 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 9150 9151 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType)) 9152 return true; 9153 9154 if (!UnionFieldType.isConstQualified()) 9155 AllVariantFieldsAreConst = false; 9156 9157 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 9158 if (UnionFieldRecord && 9159 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 9160 UnionFieldType.getCVRQualifiers())) 9161 return true; 9162 } 9163 9164 // At least one member in each anonymous union must be non-const 9165 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 9166 !FieldRecord->field_empty()) { 9167 if (Diagnose) 9168 S.Diag(FieldRecord->getLocation(), 9169 diag::note_deleted_default_ctor_all_const) 9170 << !!ICI << MD->getParent() << /*anonymous union*/1; 9171 return true; 9172 } 9173 9174 // Don't check the implicit member of the anonymous union type. 9175 // This is technically non-conformant but supported, and we have a 9176 // diagnostic for this elsewhere. 9177 return false; 9178 } 9179 9180 if (shouldDeleteForClassSubobject(FieldRecord, FD, 9181 FieldType.getCVRQualifiers())) 9182 return true; 9183 } 9184 9185 return false; 9186 } 9187 9188 /// C++11 [class.ctor] p5: 9189 /// A defaulted default constructor for a class X is defined as deleted if 9190 /// X is a union and all of its variant members are of const-qualified type. 9191 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 9192 // This is a silly definition, because it gives an empty union a deleted 9193 // default constructor. Don't do that. 9194 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) { 9195 bool AnyFields = false; 9196 for (auto *F : MD->getParent()->fields()) 9197 if ((AnyFields = !F->isUnnamedBitfield())) 9198 break; 9199 if (!AnyFields) 9200 return false; 9201 if (Diagnose) 9202 S.Diag(MD->getParent()->getLocation(), 9203 diag::note_deleted_default_ctor_all_const) 9204 << !!ICI << MD->getParent() << /*not anonymous union*/0; 9205 return true; 9206 } 9207 return false; 9208 } 9209 9210 /// Determine whether a defaulted special member function should be defined as 9211 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 9212 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 9213 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 9214 InheritedConstructorInfo *ICI, 9215 bool Diagnose) { 9216 if (MD->isInvalidDecl()) 9217 return false; 9218 CXXRecordDecl *RD = MD->getParent(); 9219 assert(!RD->isDependentType() && "do deletion after instantiation"); 9220 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 9221 return false; 9222 9223 // C++11 [expr.lambda.prim]p19: 9224 // The closure type associated with a lambda-expression has a 9225 // deleted (8.4.3) default constructor and a deleted copy 9226 // assignment operator. 9227 // C++2a adds back these operators if the lambda has no lambda-capture. 9228 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() && 9229 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 9230 if (Diagnose) 9231 Diag(RD->getLocation(), diag::note_lambda_decl); 9232 return true; 9233 } 9234 9235 // For an anonymous struct or union, the copy and assignment special members 9236 // will never be used, so skip the check. For an anonymous union declared at 9237 // namespace scope, the constructor and destructor are used. 9238 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 9239 RD->isAnonymousStructOrUnion()) 9240 return false; 9241 9242 // C++11 [class.copy]p7, p18: 9243 // If the class definition declares a move constructor or move assignment 9244 // operator, an implicitly declared copy constructor or copy assignment 9245 // operator is defined as deleted. 9246 if (MD->isImplicit() && 9247 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 9248 CXXMethodDecl *UserDeclaredMove = nullptr; 9249 9250 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the 9251 // deletion of the corresponding copy operation, not both copy operations. 9252 // MSVC 2015 has adopted the standards conforming behavior. 9253 bool DeletesOnlyMatchingCopy = 9254 getLangOpts().MSVCCompat && 9255 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015); 9256 9257 if (RD->hasUserDeclaredMoveConstructor() && 9258 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) { 9259 if (!Diagnose) return true; 9260 9261 // Find any user-declared move constructor. 9262 for (auto *I : RD->ctors()) { 9263 if (I->isMoveConstructor()) { 9264 UserDeclaredMove = I; 9265 break; 9266 } 9267 } 9268 assert(UserDeclaredMove); 9269 } else if (RD->hasUserDeclaredMoveAssignment() && 9270 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) { 9271 if (!Diagnose) return true; 9272 9273 // Find any user-declared move assignment operator. 9274 for (auto *I : RD->methods()) { 9275 if (I->isMoveAssignmentOperator()) { 9276 UserDeclaredMove = I; 9277 break; 9278 } 9279 } 9280 assert(UserDeclaredMove); 9281 } 9282 9283 if (UserDeclaredMove) { 9284 Diag(UserDeclaredMove->getLocation(), 9285 diag::note_deleted_copy_user_declared_move) 9286 << (CSM == CXXCopyAssignment) << RD 9287 << UserDeclaredMove->isMoveAssignmentOperator(); 9288 return true; 9289 } 9290 } 9291 9292 // Do access control from the special member function 9293 ContextRAII MethodContext(*this, MD); 9294 9295 // C++11 [class.dtor]p5: 9296 // -- for a virtual destructor, lookup of the non-array deallocation function 9297 // results in an ambiguity or in a function that is deleted or inaccessible 9298 if (CSM == CXXDestructor && MD->isVirtual()) { 9299 FunctionDecl *OperatorDelete = nullptr; 9300 DeclarationName Name = 9301 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 9302 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 9303 OperatorDelete, /*Diagnose*/false)) { 9304 if (Diagnose) 9305 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 9306 return true; 9307 } 9308 } 9309 9310 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose); 9311 9312 // Per DR1611, do not consider virtual bases of constructors of abstract 9313 // classes, since we are not going to construct them. 9314 // Per DR1658, do not consider virtual bases of destructors of abstract 9315 // classes either. 9316 // Per DR2180, for assignment operators we only assign (and thus only 9317 // consider) direct bases. 9318 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases 9319 : SMI.VisitPotentiallyConstructedBases)) 9320 return true; 9321 9322 if (SMI.shouldDeleteForAllConstMembers()) 9323 return true; 9324 9325 if (getLangOpts().CUDA) { 9326 // We should delete the special member in CUDA mode if target inference 9327 // failed. 9328 // For inherited constructors (non-null ICI), CSM may be passed so that MD 9329 // is treated as certain special member, which may not reflect what special 9330 // member MD really is. However inferCUDATargetForImplicitSpecialMember 9331 // expects CSM to match MD, therefore recalculate CSM. 9332 assert(ICI || CSM == getSpecialMember(MD)); 9333 auto RealCSM = CSM; 9334 if (ICI) 9335 RealCSM = getSpecialMember(MD); 9336 9337 return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD, 9338 SMI.ConstArg, Diagnose); 9339 } 9340 9341 return false; 9342 } 9343 9344 void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) { 9345 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD); 9346 assert(DFK && "not a defaultable function"); 9347 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted"); 9348 9349 if (DFK.isSpecialMember()) { 9350 ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), 9351 nullptr, /*Diagnose=*/true); 9352 } else { 9353 DefaultedComparisonAnalyzer( 9354 *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD, 9355 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted) 9356 .visit(); 9357 } 9358 } 9359 9360 /// Perform lookup for a special member of the specified kind, and determine 9361 /// whether it is trivial. If the triviality can be determined without the 9362 /// lookup, skip it. This is intended for use when determining whether a 9363 /// special member of a containing object is trivial, and thus does not ever 9364 /// perform overload resolution for default constructors. 9365 /// 9366 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 9367 /// member that was most likely to be intended to be trivial, if any. 9368 /// 9369 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to 9370 /// determine whether the special member is trivial. 9371 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 9372 Sema::CXXSpecialMember CSM, unsigned Quals, 9373 bool ConstRHS, 9374 Sema::TrivialABIHandling TAH, 9375 CXXMethodDecl **Selected) { 9376 if (Selected) 9377 *Selected = nullptr; 9378 9379 switch (CSM) { 9380 case Sema::CXXInvalid: 9381 llvm_unreachable("not a special member"); 9382 9383 case Sema::CXXDefaultConstructor: 9384 // C++11 [class.ctor]p5: 9385 // A default constructor is trivial if: 9386 // - all the [direct subobjects] have trivial default constructors 9387 // 9388 // Note, no overload resolution is performed in this case. 9389 if (RD->hasTrivialDefaultConstructor()) 9390 return true; 9391 9392 if (Selected) { 9393 // If there's a default constructor which could have been trivial, dig it 9394 // out. Otherwise, if there's any user-provided default constructor, point 9395 // to that as an example of why there's not a trivial one. 9396 CXXConstructorDecl *DefCtor = nullptr; 9397 if (RD->needsImplicitDefaultConstructor()) 9398 S.DeclareImplicitDefaultConstructor(RD); 9399 for (auto *CI : RD->ctors()) { 9400 if (!CI->isDefaultConstructor()) 9401 continue; 9402 DefCtor = CI; 9403 if (!DefCtor->isUserProvided()) 9404 break; 9405 } 9406 9407 *Selected = DefCtor; 9408 } 9409 9410 return false; 9411 9412 case Sema::CXXDestructor: 9413 // C++11 [class.dtor]p5: 9414 // A destructor is trivial if: 9415 // - all the direct [subobjects] have trivial destructors 9416 if (RD->hasTrivialDestructor() || 9417 (TAH == Sema::TAH_ConsiderTrivialABI && 9418 RD->hasTrivialDestructorForCall())) 9419 return true; 9420 9421 if (Selected) { 9422 if (RD->needsImplicitDestructor()) 9423 S.DeclareImplicitDestructor(RD); 9424 *Selected = RD->getDestructor(); 9425 } 9426 9427 return false; 9428 9429 case Sema::CXXCopyConstructor: 9430 // C++11 [class.copy]p12: 9431 // A copy constructor is trivial if: 9432 // - the constructor selected to copy each direct [subobject] is trivial 9433 if (RD->hasTrivialCopyConstructor() || 9434 (TAH == Sema::TAH_ConsiderTrivialABI && 9435 RD->hasTrivialCopyConstructorForCall())) { 9436 if (Quals == Qualifiers::Const) 9437 // We must either select the trivial copy constructor or reach an 9438 // ambiguity; no need to actually perform overload resolution. 9439 return true; 9440 } else if (!Selected) { 9441 return false; 9442 } 9443 // In C++98, we are not supposed to perform overload resolution here, but we 9444 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 9445 // cases like B as having a non-trivial copy constructor: 9446 // struct A { template<typename T> A(T&); }; 9447 // struct B { mutable A a; }; 9448 goto NeedOverloadResolution; 9449 9450 case Sema::CXXCopyAssignment: 9451 // C++11 [class.copy]p25: 9452 // A copy assignment operator is trivial if: 9453 // - the assignment operator selected to copy each direct [subobject] is 9454 // trivial 9455 if (RD->hasTrivialCopyAssignment()) { 9456 if (Quals == Qualifiers::Const) 9457 return true; 9458 } else if (!Selected) { 9459 return false; 9460 } 9461 // In C++98, we are not supposed to perform overload resolution here, but we 9462 // treat that as a language defect. 9463 goto NeedOverloadResolution; 9464 9465 case Sema::CXXMoveConstructor: 9466 case Sema::CXXMoveAssignment: 9467 NeedOverloadResolution: 9468 Sema::SpecialMemberOverloadResult SMOR = 9469 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 9470 9471 // The standard doesn't describe how to behave if the lookup is ambiguous. 9472 // We treat it as not making the member non-trivial, just like the standard 9473 // mandates for the default constructor. This should rarely matter, because 9474 // the member will also be deleted. 9475 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 9476 return true; 9477 9478 if (!SMOR.getMethod()) { 9479 assert(SMOR.getKind() == 9480 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 9481 return false; 9482 } 9483 9484 // We deliberately don't check if we found a deleted special member. We're 9485 // not supposed to! 9486 if (Selected) 9487 *Selected = SMOR.getMethod(); 9488 9489 if (TAH == Sema::TAH_ConsiderTrivialABI && 9490 (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor)) 9491 return SMOR.getMethod()->isTrivialForCall(); 9492 return SMOR.getMethod()->isTrivial(); 9493 } 9494 9495 llvm_unreachable("unknown special method kind"); 9496 } 9497 9498 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 9499 for (auto *CI : RD->ctors()) 9500 if (!CI->isImplicit()) 9501 return CI; 9502 9503 // Look for constructor templates. 9504 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 9505 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 9506 if (CXXConstructorDecl *CD = 9507 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 9508 return CD; 9509 } 9510 9511 return nullptr; 9512 } 9513 9514 /// The kind of subobject we are checking for triviality. The values of this 9515 /// enumeration are used in diagnostics. 9516 enum TrivialSubobjectKind { 9517 /// The subobject is a base class. 9518 TSK_BaseClass, 9519 /// The subobject is a non-static data member. 9520 TSK_Field, 9521 /// The object is actually the complete object. 9522 TSK_CompleteObject 9523 }; 9524 9525 /// Check whether the special member selected for a given type would be trivial. 9526 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 9527 QualType SubType, bool ConstRHS, 9528 Sema::CXXSpecialMember CSM, 9529 TrivialSubobjectKind Kind, 9530 Sema::TrivialABIHandling TAH, bool Diagnose) { 9531 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 9532 if (!SubRD) 9533 return true; 9534 9535 CXXMethodDecl *Selected; 9536 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 9537 ConstRHS, TAH, Diagnose ? &Selected : nullptr)) 9538 return true; 9539 9540 if (Diagnose) { 9541 if (ConstRHS) 9542 SubType.addConst(); 9543 9544 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 9545 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 9546 << Kind << SubType.getUnqualifiedType(); 9547 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 9548 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 9549 } else if (!Selected) 9550 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 9551 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 9552 else if (Selected->isUserProvided()) { 9553 if (Kind == TSK_CompleteObject) 9554 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 9555 << Kind << SubType.getUnqualifiedType() << CSM; 9556 else { 9557 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 9558 << Kind << SubType.getUnqualifiedType() << CSM; 9559 S.Diag(Selected->getLocation(), diag::note_declared_at); 9560 } 9561 } else { 9562 if (Kind != TSK_CompleteObject) 9563 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 9564 << Kind << SubType.getUnqualifiedType() << CSM; 9565 9566 // Explain why the defaulted or deleted special member isn't trivial. 9567 S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI, 9568 Diagnose); 9569 } 9570 } 9571 9572 return false; 9573 } 9574 9575 /// Check whether the members of a class type allow a special member to be 9576 /// trivial. 9577 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 9578 Sema::CXXSpecialMember CSM, 9579 bool ConstArg, 9580 Sema::TrivialABIHandling TAH, 9581 bool Diagnose) { 9582 for (const auto *FI : RD->fields()) { 9583 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 9584 continue; 9585 9586 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 9587 9588 // Pretend anonymous struct or union members are members of this class. 9589 if (FI->isAnonymousStructOrUnion()) { 9590 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 9591 CSM, ConstArg, TAH, Diagnose)) 9592 return false; 9593 continue; 9594 } 9595 9596 // C++11 [class.ctor]p5: 9597 // A default constructor is trivial if [...] 9598 // -- no non-static data member of its class has a 9599 // brace-or-equal-initializer 9600 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 9601 if (Diagnose) 9602 S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init) 9603 << FI; 9604 return false; 9605 } 9606 9607 // Objective C ARC 4.3.5: 9608 // [...] nontrivally ownership-qualified types are [...] not trivially 9609 // default constructible, copy constructible, move constructible, copy 9610 // assignable, move assignable, or destructible [...] 9611 if (FieldType.hasNonTrivialObjCLifetime()) { 9612 if (Diagnose) 9613 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 9614 << RD << FieldType.getObjCLifetime(); 9615 return false; 9616 } 9617 9618 bool ConstRHS = ConstArg && !FI->isMutable(); 9619 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 9620 CSM, TSK_Field, TAH, Diagnose)) 9621 return false; 9622 } 9623 9624 return true; 9625 } 9626 9627 /// Diagnose why the specified class does not have a trivial special member of 9628 /// the given kind. 9629 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 9630 QualType Ty = Context.getRecordType(RD); 9631 9632 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 9633 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 9634 TSK_CompleteObject, TAH_IgnoreTrivialABI, 9635 /*Diagnose*/true); 9636 } 9637 9638 /// Determine whether a defaulted or deleted special member function is trivial, 9639 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 9640 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 9641 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 9642 TrivialABIHandling TAH, bool Diagnose) { 9643 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 9644 9645 CXXRecordDecl *RD = MD->getParent(); 9646 9647 bool ConstArg = false; 9648 9649 // C++11 [class.copy]p12, p25: [DR1593] 9650 // A [special member] is trivial if [...] its parameter-type-list is 9651 // equivalent to the parameter-type-list of an implicit declaration [...] 9652 switch (CSM) { 9653 case CXXDefaultConstructor: 9654 case CXXDestructor: 9655 // Trivial default constructors and destructors cannot have parameters. 9656 break; 9657 9658 case CXXCopyConstructor: 9659 case CXXCopyAssignment: { 9660 // Trivial copy operations always have const, non-volatile parameter types. 9661 ConstArg = true; 9662 const ParmVarDecl *Param0 = MD->getParamDecl(0); 9663 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 9664 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 9665 if (Diagnose) 9666 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 9667 << Param0->getSourceRange() << Param0->getType() 9668 << Context.getLValueReferenceType( 9669 Context.getRecordType(RD).withConst()); 9670 return false; 9671 } 9672 break; 9673 } 9674 9675 case CXXMoveConstructor: 9676 case CXXMoveAssignment: { 9677 // Trivial move operations always have non-cv-qualified parameters. 9678 const ParmVarDecl *Param0 = MD->getParamDecl(0); 9679 const RValueReferenceType *RT = 9680 Param0->getType()->getAs<RValueReferenceType>(); 9681 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 9682 if (Diagnose) 9683 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 9684 << Param0->getSourceRange() << Param0->getType() 9685 << Context.getRValueReferenceType(Context.getRecordType(RD)); 9686 return false; 9687 } 9688 break; 9689 } 9690 9691 case CXXInvalid: 9692 llvm_unreachable("not a special member"); 9693 } 9694 9695 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 9696 if (Diagnose) 9697 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 9698 diag::note_nontrivial_default_arg) 9699 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 9700 return false; 9701 } 9702 if (MD->isVariadic()) { 9703 if (Diagnose) 9704 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 9705 return false; 9706 } 9707 9708 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 9709 // A copy/move [constructor or assignment operator] is trivial if 9710 // -- the [member] selected to copy/move each direct base class subobject 9711 // is trivial 9712 // 9713 // C++11 [class.copy]p12, C++11 [class.copy]p25: 9714 // A [default constructor or destructor] is trivial if 9715 // -- all the direct base classes have trivial [default constructors or 9716 // destructors] 9717 for (const auto &BI : RD->bases()) 9718 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(), 9719 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose)) 9720 return false; 9721 9722 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 9723 // A copy/move [constructor or assignment operator] for a class X is 9724 // trivial if 9725 // -- for each non-static data member of X that is of class type (or array 9726 // thereof), the constructor selected to copy/move that member is 9727 // trivial 9728 // 9729 // C++11 [class.copy]p12, C++11 [class.copy]p25: 9730 // A [default constructor or destructor] is trivial if 9731 // -- for all of the non-static data members of its class that are of class 9732 // type (or array thereof), each such class has a trivial [default 9733 // constructor or destructor] 9734 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose)) 9735 return false; 9736 9737 // C++11 [class.dtor]p5: 9738 // A destructor is trivial if [...] 9739 // -- the destructor is not virtual 9740 if (CSM == CXXDestructor && MD->isVirtual()) { 9741 if (Diagnose) 9742 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 9743 return false; 9744 } 9745 9746 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 9747 // A [special member] for class X is trivial if [...] 9748 // -- class X has no virtual functions and no virtual base classes 9749 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 9750 if (!Diagnose) 9751 return false; 9752 9753 if (RD->getNumVBases()) { 9754 // Check for virtual bases. We already know that the corresponding 9755 // member in all bases is trivial, so vbases must all be direct. 9756 CXXBaseSpecifier &BS = *RD->vbases_begin(); 9757 assert(BS.isVirtual()); 9758 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1; 9759 return false; 9760 } 9761 9762 // Must have a virtual method. 9763 for (const auto *MI : RD->methods()) { 9764 if (MI->isVirtual()) { 9765 SourceLocation MLoc = MI->getBeginLoc(); 9766 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 9767 return false; 9768 } 9769 } 9770 9771 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 9772 } 9773 9774 // Looks like it's trivial! 9775 return true; 9776 } 9777 9778 namespace { 9779 struct FindHiddenVirtualMethod { 9780 Sema *S; 9781 CXXMethodDecl *Method; 9782 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 9783 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 9784 9785 private: 9786 /// Check whether any most overridden method from MD in Methods 9787 static bool CheckMostOverridenMethods( 9788 const CXXMethodDecl *MD, 9789 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) { 9790 if (MD->size_overridden_methods() == 0) 9791 return Methods.count(MD->getCanonicalDecl()); 9792 for (const CXXMethodDecl *O : MD->overridden_methods()) 9793 if (CheckMostOverridenMethods(O, Methods)) 9794 return true; 9795 return false; 9796 } 9797 9798 public: 9799 /// Member lookup function that determines whether a given C++ 9800 /// method overloads virtual methods in a base class without overriding any, 9801 /// to be used with CXXRecordDecl::lookupInBases(). 9802 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 9803 RecordDecl *BaseRecord = 9804 Specifier->getType()->castAs<RecordType>()->getDecl(); 9805 9806 DeclarationName Name = Method->getDeclName(); 9807 assert(Name.getNameKind() == DeclarationName::Identifier); 9808 9809 bool foundSameNameMethod = false; 9810 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 9811 for (Path.Decls = BaseRecord->lookup(Name).begin(); 9812 Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) { 9813 NamedDecl *D = *Path.Decls; 9814 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 9815 MD = MD->getCanonicalDecl(); 9816 foundSameNameMethod = true; 9817 // Interested only in hidden virtual methods. 9818 if (!MD->isVirtual()) 9819 continue; 9820 // If the method we are checking overrides a method from its base 9821 // don't warn about the other overloaded methods. Clang deviates from 9822 // GCC by only diagnosing overloads of inherited virtual functions that 9823 // do not override any other virtual functions in the base. GCC's 9824 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 9825 // function from a base class. These cases may be better served by a 9826 // warning (not specific to virtual functions) on call sites when the 9827 // call would select a different function from the base class, were it 9828 // visible. 9829 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 9830 if (!S->IsOverload(Method, MD, false)) 9831 return true; 9832 // Collect the overload only if its hidden. 9833 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods)) 9834 overloadedMethods.push_back(MD); 9835 } 9836 } 9837 9838 if (foundSameNameMethod) 9839 OverloadedMethods.append(overloadedMethods.begin(), 9840 overloadedMethods.end()); 9841 return foundSameNameMethod; 9842 } 9843 }; 9844 } // end anonymous namespace 9845 9846 /// Add the most overridden methods from MD to Methods 9847 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 9848 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 9849 if (MD->size_overridden_methods() == 0) 9850 Methods.insert(MD->getCanonicalDecl()); 9851 else 9852 for (const CXXMethodDecl *O : MD->overridden_methods()) 9853 AddMostOverridenMethods(O, Methods); 9854 } 9855 9856 /// Check if a method overloads virtual methods in a base class without 9857 /// overriding any. 9858 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 9859 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 9860 if (!MD->getDeclName().isIdentifier()) 9861 return; 9862 9863 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 9864 /*bool RecordPaths=*/false, 9865 /*bool DetectVirtual=*/false); 9866 FindHiddenVirtualMethod FHVM; 9867 FHVM.Method = MD; 9868 FHVM.S = this; 9869 9870 // Keep the base methods that were overridden or introduced in the subclass 9871 // by 'using' in a set. A base method not in this set is hidden. 9872 CXXRecordDecl *DC = MD->getParent(); 9873 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 9874 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 9875 NamedDecl *ND = *I; 9876 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 9877 ND = shad->getTargetDecl(); 9878 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 9879 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods); 9880 } 9881 9882 if (DC->lookupInBases(FHVM, Paths)) 9883 OverloadedMethods = FHVM.OverloadedMethods; 9884 } 9885 9886 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 9887 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 9888 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 9889 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 9890 PartialDiagnostic PD = PDiag( 9891 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 9892 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 9893 Diag(overloadedMD->getLocation(), PD); 9894 } 9895 } 9896 9897 /// Diagnose methods which overload virtual methods in a base class 9898 /// without overriding any. 9899 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 9900 if (MD->isInvalidDecl()) 9901 return; 9902 9903 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 9904 return; 9905 9906 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 9907 FindHiddenVirtualMethods(MD, OverloadedMethods); 9908 if (!OverloadedMethods.empty()) { 9909 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 9910 << MD << (OverloadedMethods.size() > 1); 9911 9912 NoteHiddenVirtualMethods(MD, OverloadedMethods); 9913 } 9914 } 9915 9916 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) { 9917 auto PrintDiagAndRemoveAttr = [&](unsigned N) { 9918 // No diagnostics if this is a template instantiation. 9919 if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) { 9920 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), 9921 diag::ext_cannot_use_trivial_abi) << &RD; 9922 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), 9923 diag::note_cannot_use_trivial_abi_reason) << &RD << N; 9924 } 9925 RD.dropAttr<TrivialABIAttr>(); 9926 }; 9927 9928 // Ill-formed if the copy and move constructors are deleted. 9929 auto HasNonDeletedCopyOrMoveConstructor = [&]() { 9930 // If the type is dependent, then assume it might have 9931 // implicit copy or move ctor because we won't know yet at this point. 9932 if (RD.isDependentType()) 9933 return true; 9934 if (RD.needsImplicitCopyConstructor() && 9935 !RD.defaultedCopyConstructorIsDeleted()) 9936 return true; 9937 if (RD.needsImplicitMoveConstructor() && 9938 !RD.defaultedMoveConstructorIsDeleted()) 9939 return true; 9940 for (const CXXConstructorDecl *CD : RD.ctors()) 9941 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted()) 9942 return true; 9943 return false; 9944 }; 9945 9946 if (!HasNonDeletedCopyOrMoveConstructor()) { 9947 PrintDiagAndRemoveAttr(0); 9948 return; 9949 } 9950 9951 // Ill-formed if the struct has virtual functions. 9952 if (RD.isPolymorphic()) { 9953 PrintDiagAndRemoveAttr(1); 9954 return; 9955 } 9956 9957 for (const auto &B : RD.bases()) { 9958 // Ill-formed if the base class is non-trivial for the purpose of calls or a 9959 // virtual base. 9960 if (!B.getType()->isDependentType() && 9961 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) { 9962 PrintDiagAndRemoveAttr(2); 9963 return; 9964 } 9965 9966 if (B.isVirtual()) { 9967 PrintDiagAndRemoveAttr(3); 9968 return; 9969 } 9970 } 9971 9972 for (const auto *FD : RD.fields()) { 9973 // Ill-formed if the field is an ObjectiveC pointer or of a type that is 9974 // non-trivial for the purpose of calls. 9975 QualType FT = FD->getType(); 9976 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) { 9977 PrintDiagAndRemoveAttr(4); 9978 return; 9979 } 9980 9981 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>()) 9982 if (!RT->isDependentType() && 9983 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) { 9984 PrintDiagAndRemoveAttr(5); 9985 return; 9986 } 9987 } 9988 } 9989 9990 void Sema::ActOnFinishCXXMemberSpecification( 9991 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, 9992 SourceLocation RBrac, const ParsedAttributesView &AttrList) { 9993 if (!TagDecl) 9994 return; 9995 9996 AdjustDeclIfTemplate(TagDecl); 9997 9998 for (const ParsedAttr &AL : AttrList) { 9999 if (AL.getKind() != ParsedAttr::AT_Visibility) 10000 continue; 10001 AL.setInvalid(); 10002 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL; 10003 } 10004 10005 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 10006 // strict aliasing violation! 10007 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 10008 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 10009 10010 CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl)); 10011 } 10012 10013 /// Find the equality comparison functions that should be implicitly declared 10014 /// in a given class definition, per C++2a [class.compare.default]p3. 10015 static void findImplicitlyDeclaredEqualityComparisons( 10016 ASTContext &Ctx, CXXRecordDecl *RD, 10017 llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) { 10018 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual); 10019 if (!RD->lookup(EqEq).empty()) 10020 // Member operator== explicitly declared: no implicit operator==s. 10021 return; 10022 10023 // Traverse friends looking for an '==' or a '<=>'. 10024 for (FriendDecl *Friend : RD->friends()) { 10025 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl()); 10026 if (!FD) continue; 10027 10028 if (FD->getOverloadedOperator() == OO_EqualEqual) { 10029 // Friend operator== explicitly declared: no implicit operator==s. 10030 Spaceships.clear(); 10031 return; 10032 } 10033 10034 if (FD->getOverloadedOperator() == OO_Spaceship && 10035 FD->isExplicitlyDefaulted()) 10036 Spaceships.push_back(FD); 10037 } 10038 10039 // Look for members named 'operator<=>'. 10040 DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship); 10041 for (NamedDecl *ND : RD->lookup(Cmp)) { 10042 // Note that we could find a non-function here (either a function template 10043 // or a using-declaration). Neither case results in an implicit 10044 // 'operator=='. 10045 if (auto *FD = dyn_cast<FunctionDecl>(ND)) 10046 if (FD->isExplicitlyDefaulted()) 10047 Spaceships.push_back(FD); 10048 } 10049 } 10050 10051 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 10052 /// special functions, such as the default constructor, copy 10053 /// constructor, or destructor, to the given C++ class (C++ 10054 /// [special]p1). This routine can only be executed just before the 10055 /// definition of the class is complete. 10056 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 10057 // Don't add implicit special members to templated classes. 10058 // FIXME: This means unqualified lookups for 'operator=' within a class 10059 // template don't work properly. 10060 if (!ClassDecl->isDependentType()) { 10061 if (ClassDecl->needsImplicitDefaultConstructor()) { 10062 ++getASTContext().NumImplicitDefaultConstructors; 10063 10064 if (ClassDecl->hasInheritedConstructor()) 10065 DeclareImplicitDefaultConstructor(ClassDecl); 10066 } 10067 10068 if (ClassDecl->needsImplicitCopyConstructor()) { 10069 ++getASTContext().NumImplicitCopyConstructors; 10070 10071 // If the properties or semantics of the copy constructor couldn't be 10072 // determined while the class was being declared, force a declaration 10073 // of it now. 10074 if (ClassDecl->needsOverloadResolutionForCopyConstructor() || 10075 ClassDecl->hasInheritedConstructor()) 10076 DeclareImplicitCopyConstructor(ClassDecl); 10077 // For the MS ABI we need to know whether the copy ctor is deleted. A 10078 // prerequisite for deleting the implicit copy ctor is that the class has 10079 // a move ctor or move assignment that is either user-declared or whose 10080 // semantics are inherited from a subobject. FIXME: We should provide a 10081 // more direct way for CodeGen to ask whether the constructor was deleted. 10082 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 10083 (ClassDecl->hasUserDeclaredMoveConstructor() || 10084 ClassDecl->needsOverloadResolutionForMoveConstructor() || 10085 ClassDecl->hasUserDeclaredMoveAssignment() || 10086 ClassDecl->needsOverloadResolutionForMoveAssignment())) 10087 DeclareImplicitCopyConstructor(ClassDecl); 10088 } 10089 10090 if (getLangOpts().CPlusPlus11 && 10091 ClassDecl->needsImplicitMoveConstructor()) { 10092 ++getASTContext().NumImplicitMoveConstructors; 10093 10094 if (ClassDecl->needsOverloadResolutionForMoveConstructor() || 10095 ClassDecl->hasInheritedConstructor()) 10096 DeclareImplicitMoveConstructor(ClassDecl); 10097 } 10098 10099 if (ClassDecl->needsImplicitCopyAssignment()) { 10100 ++getASTContext().NumImplicitCopyAssignmentOperators; 10101 10102 // If we have a dynamic class, then the copy assignment operator may be 10103 // virtual, so we have to declare it immediately. This ensures that, e.g., 10104 // it shows up in the right place in the vtable and that we diagnose 10105 // problems with the implicit exception specification. 10106 if (ClassDecl->isDynamicClass() || 10107 ClassDecl->needsOverloadResolutionForCopyAssignment() || 10108 ClassDecl->hasInheritedAssignment()) 10109 DeclareImplicitCopyAssignment(ClassDecl); 10110 } 10111 10112 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 10113 ++getASTContext().NumImplicitMoveAssignmentOperators; 10114 10115 // Likewise for the move assignment operator. 10116 if (ClassDecl->isDynamicClass() || 10117 ClassDecl->needsOverloadResolutionForMoveAssignment() || 10118 ClassDecl->hasInheritedAssignment()) 10119 DeclareImplicitMoveAssignment(ClassDecl); 10120 } 10121 10122 if (ClassDecl->needsImplicitDestructor()) { 10123 ++getASTContext().NumImplicitDestructors; 10124 10125 // If we have a dynamic class, then the destructor may be virtual, so we 10126 // have to declare the destructor immediately. This ensures that, e.g., it 10127 // shows up in the right place in the vtable and that we diagnose problems 10128 // with the implicit exception specification. 10129 if (ClassDecl->isDynamicClass() || 10130 ClassDecl->needsOverloadResolutionForDestructor()) 10131 DeclareImplicitDestructor(ClassDecl); 10132 } 10133 } 10134 10135 // C++2a [class.compare.default]p3: 10136 // If the member-specification does not explicitly declare any member or 10137 // friend named operator==, an == operator function is declared implicitly 10138 // for each defaulted three-way comparison operator function defined in 10139 // the member-specification 10140 // FIXME: Consider doing this lazily. 10141 // We do this during the initial parse for a class template, not during 10142 // instantiation, so that we can handle unqualified lookups for 'operator==' 10143 // when parsing the template. 10144 if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) { 10145 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships; 10146 findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl, 10147 DefaultedSpaceships); 10148 for (auto *FD : DefaultedSpaceships) 10149 DeclareImplicitEqualityComparison(ClassDecl, FD); 10150 } 10151 } 10152 10153 unsigned 10154 Sema::ActOnReenterTemplateScope(Decl *D, 10155 llvm::function_ref<Scope *()> EnterScope) { 10156 if (!D) 10157 return 0; 10158 AdjustDeclIfTemplate(D); 10159 10160 // In order to get name lookup right, reenter template scopes in order from 10161 // outermost to innermost. 10162 SmallVector<TemplateParameterList *, 4> ParameterLists; 10163 DeclContext *LookupDC = dyn_cast<DeclContext>(D); 10164 10165 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 10166 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 10167 ParameterLists.push_back(DD->getTemplateParameterList(i)); 10168 10169 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 10170 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 10171 ParameterLists.push_back(FTD->getTemplateParameters()); 10172 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 10173 LookupDC = VD->getDeclContext(); 10174 10175 if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate()) 10176 ParameterLists.push_back(VTD->getTemplateParameters()); 10177 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D)) 10178 ParameterLists.push_back(PSD->getTemplateParameters()); 10179 } 10180 } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 10181 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 10182 ParameterLists.push_back(TD->getTemplateParameterList(i)); 10183 10184 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 10185 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 10186 ParameterLists.push_back(CTD->getTemplateParameters()); 10187 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 10188 ParameterLists.push_back(PSD->getTemplateParameters()); 10189 } 10190 } 10191 // FIXME: Alias declarations and concepts. 10192 10193 unsigned Count = 0; 10194 Scope *InnermostTemplateScope = nullptr; 10195 for (TemplateParameterList *Params : ParameterLists) { 10196 // Ignore explicit specializations; they don't contribute to the template 10197 // depth. 10198 if (Params->size() == 0) 10199 continue; 10200 10201 InnermostTemplateScope = EnterScope(); 10202 for (NamedDecl *Param : *Params) { 10203 if (Param->getDeclName()) { 10204 InnermostTemplateScope->AddDecl(Param); 10205 IdResolver.AddDecl(Param); 10206 } 10207 } 10208 ++Count; 10209 } 10210 10211 // Associate the new template scopes with the corresponding entities. 10212 if (InnermostTemplateScope) { 10213 assert(LookupDC && "no enclosing DeclContext for template lookup"); 10214 EnterTemplatedContext(InnermostTemplateScope, LookupDC); 10215 } 10216 10217 return Count; 10218 } 10219 10220 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 10221 if (!RecordD) return; 10222 AdjustDeclIfTemplate(RecordD); 10223 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 10224 PushDeclContext(S, Record); 10225 } 10226 10227 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 10228 if (!RecordD) return; 10229 PopDeclContext(); 10230 } 10231 10232 /// This is used to implement the constant expression evaluation part of the 10233 /// attribute enable_if extension. There is nothing in standard C++ which would 10234 /// require reentering parameters. 10235 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 10236 if (!Param) 10237 return; 10238 10239 S->AddDecl(Param); 10240 if (Param->getDeclName()) 10241 IdResolver.AddDecl(Param); 10242 } 10243 10244 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 10245 /// parsing a top-level (non-nested) C++ class, and we are now 10246 /// parsing those parts of the given Method declaration that could 10247 /// not be parsed earlier (C++ [class.mem]p2), such as default 10248 /// arguments. This action should enter the scope of the given 10249 /// Method declaration as if we had just parsed the qualified method 10250 /// name. However, it should not bring the parameters into scope; 10251 /// that will be performed by ActOnDelayedCXXMethodParameter. 10252 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 10253 } 10254 10255 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 10256 /// C++ method declaration. We're (re-)introducing the given 10257 /// function parameter into scope for use in parsing later parts of 10258 /// the method declaration. For example, we could see an 10259 /// ActOnParamDefaultArgument event for this parameter. 10260 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 10261 if (!ParamD) 10262 return; 10263 10264 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 10265 10266 S->AddDecl(Param); 10267 if (Param->getDeclName()) 10268 IdResolver.AddDecl(Param); 10269 } 10270 10271 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 10272 /// processing the delayed method declaration for Method. The method 10273 /// declaration is now considered finished. There may be a separate 10274 /// ActOnStartOfFunctionDef action later (not necessarily 10275 /// immediately!) for this method, if it was also defined inside the 10276 /// class body. 10277 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 10278 if (!MethodD) 10279 return; 10280 10281 AdjustDeclIfTemplate(MethodD); 10282 10283 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 10284 10285 // Now that we have our default arguments, check the constructor 10286 // again. It could produce additional diagnostics or affect whether 10287 // the class has implicitly-declared destructors, among other 10288 // things. 10289 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 10290 CheckConstructor(Constructor); 10291 10292 // Check the default arguments, which we may have added. 10293 if (!Method->isInvalidDecl()) 10294 CheckCXXDefaultArguments(Method); 10295 } 10296 10297 // Emit the given diagnostic for each non-address-space qualifier. 10298 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator. 10299 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) { 10300 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10301 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) { 10302 bool DiagOccured = false; 10303 FTI.MethodQualifiers->forEachQualifier( 10304 [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName, 10305 SourceLocation SL) { 10306 // This diagnostic should be emitted on any qualifier except an addr 10307 // space qualifier. However, forEachQualifier currently doesn't visit 10308 // addr space qualifiers, so there's no way to write this condition 10309 // right now; we just diagnose on everything. 10310 S.Diag(SL, DiagID) << QualName << SourceRange(SL); 10311 DiagOccured = true; 10312 }); 10313 if (DiagOccured) 10314 D.setInvalidType(); 10315 } 10316 } 10317 10318 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 10319 /// the well-formedness of the constructor declarator @p D with type @p 10320 /// R. If there are any errors in the declarator, this routine will 10321 /// emit diagnostics and set the invalid bit to true. In any case, the type 10322 /// will be updated to reflect a well-formed type for the constructor and 10323 /// returned. 10324 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 10325 StorageClass &SC) { 10326 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 10327 10328 // C++ [class.ctor]p3: 10329 // A constructor shall not be virtual (10.3) or static (9.4). A 10330 // constructor can be invoked for a const, volatile or const 10331 // volatile object. A constructor shall not be declared const, 10332 // volatile, or const volatile (9.3.2). 10333 if (isVirtual) { 10334 if (!D.isInvalidType()) 10335 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 10336 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 10337 << SourceRange(D.getIdentifierLoc()); 10338 D.setInvalidType(); 10339 } 10340 if (SC == SC_Static) { 10341 if (!D.isInvalidType()) 10342 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 10343 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10344 << SourceRange(D.getIdentifierLoc()); 10345 D.setInvalidType(); 10346 SC = SC_None; 10347 } 10348 10349 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 10350 diagnoseIgnoredQualifiers( 10351 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 10352 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 10353 D.getDeclSpec().getRestrictSpecLoc(), 10354 D.getDeclSpec().getAtomicSpecLoc()); 10355 D.setInvalidType(); 10356 } 10357 10358 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor); 10359 10360 // C++0x [class.ctor]p4: 10361 // A constructor shall not be declared with a ref-qualifier. 10362 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10363 if (FTI.hasRefQualifier()) { 10364 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 10365 << FTI.RefQualifierIsLValueRef 10366 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 10367 D.setInvalidType(); 10368 } 10369 10370 // Rebuild the function type "R" without any type qualifiers (in 10371 // case any of the errors above fired) and with "void" as the 10372 // return type, since constructors don't have return types. 10373 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>(); 10374 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 10375 return R; 10376 10377 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 10378 EPI.TypeQuals = Qualifiers(); 10379 EPI.RefQualifier = RQ_None; 10380 10381 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 10382 } 10383 10384 /// CheckConstructor - Checks a fully-formed constructor for 10385 /// well-formedness, issuing any diagnostics required. Returns true if 10386 /// the constructor declarator is invalid. 10387 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 10388 CXXRecordDecl *ClassDecl 10389 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 10390 if (!ClassDecl) 10391 return Constructor->setInvalidDecl(); 10392 10393 // C++ [class.copy]p3: 10394 // A declaration of a constructor for a class X is ill-formed if 10395 // its first parameter is of type (optionally cv-qualified) X and 10396 // either there are no other parameters or else all other 10397 // parameters have default arguments. 10398 if (!Constructor->isInvalidDecl() && 10399 Constructor->hasOneParamOrDefaultArgs() && 10400 Constructor->getTemplateSpecializationKind() != 10401 TSK_ImplicitInstantiation) { 10402 QualType ParamType = Constructor->getParamDecl(0)->getType(); 10403 QualType ClassTy = Context.getTagDeclType(ClassDecl); 10404 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 10405 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 10406 const char *ConstRef 10407 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 10408 : " const &"; 10409 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 10410 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 10411 10412 // FIXME: Rather that making the constructor invalid, we should endeavor 10413 // to fix the type. 10414 Constructor->setInvalidDecl(); 10415 } 10416 } 10417 } 10418 10419 /// CheckDestructor - Checks a fully-formed destructor definition for 10420 /// well-formedness, issuing any diagnostics required. Returns true 10421 /// on error. 10422 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 10423 CXXRecordDecl *RD = Destructor->getParent(); 10424 10425 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 10426 SourceLocation Loc; 10427 10428 if (!Destructor->isImplicit()) 10429 Loc = Destructor->getLocation(); 10430 else 10431 Loc = RD->getLocation(); 10432 10433 // If we have a virtual destructor, look up the deallocation function 10434 if (FunctionDecl *OperatorDelete = 10435 FindDeallocationFunctionForDestructor(Loc, RD)) { 10436 Expr *ThisArg = nullptr; 10437 10438 // If the notional 'delete this' expression requires a non-trivial 10439 // conversion from 'this' to the type of a destroying operator delete's 10440 // first parameter, perform that conversion now. 10441 if (OperatorDelete->isDestroyingOperatorDelete()) { 10442 QualType ParamType = OperatorDelete->getParamDecl(0)->getType(); 10443 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) { 10444 // C++ [class.dtor]p13: 10445 // ... as if for the expression 'delete this' appearing in a 10446 // non-virtual destructor of the destructor's class. 10447 ContextRAII SwitchContext(*this, Destructor); 10448 ExprResult This = 10449 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation()); 10450 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?"); 10451 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing); 10452 if (This.isInvalid()) { 10453 // FIXME: Register this as a context note so that it comes out 10454 // in the right order. 10455 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here); 10456 return true; 10457 } 10458 ThisArg = This.get(); 10459 } 10460 } 10461 10462 DiagnoseUseOfDecl(OperatorDelete, Loc); 10463 MarkFunctionReferenced(Loc, OperatorDelete); 10464 Destructor->setOperatorDelete(OperatorDelete, ThisArg); 10465 } 10466 } 10467 10468 return false; 10469 } 10470 10471 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 10472 /// the well-formednes of the destructor declarator @p D with type @p 10473 /// R. If there are any errors in the declarator, this routine will 10474 /// emit diagnostics and set the declarator to invalid. Even if this happens, 10475 /// will be updated to reflect a well-formed type for the destructor and 10476 /// returned. 10477 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 10478 StorageClass& SC) { 10479 // C++ [class.dtor]p1: 10480 // [...] A typedef-name that names a class is a class-name 10481 // (7.1.3); however, a typedef-name that names a class shall not 10482 // be used as the identifier in the declarator for a destructor 10483 // declaration. 10484 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 10485 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 10486 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name) 10487 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 10488 else if (const TemplateSpecializationType *TST = 10489 DeclaratorType->getAs<TemplateSpecializationType>()) 10490 if (TST->isTypeAlias()) 10491 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name) 10492 << DeclaratorType << 1; 10493 10494 // C++ [class.dtor]p2: 10495 // A destructor is used to destroy objects of its class type. A 10496 // destructor takes no parameters, and no return type can be 10497 // specified for it (not even void). The address of a destructor 10498 // shall not be taken. A destructor shall not be static. A 10499 // destructor can be invoked for a const, volatile or const 10500 // volatile object. A destructor shall not be declared const, 10501 // volatile or const volatile (9.3.2). 10502 if (SC == SC_Static) { 10503 if (!D.isInvalidType()) 10504 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 10505 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10506 << SourceRange(D.getIdentifierLoc()) 10507 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 10508 10509 SC = SC_None; 10510 } 10511 if (!D.isInvalidType()) { 10512 // Destructors don't have return types, but the parser will 10513 // happily parse something like: 10514 // 10515 // class X { 10516 // float ~X(); 10517 // }; 10518 // 10519 // The return type will be eliminated later. 10520 if (D.getDeclSpec().hasTypeSpecifier()) 10521 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 10522 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 10523 << SourceRange(D.getIdentifierLoc()); 10524 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 10525 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 10526 SourceLocation(), 10527 D.getDeclSpec().getConstSpecLoc(), 10528 D.getDeclSpec().getVolatileSpecLoc(), 10529 D.getDeclSpec().getRestrictSpecLoc(), 10530 D.getDeclSpec().getAtomicSpecLoc()); 10531 D.setInvalidType(); 10532 } 10533 } 10534 10535 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor); 10536 10537 // C++0x [class.dtor]p2: 10538 // A destructor shall not be declared with a ref-qualifier. 10539 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10540 if (FTI.hasRefQualifier()) { 10541 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 10542 << FTI.RefQualifierIsLValueRef 10543 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 10544 D.setInvalidType(); 10545 } 10546 10547 // Make sure we don't have any parameters. 10548 if (FTIHasNonVoidParameters(FTI)) { 10549 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 10550 10551 // Delete the parameters. 10552 FTI.freeParams(); 10553 D.setInvalidType(); 10554 } 10555 10556 // Make sure the destructor isn't variadic. 10557 if (FTI.isVariadic) { 10558 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 10559 D.setInvalidType(); 10560 } 10561 10562 // Rebuild the function type "R" without any type qualifiers or 10563 // parameters (in case any of the errors above fired) and with 10564 // "void" as the return type, since destructors don't have return 10565 // types. 10566 if (!D.isInvalidType()) 10567 return R; 10568 10569 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>(); 10570 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 10571 EPI.Variadic = false; 10572 EPI.TypeQuals = Qualifiers(); 10573 EPI.RefQualifier = RQ_None; 10574 return Context.getFunctionType(Context.VoidTy, None, EPI); 10575 } 10576 10577 static void extendLeft(SourceRange &R, SourceRange Before) { 10578 if (Before.isInvalid()) 10579 return; 10580 R.setBegin(Before.getBegin()); 10581 if (R.getEnd().isInvalid()) 10582 R.setEnd(Before.getEnd()); 10583 } 10584 10585 static void extendRight(SourceRange &R, SourceRange After) { 10586 if (After.isInvalid()) 10587 return; 10588 if (R.getBegin().isInvalid()) 10589 R.setBegin(After.getBegin()); 10590 R.setEnd(After.getEnd()); 10591 } 10592 10593 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 10594 /// well-formednes of the conversion function declarator @p D with 10595 /// type @p R. If there are any errors in the declarator, this routine 10596 /// will emit diagnostics and return true. Otherwise, it will return 10597 /// false. Either way, the type @p R will be updated to reflect a 10598 /// well-formed type for the conversion operator. 10599 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 10600 StorageClass& SC) { 10601 // C++ [class.conv.fct]p1: 10602 // Neither parameter types nor return type can be specified. The 10603 // type of a conversion function (8.3.5) is "function taking no 10604 // parameter returning conversion-type-id." 10605 if (SC == SC_Static) { 10606 if (!D.isInvalidType()) 10607 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 10608 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10609 << D.getName().getSourceRange(); 10610 D.setInvalidType(); 10611 SC = SC_None; 10612 } 10613 10614 TypeSourceInfo *ConvTSI = nullptr; 10615 QualType ConvType = 10616 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); 10617 10618 const DeclSpec &DS = D.getDeclSpec(); 10619 if (DS.hasTypeSpecifier() && !D.isInvalidType()) { 10620 // Conversion functions don't have return types, but the parser will 10621 // happily parse something like: 10622 // 10623 // class X { 10624 // float operator bool(); 10625 // }; 10626 // 10627 // The return type will be changed later anyway. 10628 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 10629 << SourceRange(DS.getTypeSpecTypeLoc()) 10630 << SourceRange(D.getIdentifierLoc()); 10631 D.setInvalidType(); 10632 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) { 10633 // It's also plausible that the user writes type qualifiers in the wrong 10634 // place, such as: 10635 // struct S { const operator int(); }; 10636 // FIXME: we could provide a fixit to move the qualifiers onto the 10637 // conversion type. 10638 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 10639 << SourceRange(D.getIdentifierLoc()) << 0; 10640 D.setInvalidType(); 10641 } 10642 10643 const auto *Proto = R->castAs<FunctionProtoType>(); 10644 10645 // Make sure we don't have any parameters. 10646 if (Proto->getNumParams() > 0) { 10647 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 10648 10649 // Delete the parameters. 10650 D.getFunctionTypeInfo().freeParams(); 10651 D.setInvalidType(); 10652 } else if (Proto->isVariadic()) { 10653 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 10654 D.setInvalidType(); 10655 } 10656 10657 // Diagnose "&operator bool()" and other such nonsense. This 10658 // is actually a gcc extension which we don't support. 10659 if (Proto->getReturnType() != ConvType) { 10660 bool NeedsTypedef = false; 10661 SourceRange Before, After; 10662 10663 // Walk the chunks and extract information on them for our diagnostic. 10664 bool PastFunctionChunk = false; 10665 for (auto &Chunk : D.type_objects()) { 10666 switch (Chunk.Kind) { 10667 case DeclaratorChunk::Function: 10668 if (!PastFunctionChunk) { 10669 if (Chunk.Fun.HasTrailingReturnType) { 10670 TypeSourceInfo *TRT = nullptr; 10671 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); 10672 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); 10673 } 10674 PastFunctionChunk = true; 10675 break; 10676 } 10677 LLVM_FALLTHROUGH; 10678 case DeclaratorChunk::Array: 10679 NeedsTypedef = true; 10680 extendRight(After, Chunk.getSourceRange()); 10681 break; 10682 10683 case DeclaratorChunk::Pointer: 10684 case DeclaratorChunk::BlockPointer: 10685 case DeclaratorChunk::Reference: 10686 case DeclaratorChunk::MemberPointer: 10687 case DeclaratorChunk::Pipe: 10688 extendLeft(Before, Chunk.getSourceRange()); 10689 break; 10690 10691 case DeclaratorChunk::Paren: 10692 extendLeft(Before, Chunk.Loc); 10693 extendRight(After, Chunk.EndLoc); 10694 break; 10695 } 10696 } 10697 10698 SourceLocation Loc = Before.isValid() ? Before.getBegin() : 10699 After.isValid() ? After.getBegin() : 10700 D.getIdentifierLoc(); 10701 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); 10702 DB << Before << After; 10703 10704 if (!NeedsTypedef) { 10705 DB << /*don't need a typedef*/0; 10706 10707 // If we can provide a correct fix-it hint, do so. 10708 if (After.isInvalid() && ConvTSI) { 10709 SourceLocation InsertLoc = 10710 getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc()); 10711 DB << FixItHint::CreateInsertion(InsertLoc, " ") 10712 << FixItHint::CreateInsertionFromRange( 10713 InsertLoc, CharSourceRange::getTokenRange(Before)) 10714 << FixItHint::CreateRemoval(Before); 10715 } 10716 } else if (!Proto->getReturnType()->isDependentType()) { 10717 DB << /*typedef*/1 << Proto->getReturnType(); 10718 } else if (getLangOpts().CPlusPlus11) { 10719 DB << /*alias template*/2 << Proto->getReturnType(); 10720 } else { 10721 DB << /*might not be fixable*/3; 10722 } 10723 10724 // Recover by incorporating the other type chunks into the result type. 10725 // Note, this does *not* change the name of the function. This is compatible 10726 // with the GCC extension: 10727 // struct S { &operator int(); } s; 10728 // int &r = s.operator int(); // ok in GCC 10729 // S::operator int&() {} // error in GCC, function name is 'operator int'. 10730 ConvType = Proto->getReturnType(); 10731 } 10732 10733 // C++ [class.conv.fct]p4: 10734 // The conversion-type-id shall not represent a function type nor 10735 // an array type. 10736 if (ConvType->isArrayType()) { 10737 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 10738 ConvType = Context.getPointerType(ConvType); 10739 D.setInvalidType(); 10740 } else if (ConvType->isFunctionType()) { 10741 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 10742 ConvType = Context.getPointerType(ConvType); 10743 D.setInvalidType(); 10744 } 10745 10746 // Rebuild the function type "R" without any parameters (in case any 10747 // of the errors above fired) and with the conversion type as the 10748 // return type. 10749 if (D.isInvalidType()) 10750 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 10751 10752 // C++0x explicit conversion operators. 10753 if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20) 10754 Diag(DS.getExplicitSpecLoc(), 10755 getLangOpts().CPlusPlus11 10756 ? diag::warn_cxx98_compat_explicit_conversion_functions 10757 : diag::ext_explicit_conversion_functions) 10758 << SourceRange(DS.getExplicitSpecRange()); 10759 } 10760 10761 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 10762 /// the declaration of the given C++ conversion function. This routine 10763 /// is responsible for recording the conversion function in the C++ 10764 /// class, if possible. 10765 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 10766 assert(Conversion && "Expected to receive a conversion function declaration"); 10767 10768 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 10769 10770 // Make sure we aren't redeclaring the conversion function. 10771 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 10772 // C++ [class.conv.fct]p1: 10773 // [...] A conversion function is never used to convert a 10774 // (possibly cv-qualified) object to the (possibly cv-qualified) 10775 // same object type (or a reference to it), to a (possibly 10776 // cv-qualified) base class of that type (or a reference to it), 10777 // or to (possibly cv-qualified) void. 10778 QualType ClassType 10779 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 10780 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 10781 ConvType = ConvTypeRef->getPointeeType(); 10782 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 10783 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 10784 /* Suppress diagnostics for instantiations. */; 10785 else if (Conversion->size_overridden_methods() != 0) 10786 /* Suppress diagnostics for overriding virtual function in a base class. */; 10787 else if (ConvType->isRecordType()) { 10788 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 10789 if (ConvType == ClassType) 10790 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 10791 << ClassType; 10792 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType)) 10793 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 10794 << ClassType << ConvType; 10795 } else if (ConvType->isVoidType()) { 10796 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 10797 << ClassType << ConvType; 10798 } 10799 10800 if (FunctionTemplateDecl *ConversionTemplate 10801 = Conversion->getDescribedFunctionTemplate()) 10802 return ConversionTemplate; 10803 10804 return Conversion; 10805 } 10806 10807 namespace { 10808 /// Utility class to accumulate and print a diagnostic listing the invalid 10809 /// specifier(s) on a declaration. 10810 struct BadSpecifierDiagnoser { 10811 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID) 10812 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {} 10813 ~BadSpecifierDiagnoser() { 10814 Diagnostic << Specifiers; 10815 } 10816 10817 template<typename T> void check(SourceLocation SpecLoc, T Spec) { 10818 return check(SpecLoc, DeclSpec::getSpecifierName(Spec)); 10819 } 10820 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) { 10821 return check(SpecLoc, 10822 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy())); 10823 } 10824 void check(SourceLocation SpecLoc, const char *Spec) { 10825 if (SpecLoc.isInvalid()) return; 10826 Diagnostic << SourceRange(SpecLoc, SpecLoc); 10827 if (!Specifiers.empty()) Specifiers += " "; 10828 Specifiers += Spec; 10829 } 10830 10831 Sema &S; 10832 Sema::SemaDiagnosticBuilder Diagnostic; 10833 std::string Specifiers; 10834 }; 10835 } 10836 10837 /// Check the validity of a declarator that we parsed for a deduction-guide. 10838 /// These aren't actually declarators in the grammar, so we need to check that 10839 /// the user didn't specify any pieces that are not part of the deduction-guide 10840 /// grammar. 10841 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R, 10842 StorageClass &SC) { 10843 TemplateName GuidedTemplate = D.getName().TemplateName.get().get(); 10844 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl(); 10845 assert(GuidedTemplateDecl && "missing template decl for deduction guide"); 10846 10847 // C++ [temp.deduct.guide]p3: 10848 // A deduction-gide shall be declared in the same scope as the 10849 // corresponding class template. 10850 if (!CurContext->getRedeclContext()->Equals( 10851 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) { 10852 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope) 10853 << GuidedTemplateDecl; 10854 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here); 10855 } 10856 10857 auto &DS = D.getMutableDeclSpec(); 10858 // We leave 'friend' and 'virtual' to be rejected in the normal way. 10859 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() || 10860 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() || 10861 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) { 10862 BadSpecifierDiagnoser Diagnoser( 10863 *this, D.getIdentifierLoc(), 10864 diag::err_deduction_guide_invalid_specifier); 10865 10866 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec()); 10867 DS.ClearStorageClassSpecs(); 10868 SC = SC_None; 10869 10870 // 'explicit' is permitted. 10871 Diagnoser.check(DS.getInlineSpecLoc(), "inline"); 10872 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn"); 10873 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr"); 10874 DS.ClearConstexprSpec(); 10875 10876 Diagnoser.check(DS.getConstSpecLoc(), "const"); 10877 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict"); 10878 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile"); 10879 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic"); 10880 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned"); 10881 DS.ClearTypeQualifiers(); 10882 10883 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex()); 10884 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign()); 10885 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth()); 10886 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType()); 10887 DS.ClearTypeSpecType(); 10888 } 10889 10890 if (D.isInvalidType()) 10891 return; 10892 10893 // Check the declarator is simple enough. 10894 bool FoundFunction = false; 10895 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) { 10896 if (Chunk.Kind == DeclaratorChunk::Paren) 10897 continue; 10898 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) { 10899 Diag(D.getDeclSpec().getBeginLoc(), 10900 diag::err_deduction_guide_with_complex_decl) 10901 << D.getSourceRange(); 10902 break; 10903 } 10904 if (!Chunk.Fun.hasTrailingReturnType()) { 10905 Diag(D.getName().getBeginLoc(), 10906 diag::err_deduction_guide_no_trailing_return_type); 10907 break; 10908 } 10909 10910 // Check that the return type is written as a specialization of 10911 // the template specified as the deduction-guide's name. 10912 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType(); 10913 TypeSourceInfo *TSI = nullptr; 10914 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI); 10915 assert(TSI && "deduction guide has valid type but invalid return type?"); 10916 bool AcceptableReturnType = false; 10917 bool MightInstantiateToSpecialization = false; 10918 if (auto RetTST = 10919 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) { 10920 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName(); 10921 bool TemplateMatches = 10922 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate); 10923 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches) 10924 AcceptableReturnType = true; 10925 else { 10926 // This could still instantiate to the right type, unless we know it 10927 // names the wrong class template. 10928 auto *TD = SpecifiedName.getAsTemplateDecl(); 10929 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) && 10930 !TemplateMatches); 10931 } 10932 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) { 10933 MightInstantiateToSpecialization = true; 10934 } 10935 10936 if (!AcceptableReturnType) { 10937 Diag(TSI->getTypeLoc().getBeginLoc(), 10938 diag::err_deduction_guide_bad_trailing_return_type) 10939 << GuidedTemplate << TSI->getType() 10940 << MightInstantiateToSpecialization 10941 << TSI->getTypeLoc().getSourceRange(); 10942 } 10943 10944 // Keep going to check that we don't have any inner declarator pieces (we 10945 // could still have a function returning a pointer to a function). 10946 FoundFunction = true; 10947 } 10948 10949 if (D.isFunctionDefinition()) 10950 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function); 10951 } 10952 10953 //===----------------------------------------------------------------------===// 10954 // Namespace Handling 10955 //===----------------------------------------------------------------------===// 10956 10957 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is 10958 /// reopened. 10959 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 10960 SourceLocation Loc, 10961 IdentifierInfo *II, bool *IsInline, 10962 NamespaceDecl *PrevNS) { 10963 assert(*IsInline != PrevNS->isInline()); 10964 10965 if (PrevNS->isInline()) 10966 // The user probably just forgot the 'inline', so suggest that it 10967 // be added back. 10968 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 10969 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 10970 else 10971 S.Diag(Loc, diag::err_inline_namespace_mismatch); 10972 10973 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 10974 *IsInline = PrevNS->isInline(); 10975 } 10976 10977 /// ActOnStartNamespaceDef - This is called at the start of a namespace 10978 /// definition. 10979 Decl *Sema::ActOnStartNamespaceDef( 10980 Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc, 10981 SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace, 10982 const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) { 10983 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 10984 // For anonymous namespace, take the location of the left brace. 10985 SourceLocation Loc = II ? IdentLoc : LBrace; 10986 bool IsInline = InlineLoc.isValid(); 10987 bool IsInvalid = false; 10988 bool IsStd = false; 10989 bool AddToKnown = false; 10990 Scope *DeclRegionScope = NamespcScope->getParent(); 10991 10992 NamespaceDecl *PrevNS = nullptr; 10993 if (II) { 10994 // C++ [namespace.def]p2: 10995 // The identifier in an original-namespace-definition shall not 10996 // have been previously defined in the declarative region in 10997 // which the original-namespace-definition appears. The 10998 // identifier in an original-namespace-definition is the name of 10999 // the namespace. Subsequently in that declarative region, it is 11000 // treated as an original-namespace-name. 11001 // 11002 // Since namespace names are unique in their scope, and we don't 11003 // look through using directives, just look for any ordinary names 11004 // as if by qualified name lookup. 11005 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, 11006 ForExternalRedeclaration); 11007 LookupQualifiedName(R, CurContext->getRedeclContext()); 11008 NamedDecl *PrevDecl = 11009 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr; 11010 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 11011 11012 if (PrevNS) { 11013 // This is an extended namespace definition. 11014 if (IsInline != PrevNS->isInline()) 11015 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 11016 &IsInline, PrevNS); 11017 } else if (PrevDecl) { 11018 // This is an invalid name redefinition. 11019 Diag(Loc, diag::err_redefinition_different_kind) 11020 << II; 11021 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 11022 IsInvalid = true; 11023 // Continue on to push Namespc as current DeclContext and return it. 11024 } else if (II->isStr("std") && 11025 CurContext->getRedeclContext()->isTranslationUnit()) { 11026 // This is the first "real" definition of the namespace "std", so update 11027 // our cache of the "std" namespace to point at this definition. 11028 PrevNS = getStdNamespace(); 11029 IsStd = true; 11030 AddToKnown = !IsInline; 11031 } else { 11032 // We've seen this namespace for the first time. 11033 AddToKnown = !IsInline; 11034 } 11035 } else { 11036 // Anonymous namespaces. 11037 11038 // Determine whether the parent already has an anonymous namespace. 11039 DeclContext *Parent = CurContext->getRedeclContext(); 11040 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 11041 PrevNS = TU->getAnonymousNamespace(); 11042 } else { 11043 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 11044 PrevNS = ND->getAnonymousNamespace(); 11045 } 11046 11047 if (PrevNS && IsInline != PrevNS->isInline()) 11048 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 11049 &IsInline, PrevNS); 11050 } 11051 11052 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 11053 StartLoc, Loc, II, PrevNS); 11054 if (IsInvalid) 11055 Namespc->setInvalidDecl(); 11056 11057 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 11058 AddPragmaAttributes(DeclRegionScope, Namespc); 11059 11060 // FIXME: Should we be merging attributes? 11061 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 11062 PushNamespaceVisibilityAttr(Attr, Loc); 11063 11064 if (IsStd) 11065 StdNamespace = Namespc; 11066 if (AddToKnown) 11067 KnownNamespaces[Namespc] = false; 11068 11069 if (II) { 11070 PushOnScopeChains(Namespc, DeclRegionScope); 11071 } else { 11072 // Link the anonymous namespace into its parent. 11073 DeclContext *Parent = CurContext->getRedeclContext(); 11074 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 11075 TU->setAnonymousNamespace(Namespc); 11076 } else { 11077 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 11078 } 11079 11080 CurContext->addDecl(Namespc); 11081 11082 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 11083 // behaves as if it were replaced by 11084 // namespace unique { /* empty body */ } 11085 // using namespace unique; 11086 // namespace unique { namespace-body } 11087 // where all occurrences of 'unique' in a translation unit are 11088 // replaced by the same identifier and this identifier differs 11089 // from all other identifiers in the entire program. 11090 11091 // We just create the namespace with an empty name and then add an 11092 // implicit using declaration, just like the standard suggests. 11093 // 11094 // CodeGen enforces the "universally unique" aspect by giving all 11095 // declarations semantically contained within an anonymous 11096 // namespace internal linkage. 11097 11098 if (!PrevNS) { 11099 UD = UsingDirectiveDecl::Create(Context, Parent, 11100 /* 'using' */ LBrace, 11101 /* 'namespace' */ SourceLocation(), 11102 /* qualifier */ NestedNameSpecifierLoc(), 11103 /* identifier */ SourceLocation(), 11104 Namespc, 11105 /* Ancestor */ Parent); 11106 UD->setImplicit(); 11107 Parent->addDecl(UD); 11108 } 11109 } 11110 11111 ActOnDocumentableDecl(Namespc); 11112 11113 // Although we could have an invalid decl (i.e. the namespace name is a 11114 // redefinition), push it as current DeclContext and try to continue parsing. 11115 // FIXME: We should be able to push Namespc here, so that the each DeclContext 11116 // for the namespace has the declarations that showed up in that particular 11117 // namespace definition. 11118 PushDeclContext(NamespcScope, Namespc); 11119 return Namespc; 11120 } 11121 11122 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 11123 /// is a namespace alias, returns the namespace it points to. 11124 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 11125 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 11126 return AD->getNamespace(); 11127 return dyn_cast_or_null<NamespaceDecl>(D); 11128 } 11129 11130 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 11131 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 11132 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 11133 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 11134 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 11135 Namespc->setRBraceLoc(RBrace); 11136 PopDeclContext(); 11137 if (Namespc->hasAttr<VisibilityAttr>()) 11138 PopPragmaVisibility(true, RBrace); 11139 // If this namespace contains an export-declaration, export it now. 11140 if (DeferredExportedNamespaces.erase(Namespc)) 11141 Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported); 11142 } 11143 11144 CXXRecordDecl *Sema::getStdBadAlloc() const { 11145 return cast_or_null<CXXRecordDecl>( 11146 StdBadAlloc.get(Context.getExternalSource())); 11147 } 11148 11149 EnumDecl *Sema::getStdAlignValT() const { 11150 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource())); 11151 } 11152 11153 NamespaceDecl *Sema::getStdNamespace() const { 11154 return cast_or_null<NamespaceDecl>( 11155 StdNamespace.get(Context.getExternalSource())); 11156 } 11157 11158 NamespaceDecl *Sema::lookupStdExperimentalNamespace() { 11159 if (!StdExperimentalNamespaceCache) { 11160 if (auto Std = getStdNamespace()) { 11161 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"), 11162 SourceLocation(), LookupNamespaceName); 11163 if (!LookupQualifiedName(Result, Std) || 11164 !(StdExperimentalNamespaceCache = 11165 Result.getAsSingle<NamespaceDecl>())) 11166 Result.suppressDiagnostics(); 11167 } 11168 } 11169 return StdExperimentalNamespaceCache; 11170 } 11171 11172 namespace { 11173 11174 enum UnsupportedSTLSelect { 11175 USS_InvalidMember, 11176 USS_MissingMember, 11177 USS_NonTrivial, 11178 USS_Other 11179 }; 11180 11181 struct InvalidSTLDiagnoser { 11182 Sema &S; 11183 SourceLocation Loc; 11184 QualType TyForDiags; 11185 11186 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "", 11187 const VarDecl *VD = nullptr) { 11188 { 11189 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported) 11190 << TyForDiags << ((int)Sel); 11191 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) { 11192 assert(!Name.empty()); 11193 D << Name; 11194 } 11195 } 11196 if (Sel == USS_InvalidMember) { 11197 S.Diag(VD->getLocation(), diag::note_var_declared_here) 11198 << VD << VD->getSourceRange(); 11199 } 11200 return QualType(); 11201 } 11202 }; 11203 } // namespace 11204 11205 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind, 11206 SourceLocation Loc, 11207 ComparisonCategoryUsage Usage) { 11208 assert(getLangOpts().CPlusPlus && 11209 "Looking for comparison category type outside of C++."); 11210 11211 // Use an elaborated type for diagnostics which has a name containing the 11212 // prepended 'std' namespace but not any inline namespace names. 11213 auto TyForDiags = [&](ComparisonCategoryInfo *Info) { 11214 auto *NNS = 11215 NestedNameSpecifier::Create(Context, nullptr, getStdNamespace()); 11216 return Context.getElaboratedType(ETK_None, NNS, Info->getType()); 11217 }; 11218 11219 // Check if we've already successfully checked the comparison category type 11220 // before. If so, skip checking it again. 11221 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind); 11222 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) { 11223 // The only thing we need to check is that the type has a reachable 11224 // definition in the current context. 11225 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type)) 11226 return QualType(); 11227 11228 return Info->getType(); 11229 } 11230 11231 // If lookup failed 11232 if (!Info) { 11233 std::string NameForDiags = "std::"; 11234 NameForDiags += ComparisonCategories::getCategoryString(Kind); 11235 Diag(Loc, diag::err_implied_comparison_category_type_not_found) 11236 << NameForDiags << (int)Usage; 11237 return QualType(); 11238 } 11239 11240 assert(Info->Kind == Kind); 11241 assert(Info->Record); 11242 11243 // Update the Record decl in case we encountered a forward declaration on our 11244 // first pass. FIXME: This is a bit of a hack. 11245 if (Info->Record->hasDefinition()) 11246 Info->Record = Info->Record->getDefinition(); 11247 11248 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type)) 11249 return QualType(); 11250 11251 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)}; 11252 11253 if (!Info->Record->isTriviallyCopyable()) 11254 return UnsupportedSTLError(USS_NonTrivial); 11255 11256 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) { 11257 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl(); 11258 // Tolerate empty base classes. 11259 if (Base->isEmpty()) 11260 continue; 11261 // Reject STL implementations which have at least one non-empty base. 11262 return UnsupportedSTLError(); 11263 } 11264 11265 // Check that the STL has implemented the types using a single integer field. 11266 // This expectation allows better codegen for builtin operators. We require: 11267 // (1) The class has exactly one field. 11268 // (2) The field is an integral or enumeration type. 11269 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end(); 11270 if (std::distance(FIt, FEnd) != 1 || 11271 !FIt->getType()->isIntegralOrEnumerationType()) { 11272 return UnsupportedSTLError(); 11273 } 11274 11275 // Build each of the require values and store them in Info. 11276 for (ComparisonCategoryResult CCR : 11277 ComparisonCategories::getPossibleResultsForType(Kind)) { 11278 StringRef MemName = ComparisonCategories::getResultString(CCR); 11279 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR); 11280 11281 if (!ValInfo) 11282 return UnsupportedSTLError(USS_MissingMember, MemName); 11283 11284 VarDecl *VD = ValInfo->VD; 11285 assert(VD && "should not be null!"); 11286 11287 // Attempt to diagnose reasons why the STL definition of this type 11288 // might be foobar, including it failing to be a constant expression. 11289 // TODO Handle more ways the lookup or result can be invalid. 11290 if (!VD->isStaticDataMember() || 11291 !VD->isUsableInConstantExpressions(Context)) 11292 return UnsupportedSTLError(USS_InvalidMember, MemName, VD); 11293 11294 // Attempt to evaluate the var decl as a constant expression and extract 11295 // the value of its first field as a ICE. If this fails, the STL 11296 // implementation is not supported. 11297 if (!ValInfo->hasValidIntValue()) 11298 return UnsupportedSTLError(); 11299 11300 MarkVariableReferenced(Loc, VD); 11301 } 11302 11303 // We've successfully built the required types and expressions. Update 11304 // the cache and return the newly cached value. 11305 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true; 11306 return Info->getType(); 11307 } 11308 11309 /// Retrieve the special "std" namespace, which may require us to 11310 /// implicitly define the namespace. 11311 NamespaceDecl *Sema::getOrCreateStdNamespace() { 11312 if (!StdNamespace) { 11313 // The "std" namespace has not yet been defined, so build one implicitly. 11314 StdNamespace = NamespaceDecl::Create(Context, 11315 Context.getTranslationUnitDecl(), 11316 /*Inline=*/false, 11317 SourceLocation(), SourceLocation(), 11318 &PP.getIdentifierTable().get("std"), 11319 /*PrevDecl=*/nullptr); 11320 getStdNamespace()->setImplicit(true); 11321 } 11322 11323 return getStdNamespace(); 11324 } 11325 11326 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 11327 assert(getLangOpts().CPlusPlus && 11328 "Looking for std::initializer_list outside of C++."); 11329 11330 // We're looking for implicit instantiations of 11331 // template <typename E> class std::initializer_list. 11332 11333 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 11334 return false; 11335 11336 ClassTemplateDecl *Template = nullptr; 11337 const TemplateArgument *Arguments = nullptr; 11338 11339 if (const RecordType *RT = Ty->getAs<RecordType>()) { 11340 11341 ClassTemplateSpecializationDecl *Specialization = 11342 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 11343 if (!Specialization) 11344 return false; 11345 11346 Template = Specialization->getSpecializedTemplate(); 11347 Arguments = Specialization->getTemplateArgs().data(); 11348 } else if (const TemplateSpecializationType *TST = 11349 Ty->getAs<TemplateSpecializationType>()) { 11350 Template = dyn_cast_or_null<ClassTemplateDecl>( 11351 TST->getTemplateName().getAsTemplateDecl()); 11352 Arguments = TST->getArgs(); 11353 } 11354 if (!Template) 11355 return false; 11356 11357 if (!StdInitializerList) { 11358 // Haven't recognized std::initializer_list yet, maybe this is it. 11359 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 11360 if (TemplateClass->getIdentifier() != 11361 &PP.getIdentifierTable().get("initializer_list") || 11362 !getStdNamespace()->InEnclosingNamespaceSetOf( 11363 TemplateClass->getDeclContext())) 11364 return false; 11365 // This is a template called std::initializer_list, but is it the right 11366 // template? 11367 TemplateParameterList *Params = Template->getTemplateParameters(); 11368 if (Params->getMinRequiredArguments() != 1) 11369 return false; 11370 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 11371 return false; 11372 11373 // It's the right template. 11374 StdInitializerList = Template; 11375 } 11376 11377 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) 11378 return false; 11379 11380 // This is an instance of std::initializer_list. Find the argument type. 11381 if (Element) 11382 *Element = Arguments[0].getAsType(); 11383 return true; 11384 } 11385 11386 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 11387 NamespaceDecl *Std = S.getStdNamespace(); 11388 if (!Std) { 11389 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 11390 return nullptr; 11391 } 11392 11393 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 11394 Loc, Sema::LookupOrdinaryName); 11395 if (!S.LookupQualifiedName(Result, Std)) { 11396 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 11397 return nullptr; 11398 } 11399 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 11400 if (!Template) { 11401 Result.suppressDiagnostics(); 11402 // We found something weird. Complain about the first thing we found. 11403 NamedDecl *Found = *Result.begin(); 11404 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 11405 return nullptr; 11406 } 11407 11408 // We found some template called std::initializer_list. Now verify that it's 11409 // correct. 11410 TemplateParameterList *Params = Template->getTemplateParameters(); 11411 if (Params->getMinRequiredArguments() != 1 || 11412 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 11413 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 11414 return nullptr; 11415 } 11416 11417 return Template; 11418 } 11419 11420 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 11421 if (!StdInitializerList) { 11422 StdInitializerList = LookupStdInitializerList(*this, Loc); 11423 if (!StdInitializerList) 11424 return QualType(); 11425 } 11426 11427 TemplateArgumentListInfo Args(Loc, Loc); 11428 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 11429 Context.getTrivialTypeSourceInfo(Element, 11430 Loc))); 11431 return Context.getCanonicalType( 11432 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 11433 } 11434 11435 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) { 11436 // C++ [dcl.init.list]p2: 11437 // A constructor is an initializer-list constructor if its first parameter 11438 // is of type std::initializer_list<E> or reference to possibly cv-qualified 11439 // std::initializer_list<E> for some type E, and either there are no other 11440 // parameters or else all other parameters have default arguments. 11441 if (!Ctor->hasOneParamOrDefaultArgs()) 11442 return false; 11443 11444 QualType ArgType = Ctor->getParamDecl(0)->getType(); 11445 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 11446 ArgType = RT->getPointeeType().getUnqualifiedType(); 11447 11448 return isStdInitializerList(ArgType, nullptr); 11449 } 11450 11451 /// Determine whether a using statement is in a context where it will be 11452 /// apply in all contexts. 11453 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 11454 switch (CurContext->getDeclKind()) { 11455 case Decl::TranslationUnit: 11456 return true; 11457 case Decl::LinkageSpec: 11458 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 11459 default: 11460 return false; 11461 } 11462 } 11463 11464 namespace { 11465 11466 // Callback to only accept typo corrections that are namespaces. 11467 class NamespaceValidatorCCC final : public CorrectionCandidateCallback { 11468 public: 11469 bool ValidateCandidate(const TypoCorrection &candidate) override { 11470 if (NamedDecl *ND = candidate.getCorrectionDecl()) 11471 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 11472 return false; 11473 } 11474 11475 std::unique_ptr<CorrectionCandidateCallback> clone() override { 11476 return std::make_unique<NamespaceValidatorCCC>(*this); 11477 } 11478 }; 11479 11480 } 11481 11482 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 11483 CXXScopeSpec &SS, 11484 SourceLocation IdentLoc, 11485 IdentifierInfo *Ident) { 11486 R.clear(); 11487 NamespaceValidatorCCC CCC{}; 11488 if (TypoCorrection Corrected = 11489 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC, 11490 Sema::CTK_ErrorRecovery)) { 11491 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 11492 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 11493 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 11494 Ident->getName().equals(CorrectedStr); 11495 S.diagnoseTypo(Corrected, 11496 S.PDiag(diag::err_using_directive_member_suggest) 11497 << Ident << DC << DroppedSpecifier << SS.getRange(), 11498 S.PDiag(diag::note_namespace_defined_here)); 11499 } else { 11500 S.diagnoseTypo(Corrected, 11501 S.PDiag(diag::err_using_directive_suggest) << Ident, 11502 S.PDiag(diag::note_namespace_defined_here)); 11503 } 11504 R.addDecl(Corrected.getFoundDecl()); 11505 return true; 11506 } 11507 return false; 11508 } 11509 11510 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc, 11511 SourceLocation NamespcLoc, CXXScopeSpec &SS, 11512 SourceLocation IdentLoc, 11513 IdentifierInfo *NamespcName, 11514 const ParsedAttributesView &AttrList) { 11515 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 11516 assert(NamespcName && "Invalid NamespcName."); 11517 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 11518 11519 // This can only happen along a recovery path. 11520 while (S->isTemplateParamScope()) 11521 S = S->getParent(); 11522 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 11523 11524 UsingDirectiveDecl *UDir = nullptr; 11525 NestedNameSpecifier *Qualifier = nullptr; 11526 if (SS.isSet()) 11527 Qualifier = SS.getScopeRep(); 11528 11529 // Lookup namespace name. 11530 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 11531 LookupParsedName(R, S, &SS); 11532 if (R.isAmbiguous()) 11533 return nullptr; 11534 11535 if (R.empty()) { 11536 R.clear(); 11537 // Allow "using namespace std;" or "using namespace ::std;" even if 11538 // "std" hasn't been defined yet, for GCC compatibility. 11539 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 11540 NamespcName->isStr("std")) { 11541 Diag(IdentLoc, diag::ext_using_undefined_std); 11542 R.addDecl(getOrCreateStdNamespace()); 11543 R.resolveKind(); 11544 } 11545 // Otherwise, attempt typo correction. 11546 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 11547 } 11548 11549 if (!R.empty()) { 11550 NamedDecl *Named = R.getRepresentativeDecl(); 11551 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>(); 11552 assert(NS && "expected namespace decl"); 11553 11554 // The use of a nested name specifier may trigger deprecation warnings. 11555 DiagnoseUseOfDecl(Named, IdentLoc); 11556 11557 // C++ [namespace.udir]p1: 11558 // A using-directive specifies that the names in the nominated 11559 // namespace can be used in the scope in which the 11560 // using-directive appears after the using-directive. During 11561 // unqualified name lookup (3.4.1), the names appear as if they 11562 // were declared in the nearest enclosing namespace which 11563 // contains both the using-directive and the nominated 11564 // namespace. [Note: in this context, "contains" means "contains 11565 // directly or indirectly". ] 11566 11567 // Find enclosing context containing both using-directive and 11568 // nominated namespace. 11569 DeclContext *CommonAncestor = NS; 11570 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 11571 CommonAncestor = CommonAncestor->getParent(); 11572 11573 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 11574 SS.getWithLocInContext(Context), 11575 IdentLoc, Named, CommonAncestor); 11576 11577 if (IsUsingDirectiveInToplevelContext(CurContext) && 11578 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 11579 Diag(IdentLoc, diag::warn_using_directive_in_header); 11580 } 11581 11582 PushUsingDirective(S, UDir); 11583 } else { 11584 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 11585 } 11586 11587 if (UDir) 11588 ProcessDeclAttributeList(S, UDir, AttrList); 11589 11590 return UDir; 11591 } 11592 11593 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 11594 // If the scope has an associated entity and the using directive is at 11595 // namespace or translation unit scope, add the UsingDirectiveDecl into 11596 // its lookup structure so qualified name lookup can find it. 11597 DeclContext *Ctx = S->getEntity(); 11598 if (Ctx && !Ctx->isFunctionOrMethod()) 11599 Ctx->addDecl(UDir); 11600 else 11601 // Otherwise, it is at block scope. The using-directives will affect lookup 11602 // only to the end of the scope. 11603 S->PushUsingDirective(UDir); 11604 } 11605 11606 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS, 11607 SourceLocation UsingLoc, 11608 SourceLocation TypenameLoc, CXXScopeSpec &SS, 11609 UnqualifiedId &Name, 11610 SourceLocation EllipsisLoc, 11611 const ParsedAttributesView &AttrList) { 11612 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 11613 11614 if (SS.isEmpty()) { 11615 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname); 11616 return nullptr; 11617 } 11618 11619 switch (Name.getKind()) { 11620 case UnqualifiedIdKind::IK_ImplicitSelfParam: 11621 case UnqualifiedIdKind::IK_Identifier: 11622 case UnqualifiedIdKind::IK_OperatorFunctionId: 11623 case UnqualifiedIdKind::IK_LiteralOperatorId: 11624 case UnqualifiedIdKind::IK_ConversionFunctionId: 11625 break; 11626 11627 case UnqualifiedIdKind::IK_ConstructorName: 11628 case UnqualifiedIdKind::IK_ConstructorTemplateId: 11629 // C++11 inheriting constructors. 11630 Diag(Name.getBeginLoc(), 11631 getLangOpts().CPlusPlus11 11632 ? diag::warn_cxx98_compat_using_decl_constructor 11633 : diag::err_using_decl_constructor) 11634 << SS.getRange(); 11635 11636 if (getLangOpts().CPlusPlus11) break; 11637 11638 return nullptr; 11639 11640 case UnqualifiedIdKind::IK_DestructorName: 11641 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange(); 11642 return nullptr; 11643 11644 case UnqualifiedIdKind::IK_TemplateId: 11645 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id) 11646 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 11647 return nullptr; 11648 11649 case UnqualifiedIdKind::IK_DeductionGuideName: 11650 llvm_unreachable("cannot parse qualified deduction guide name"); 11651 } 11652 11653 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 11654 DeclarationName TargetName = TargetNameInfo.getName(); 11655 if (!TargetName) 11656 return nullptr; 11657 11658 // Warn about access declarations. 11659 if (UsingLoc.isInvalid()) { 11660 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11 11661 ? diag::err_access_decl 11662 : diag::warn_access_decl_deprecated) 11663 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 11664 } 11665 11666 if (EllipsisLoc.isInvalid()) { 11667 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 11668 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 11669 return nullptr; 11670 } else { 11671 if (!SS.getScopeRep()->containsUnexpandedParameterPack() && 11672 !TargetNameInfo.containsUnexpandedParameterPack()) { 11673 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 11674 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc()); 11675 EllipsisLoc = SourceLocation(); 11676 } 11677 } 11678 11679 NamedDecl *UD = 11680 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc, 11681 SS, TargetNameInfo, EllipsisLoc, AttrList, 11682 /*IsInstantiation*/ false, 11683 AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists)); 11684 if (UD) 11685 PushOnScopeChains(UD, S, /*AddToContext*/ false); 11686 11687 return UD; 11688 } 11689 11690 Decl *Sema::ActOnUsingEnumDeclaration(Scope *S, AccessSpecifier AS, 11691 SourceLocation UsingLoc, 11692 SourceLocation EnumLoc, 11693 const DeclSpec &DS) { 11694 switch (DS.getTypeSpecType()) { 11695 case DeclSpec::TST_error: 11696 // This will already have been diagnosed 11697 return nullptr; 11698 11699 case DeclSpec::TST_enum: 11700 break; 11701 11702 case DeclSpec::TST_typename: 11703 Diag(DS.getTypeSpecTypeLoc(), diag::err_using_enum_is_dependent); 11704 return nullptr; 11705 11706 default: 11707 llvm_unreachable("unexpected DeclSpec type"); 11708 } 11709 11710 // As with enum-decls, we ignore attributes for now. 11711 auto *Enum = cast<EnumDecl>(DS.getRepAsDecl()); 11712 if (auto *Def = Enum->getDefinition()) 11713 Enum = Def; 11714 11715 auto *UD = BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc, 11716 DS.getTypeSpecTypeNameLoc(), Enum); 11717 if (UD) 11718 PushOnScopeChains(UD, S, /*AddToContext*/ false); 11719 11720 return UD; 11721 } 11722 11723 /// Determine whether a using declaration considers the given 11724 /// declarations as "equivalent", e.g., if they are redeclarations of 11725 /// the same entity or are both typedefs of the same type. 11726 static bool 11727 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 11728 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 11729 return true; 11730 11731 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 11732 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 11733 return Context.hasSameType(TD1->getUnderlyingType(), 11734 TD2->getUnderlyingType()); 11735 11736 // Two using_if_exists using-declarations are equivalent if both are 11737 // unresolved. 11738 if (isa<UnresolvedUsingIfExistsDecl>(D1) && 11739 isa<UnresolvedUsingIfExistsDecl>(D2)) 11740 return true; 11741 11742 return false; 11743 } 11744 11745 11746 /// Determines whether to create a using shadow decl for a particular 11747 /// decl, given the set of decls existing prior to this using lookup. 11748 bool Sema::CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Orig, 11749 const LookupResult &Previous, 11750 UsingShadowDecl *&PrevShadow) { 11751 // Diagnose finding a decl which is not from a base class of the 11752 // current class. We do this now because there are cases where this 11753 // function will silently decide not to build a shadow decl, which 11754 // will pre-empt further diagnostics. 11755 // 11756 // We don't need to do this in C++11 because we do the check once on 11757 // the qualifier. 11758 // 11759 // FIXME: diagnose the following if we care enough: 11760 // struct A { int foo; }; 11761 // struct B : A { using A::foo; }; 11762 // template <class T> struct C : A {}; 11763 // template <class T> struct D : C<T> { using B::foo; } // <--- 11764 // This is invalid (during instantiation) in C++03 because B::foo 11765 // resolves to the using decl in B, which is not a base class of D<T>. 11766 // We can't diagnose it immediately because C<T> is an unknown 11767 // specialization. The UsingShadowDecl in D<T> then points directly 11768 // to A::foo, which will look well-formed when we instantiate. 11769 // The right solution is to not collapse the shadow-decl chain. 11770 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) 11771 if (auto *Using = dyn_cast<UsingDecl>(BUD)) { 11772 DeclContext *OrigDC = Orig->getDeclContext(); 11773 11774 // Handle enums and anonymous structs. 11775 if (isa<EnumDecl>(OrigDC)) 11776 OrigDC = OrigDC->getParent(); 11777 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 11778 while (OrigRec->isAnonymousStructOrUnion()) 11779 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 11780 11781 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 11782 if (OrigDC == CurContext) { 11783 Diag(Using->getLocation(), 11784 diag::err_using_decl_nested_name_specifier_is_current_class) 11785 << Using->getQualifierLoc().getSourceRange(); 11786 Diag(Orig->getLocation(), diag::note_using_decl_target); 11787 Using->setInvalidDecl(); 11788 return true; 11789 } 11790 11791 Diag(Using->getQualifierLoc().getBeginLoc(), 11792 diag::err_using_decl_nested_name_specifier_is_not_base_class) 11793 << Using->getQualifier() << cast<CXXRecordDecl>(CurContext) 11794 << Using->getQualifierLoc().getSourceRange(); 11795 Diag(Orig->getLocation(), diag::note_using_decl_target); 11796 Using->setInvalidDecl(); 11797 return true; 11798 } 11799 } 11800 11801 if (Previous.empty()) return false; 11802 11803 NamedDecl *Target = Orig; 11804 if (isa<UsingShadowDecl>(Target)) 11805 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 11806 11807 // If the target happens to be one of the previous declarations, we 11808 // don't have a conflict. 11809 // 11810 // FIXME: but we might be increasing its access, in which case we 11811 // should redeclare it. 11812 NamedDecl *NonTag = nullptr, *Tag = nullptr; 11813 bool FoundEquivalentDecl = false; 11814 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 11815 I != E; ++I) { 11816 NamedDecl *D = (*I)->getUnderlyingDecl(); 11817 // We can have UsingDecls in our Previous results because we use the same 11818 // LookupResult for checking whether the UsingDecl itself is a valid 11819 // redeclaration. 11820 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D) || isa<UsingEnumDecl>(D)) 11821 continue; 11822 11823 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 11824 // C++ [class.mem]p19: 11825 // If T is the name of a class, then [every named member other than 11826 // a non-static data member] shall have a name different from T 11827 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) && 11828 !isa<IndirectFieldDecl>(Target) && 11829 !isa<UnresolvedUsingValueDecl>(Target) && 11830 DiagnoseClassNameShadow( 11831 CurContext, 11832 DeclarationNameInfo(BUD->getDeclName(), BUD->getLocation()))) 11833 return true; 11834 } 11835 11836 if (IsEquivalentForUsingDecl(Context, D, Target)) { 11837 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 11838 PrevShadow = Shadow; 11839 FoundEquivalentDecl = true; 11840 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) { 11841 // We don't conflict with an existing using shadow decl of an equivalent 11842 // declaration, but we're not a redeclaration of it. 11843 FoundEquivalentDecl = true; 11844 } 11845 11846 if (isVisible(D)) 11847 (isa<TagDecl>(D) ? Tag : NonTag) = D; 11848 } 11849 11850 if (FoundEquivalentDecl) 11851 return false; 11852 11853 // Always emit a diagnostic for a mismatch between an unresolved 11854 // using_if_exists and a resolved using declaration in either direction. 11855 if (isa<UnresolvedUsingIfExistsDecl>(Target) != 11856 (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) { 11857 if (!NonTag && !Tag) 11858 return false; 11859 Diag(BUD->getLocation(), diag::err_using_decl_conflict); 11860 Diag(Target->getLocation(), diag::note_using_decl_target); 11861 Diag((NonTag ? NonTag : Tag)->getLocation(), 11862 diag::note_using_decl_conflict); 11863 BUD->setInvalidDecl(); 11864 return true; 11865 } 11866 11867 if (FunctionDecl *FD = Target->getAsFunction()) { 11868 NamedDecl *OldDecl = nullptr; 11869 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 11870 /*IsForUsingDecl*/ true)) { 11871 case Ovl_Overload: 11872 return false; 11873 11874 case Ovl_NonFunction: 11875 Diag(BUD->getLocation(), diag::err_using_decl_conflict); 11876 break; 11877 11878 // We found a decl with the exact signature. 11879 case Ovl_Match: 11880 // If we're in a record, we want to hide the target, so we 11881 // return true (without a diagnostic) to tell the caller not to 11882 // build a shadow decl. 11883 if (CurContext->isRecord()) 11884 return true; 11885 11886 // If we're not in a record, this is an error. 11887 Diag(BUD->getLocation(), diag::err_using_decl_conflict); 11888 break; 11889 } 11890 11891 Diag(Target->getLocation(), diag::note_using_decl_target); 11892 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 11893 BUD->setInvalidDecl(); 11894 return true; 11895 } 11896 11897 // Target is not a function. 11898 11899 if (isa<TagDecl>(Target)) { 11900 // No conflict between a tag and a non-tag. 11901 if (!Tag) return false; 11902 11903 Diag(BUD->getLocation(), diag::err_using_decl_conflict); 11904 Diag(Target->getLocation(), diag::note_using_decl_target); 11905 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 11906 BUD->setInvalidDecl(); 11907 return true; 11908 } 11909 11910 // No conflict between a tag and a non-tag. 11911 if (!NonTag) return false; 11912 11913 Diag(BUD->getLocation(), diag::err_using_decl_conflict); 11914 Diag(Target->getLocation(), diag::note_using_decl_target); 11915 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 11916 BUD->setInvalidDecl(); 11917 return true; 11918 } 11919 11920 /// Determine whether a direct base class is a virtual base class. 11921 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) { 11922 if (!Derived->getNumVBases()) 11923 return false; 11924 for (auto &B : Derived->bases()) 11925 if (B.getType()->getAsCXXRecordDecl() == Base) 11926 return B.isVirtual(); 11927 llvm_unreachable("not a direct base class"); 11928 } 11929 11930 /// Builds a shadow declaration corresponding to a 'using' declaration. 11931 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD, 11932 NamedDecl *Orig, 11933 UsingShadowDecl *PrevDecl) { 11934 // If we resolved to another shadow declaration, just coalesce them. 11935 NamedDecl *Target = Orig; 11936 if (isa<UsingShadowDecl>(Target)) { 11937 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 11938 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 11939 } 11940 11941 NamedDecl *NonTemplateTarget = Target; 11942 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target)) 11943 NonTemplateTarget = TargetTD->getTemplatedDecl(); 11944 11945 UsingShadowDecl *Shadow; 11946 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) { 11947 UsingDecl *Using = cast<UsingDecl>(BUD); 11948 bool IsVirtualBase = 11949 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext), 11950 Using->getQualifier()->getAsRecordDecl()); 11951 Shadow = ConstructorUsingShadowDecl::Create( 11952 Context, CurContext, Using->getLocation(), Using, Orig, IsVirtualBase); 11953 } else { 11954 Shadow = UsingShadowDecl::Create(Context, CurContext, BUD->getLocation(), 11955 Target->getDeclName(), BUD, Target); 11956 } 11957 BUD->addShadowDecl(Shadow); 11958 11959 Shadow->setAccess(BUD->getAccess()); 11960 if (Orig->isInvalidDecl() || BUD->isInvalidDecl()) 11961 Shadow->setInvalidDecl(); 11962 11963 Shadow->setPreviousDecl(PrevDecl); 11964 11965 if (S) 11966 PushOnScopeChains(Shadow, S); 11967 else 11968 CurContext->addDecl(Shadow); 11969 11970 11971 return Shadow; 11972 } 11973 11974 /// Hides a using shadow declaration. This is required by the current 11975 /// using-decl implementation when a resolvable using declaration in a 11976 /// class is followed by a declaration which would hide or override 11977 /// one or more of the using decl's targets; for example: 11978 /// 11979 /// struct Base { void foo(int); }; 11980 /// struct Derived : Base { 11981 /// using Base::foo; 11982 /// void foo(int); 11983 /// }; 11984 /// 11985 /// The governing language is C++03 [namespace.udecl]p12: 11986 /// 11987 /// When a using-declaration brings names from a base class into a 11988 /// derived class scope, member functions in the derived class 11989 /// override and/or hide member functions with the same name and 11990 /// parameter types in a base class (rather than conflicting). 11991 /// 11992 /// There are two ways to implement this: 11993 /// (1) optimistically create shadow decls when they're not hidden 11994 /// by existing declarations, or 11995 /// (2) don't create any shadow decls (or at least don't make them 11996 /// visible) until we've fully parsed/instantiated the class. 11997 /// The problem with (1) is that we might have to retroactively remove 11998 /// a shadow decl, which requires several O(n) operations because the 11999 /// decl structures are (very reasonably) not designed for removal. 12000 /// (2) avoids this but is very fiddly and phase-dependent. 12001 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 12002 if (Shadow->getDeclName().getNameKind() == 12003 DeclarationName::CXXConversionFunctionName) 12004 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 12005 12006 // Remove it from the DeclContext... 12007 Shadow->getDeclContext()->removeDecl(Shadow); 12008 12009 // ...and the scope, if applicable... 12010 if (S) { 12011 S->RemoveDecl(Shadow); 12012 IdResolver.RemoveDecl(Shadow); 12013 } 12014 12015 // ...and the using decl. 12016 Shadow->getIntroducer()->removeShadowDecl(Shadow); 12017 12018 // TODO: complain somehow if Shadow was used. It shouldn't 12019 // be possible for this to happen, because...? 12020 } 12021 12022 /// Find the base specifier for a base class with the given type. 12023 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 12024 QualType DesiredBase, 12025 bool &AnyDependentBases) { 12026 // Check whether the named type is a direct base class. 12027 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified() 12028 .getUnqualifiedType(); 12029 for (auto &Base : Derived->bases()) { 12030 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 12031 if (CanonicalDesiredBase == BaseType) 12032 return &Base; 12033 if (BaseType->isDependentType()) 12034 AnyDependentBases = true; 12035 } 12036 return nullptr; 12037 } 12038 12039 namespace { 12040 class UsingValidatorCCC final : public CorrectionCandidateCallback { 12041 public: 12042 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 12043 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 12044 : HasTypenameKeyword(HasTypenameKeyword), 12045 IsInstantiation(IsInstantiation), OldNNS(NNS), 12046 RequireMemberOf(RequireMemberOf) {} 12047 12048 bool ValidateCandidate(const TypoCorrection &Candidate) override { 12049 NamedDecl *ND = Candidate.getCorrectionDecl(); 12050 12051 // Keywords are not valid here. 12052 if (!ND || isa<NamespaceDecl>(ND)) 12053 return false; 12054 12055 // Completely unqualified names are invalid for a 'using' declaration. 12056 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 12057 return false; 12058 12059 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would 12060 // reject. 12061 12062 if (RequireMemberOf) { 12063 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 12064 if (FoundRecord && FoundRecord->isInjectedClassName()) { 12065 // No-one ever wants a using-declaration to name an injected-class-name 12066 // of a base class, unless they're declaring an inheriting constructor. 12067 ASTContext &Ctx = ND->getASTContext(); 12068 if (!Ctx.getLangOpts().CPlusPlus11) 12069 return false; 12070 QualType FoundType = Ctx.getRecordType(FoundRecord); 12071 12072 // Check that the injected-class-name is named as a member of its own 12073 // type; we don't want to suggest 'using Derived::Base;', since that 12074 // means something else. 12075 NestedNameSpecifier *Specifier = 12076 Candidate.WillReplaceSpecifier() 12077 ? Candidate.getCorrectionSpecifier() 12078 : OldNNS; 12079 if (!Specifier->getAsType() || 12080 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 12081 return false; 12082 12083 // Check that this inheriting constructor declaration actually names a 12084 // direct base class of the current class. 12085 bool AnyDependentBases = false; 12086 if (!findDirectBaseWithType(RequireMemberOf, 12087 Ctx.getRecordType(FoundRecord), 12088 AnyDependentBases) && 12089 !AnyDependentBases) 12090 return false; 12091 } else { 12092 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 12093 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 12094 return false; 12095 12096 // FIXME: Check that the base class member is accessible? 12097 } 12098 } else { 12099 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 12100 if (FoundRecord && FoundRecord->isInjectedClassName()) 12101 return false; 12102 } 12103 12104 if (isa<TypeDecl>(ND)) 12105 return HasTypenameKeyword || !IsInstantiation; 12106 12107 return !HasTypenameKeyword; 12108 } 12109 12110 std::unique_ptr<CorrectionCandidateCallback> clone() override { 12111 return std::make_unique<UsingValidatorCCC>(*this); 12112 } 12113 12114 private: 12115 bool HasTypenameKeyword; 12116 bool IsInstantiation; 12117 NestedNameSpecifier *OldNNS; 12118 CXXRecordDecl *RequireMemberOf; 12119 }; 12120 } // end anonymous namespace 12121 12122 /// Remove decls we can't actually see from a lookup being used to declare 12123 /// shadow using decls. 12124 /// 12125 /// \param S - The scope of the potential shadow decl 12126 /// \param Previous - The lookup of a potential shadow decl's name. 12127 void Sema::FilterUsingLookup(Scope *S, LookupResult &Previous) { 12128 // It is really dumb that we have to do this. 12129 LookupResult::Filter F = Previous.makeFilter(); 12130 while (F.hasNext()) { 12131 NamedDecl *D = F.next(); 12132 if (!isDeclInScope(D, CurContext, S)) 12133 F.erase(); 12134 // If we found a local extern declaration that's not ordinarily visible, 12135 // and this declaration is being added to a non-block scope, ignore it. 12136 // We're only checking for scope conflicts here, not also for violations 12137 // of the linkage rules. 12138 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 12139 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 12140 F.erase(); 12141 } 12142 F.done(); 12143 } 12144 12145 /// Builds a using declaration. 12146 /// 12147 /// \param IsInstantiation - Whether this call arises from an 12148 /// instantiation of an unresolved using declaration. We treat 12149 /// the lookup differently for these declarations. 12150 NamedDecl *Sema::BuildUsingDeclaration( 12151 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, 12152 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, 12153 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, 12154 const ParsedAttributesView &AttrList, bool IsInstantiation, 12155 bool IsUsingIfExists) { 12156 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 12157 SourceLocation IdentLoc = NameInfo.getLoc(); 12158 assert(IdentLoc.isValid() && "Invalid TargetName location."); 12159 12160 // FIXME: We ignore attributes for now. 12161 12162 // For an inheriting constructor declaration, the name of the using 12163 // declaration is the name of a constructor in this class, not in the 12164 // base class. 12165 DeclarationNameInfo UsingName = NameInfo; 12166 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName) 12167 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext)) 12168 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 12169 Context.getCanonicalType(Context.getRecordType(RD)))); 12170 12171 // Do the redeclaration lookup in the current scope. 12172 LookupResult Previous(*this, UsingName, LookupUsingDeclName, 12173 ForVisibleRedeclaration); 12174 Previous.setHideTags(false); 12175 if (S) { 12176 LookupName(Previous, S); 12177 12178 FilterUsingLookup(S, Previous); 12179 } else { 12180 assert(IsInstantiation && "no scope in non-instantiation"); 12181 if (CurContext->isRecord()) 12182 LookupQualifiedName(Previous, CurContext); 12183 else { 12184 // No redeclaration check is needed here; in non-member contexts we 12185 // diagnosed all possible conflicts with other using-declarations when 12186 // building the template: 12187 // 12188 // For a dependent non-type using declaration, the only valid case is 12189 // if we instantiate to a single enumerator. We check for conflicts 12190 // between shadow declarations we introduce, and we check in the template 12191 // definition for conflicts between a non-type using declaration and any 12192 // other declaration, which together covers all cases. 12193 // 12194 // A dependent typename using declaration will never successfully 12195 // instantiate, since it will always name a class member, so we reject 12196 // that in the template definition. 12197 } 12198 } 12199 12200 // Check for invalid redeclarations. 12201 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 12202 SS, IdentLoc, Previous)) 12203 return nullptr; 12204 12205 // 'using_if_exists' doesn't make sense on an inherited constructor. 12206 if (IsUsingIfExists && UsingName.getName().getNameKind() == 12207 DeclarationName::CXXConstructorName) { 12208 Diag(UsingLoc, diag::err_using_if_exists_on_ctor); 12209 return nullptr; 12210 } 12211 12212 DeclContext *LookupContext = computeDeclContext(SS); 12213 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 12214 if (!LookupContext || EllipsisLoc.isValid()) { 12215 NamedDecl *D; 12216 // Dependent scope, or an unexpanded pack 12217 if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, 12218 SS, NameInfo, IdentLoc)) 12219 return nullptr; 12220 12221 if (HasTypenameKeyword) { 12222 // FIXME: not all declaration name kinds are legal here 12223 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 12224 UsingLoc, TypenameLoc, 12225 QualifierLoc, 12226 IdentLoc, NameInfo.getName(), 12227 EllipsisLoc); 12228 } else { 12229 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 12230 QualifierLoc, NameInfo, EllipsisLoc); 12231 } 12232 D->setAccess(AS); 12233 CurContext->addDecl(D); 12234 ProcessDeclAttributeList(S, D, AttrList); 12235 return D; 12236 } 12237 12238 auto Build = [&](bool Invalid) { 12239 UsingDecl *UD = 12240 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 12241 UsingName, HasTypenameKeyword); 12242 UD->setAccess(AS); 12243 CurContext->addDecl(UD); 12244 ProcessDeclAttributeList(S, UD, AttrList); 12245 UD->setInvalidDecl(Invalid); 12246 return UD; 12247 }; 12248 auto BuildInvalid = [&]{ return Build(true); }; 12249 auto BuildValid = [&]{ return Build(false); }; 12250 12251 if (RequireCompleteDeclContext(SS, LookupContext)) 12252 return BuildInvalid(); 12253 12254 // Look up the target name. 12255 LookupResult R(*this, NameInfo, LookupOrdinaryName); 12256 12257 // Unlike most lookups, we don't always want to hide tag 12258 // declarations: tag names are visible through the using declaration 12259 // even if hidden by ordinary names, *except* in a dependent context 12260 // where they may be used by two-phase lookup. 12261 if (!IsInstantiation) 12262 R.setHideTags(false); 12263 12264 // For the purposes of this lookup, we have a base object type 12265 // equal to that of the current context. 12266 if (CurContext->isRecord()) { 12267 R.setBaseObjectType( 12268 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 12269 } 12270 12271 LookupQualifiedName(R, LookupContext); 12272 12273 // Validate the context, now we have a lookup 12274 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo, 12275 IdentLoc, &R)) 12276 return nullptr; 12277 12278 if (R.empty() && IsUsingIfExists) 12279 R.addDecl(UnresolvedUsingIfExistsDecl::Create(Context, CurContext, UsingLoc, 12280 UsingName.getName()), 12281 AS_public); 12282 12283 // Try to correct typos if possible. If constructor name lookup finds no 12284 // results, that means the named class has no explicit constructors, and we 12285 // suppressed declaring implicit ones (probably because it's dependent or 12286 // invalid). 12287 if (R.empty() && 12288 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { 12289 // HACK 2017-01-08: Work around an issue with libstdc++'s detection of 12290 // ::gets. Sometimes it believes that glibc provides a ::gets in cases where 12291 // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later. 12292 auto *II = NameInfo.getName().getAsIdentifierInfo(); 12293 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") && 12294 CurContext->isStdNamespace() && 12295 isa<TranslationUnitDecl>(LookupContext) && 12296 getSourceManager().isInSystemHeader(UsingLoc)) 12297 return nullptr; 12298 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 12299 dyn_cast<CXXRecordDecl>(CurContext)); 12300 if (TypoCorrection Corrected = 12301 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 12302 CTK_ErrorRecovery)) { 12303 // We reject candidates where DroppedSpecifier == true, hence the 12304 // literal '0' below. 12305 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 12306 << NameInfo.getName() << LookupContext << 0 12307 << SS.getRange()); 12308 12309 // If we picked a correction with no attached Decl we can't do anything 12310 // useful with it, bail out. 12311 NamedDecl *ND = Corrected.getCorrectionDecl(); 12312 if (!ND) 12313 return BuildInvalid(); 12314 12315 // If we corrected to an inheriting constructor, handle it as one. 12316 auto *RD = dyn_cast<CXXRecordDecl>(ND); 12317 if (RD && RD->isInjectedClassName()) { 12318 // The parent of the injected class name is the class itself. 12319 RD = cast<CXXRecordDecl>(RD->getParent()); 12320 12321 // Fix up the information we'll use to build the using declaration. 12322 if (Corrected.WillReplaceSpecifier()) { 12323 NestedNameSpecifierLocBuilder Builder; 12324 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 12325 QualifierLoc.getSourceRange()); 12326 QualifierLoc = Builder.getWithLocInContext(Context); 12327 } 12328 12329 // In this case, the name we introduce is the name of a derived class 12330 // constructor. 12331 auto *CurClass = cast<CXXRecordDecl>(CurContext); 12332 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 12333 Context.getCanonicalType(Context.getRecordType(CurClass)))); 12334 UsingName.setNamedTypeInfo(nullptr); 12335 for (auto *Ctor : LookupConstructors(RD)) 12336 R.addDecl(Ctor); 12337 R.resolveKind(); 12338 } else { 12339 // FIXME: Pick up all the declarations if we found an overloaded 12340 // function. 12341 UsingName.setName(ND->getDeclName()); 12342 R.addDecl(ND); 12343 } 12344 } else { 12345 Diag(IdentLoc, diag::err_no_member) 12346 << NameInfo.getName() << LookupContext << SS.getRange(); 12347 return BuildInvalid(); 12348 } 12349 } 12350 12351 if (R.isAmbiguous()) 12352 return BuildInvalid(); 12353 12354 if (HasTypenameKeyword) { 12355 // If we asked for a typename and got a non-type decl, error out. 12356 if (!R.getAsSingle<TypeDecl>() && 12357 !R.getAsSingle<UnresolvedUsingIfExistsDecl>()) { 12358 Diag(IdentLoc, diag::err_using_typename_non_type); 12359 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 12360 Diag((*I)->getUnderlyingDecl()->getLocation(), 12361 diag::note_using_decl_target); 12362 return BuildInvalid(); 12363 } 12364 } else { 12365 // If we asked for a non-typename and we got a type, error out, 12366 // but only if this is an instantiation of an unresolved using 12367 // decl. Otherwise just silently find the type name. 12368 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 12369 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 12370 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 12371 return BuildInvalid(); 12372 } 12373 } 12374 12375 // C++14 [namespace.udecl]p6: 12376 // A using-declaration shall not name a namespace. 12377 if (R.getAsSingle<NamespaceDecl>()) { 12378 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 12379 << SS.getRange(); 12380 return BuildInvalid(); 12381 } 12382 12383 UsingDecl *UD = BuildValid(); 12384 12385 // Some additional rules apply to inheriting constructors. 12386 if (UsingName.getName().getNameKind() == 12387 DeclarationName::CXXConstructorName) { 12388 // Suppress access diagnostics; the access check is instead performed at the 12389 // point of use for an inheriting constructor. 12390 R.suppressDiagnostics(); 12391 if (CheckInheritingConstructorUsingDecl(UD)) 12392 return UD; 12393 } 12394 12395 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 12396 UsingShadowDecl *PrevDecl = nullptr; 12397 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 12398 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 12399 } 12400 12401 return UD; 12402 } 12403 12404 NamedDecl *Sema::BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS, 12405 SourceLocation UsingLoc, 12406 SourceLocation EnumLoc, 12407 SourceLocation NameLoc, 12408 EnumDecl *ED) { 12409 bool Invalid = false; 12410 12411 if (CurContext->getRedeclContext()->isRecord()) { 12412 /// In class scope, check if this is a duplicate, for better a diagnostic. 12413 DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc); 12414 LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName, 12415 ForVisibleRedeclaration); 12416 12417 LookupName(Previous, S); 12418 12419 for (NamedDecl *D : Previous) 12420 if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D)) 12421 if (UED->getEnumDecl() == ED) { 12422 Diag(UsingLoc, diag::err_using_enum_decl_redeclaration) 12423 << SourceRange(EnumLoc, NameLoc); 12424 Diag(D->getLocation(), diag::note_using_enum_decl) << 1; 12425 Invalid = true; 12426 break; 12427 } 12428 } 12429 12430 if (RequireCompleteEnumDecl(ED, NameLoc)) 12431 Invalid = true; 12432 12433 UsingEnumDecl *UD = UsingEnumDecl::Create(Context, CurContext, UsingLoc, 12434 EnumLoc, NameLoc, ED); 12435 UD->setAccess(AS); 12436 CurContext->addDecl(UD); 12437 12438 if (Invalid) { 12439 UD->setInvalidDecl(); 12440 return UD; 12441 } 12442 12443 // Create the shadow decls for each enumerator 12444 for (EnumConstantDecl *EC : ED->enumerators()) { 12445 UsingShadowDecl *PrevDecl = nullptr; 12446 DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation()); 12447 LookupResult Previous(*this, DNI, LookupOrdinaryName, 12448 ForVisibleRedeclaration); 12449 LookupName(Previous, S); 12450 FilterUsingLookup(S, Previous); 12451 12452 if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl)) 12453 BuildUsingShadowDecl(S, UD, EC, PrevDecl); 12454 } 12455 12456 return UD; 12457 } 12458 12459 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom, 12460 ArrayRef<NamedDecl *> Expansions) { 12461 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || 12462 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || 12463 isa<UsingPackDecl>(InstantiatedFrom)); 12464 12465 auto *UPD = 12466 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions); 12467 UPD->setAccess(InstantiatedFrom->getAccess()); 12468 CurContext->addDecl(UPD); 12469 return UPD; 12470 } 12471 12472 /// Additional checks for a using declaration referring to a constructor name. 12473 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 12474 assert(!UD->hasTypename() && "expecting a constructor name"); 12475 12476 const Type *SourceType = UD->getQualifier()->getAsType(); 12477 assert(SourceType && 12478 "Using decl naming constructor doesn't have type in scope spec."); 12479 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 12480 12481 // Check whether the named type is a direct base class. 12482 bool AnyDependentBases = false; 12483 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 12484 AnyDependentBases); 12485 if (!Base && !AnyDependentBases) { 12486 Diag(UD->getUsingLoc(), 12487 diag::err_using_decl_constructor_not_in_direct_base) 12488 << UD->getNameInfo().getSourceRange() 12489 << QualType(SourceType, 0) << TargetClass; 12490 UD->setInvalidDecl(); 12491 return true; 12492 } 12493 12494 if (Base) 12495 Base->setInheritConstructors(); 12496 12497 return false; 12498 } 12499 12500 /// Checks that the given using declaration is not an invalid 12501 /// redeclaration. Note that this is checking only for the using decl 12502 /// itself, not for any ill-formedness among the UsingShadowDecls. 12503 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 12504 bool HasTypenameKeyword, 12505 const CXXScopeSpec &SS, 12506 SourceLocation NameLoc, 12507 const LookupResult &Prev) { 12508 NestedNameSpecifier *Qual = SS.getScopeRep(); 12509 12510 // C++03 [namespace.udecl]p8: 12511 // C++0x [namespace.udecl]p10: 12512 // A using-declaration is a declaration and can therefore be used 12513 // repeatedly where (and only where) multiple declarations are 12514 // allowed. 12515 // 12516 // That's in non-member contexts. 12517 if (!CurContext->getRedeclContext()->isRecord()) { 12518 // A dependent qualifier outside a class can only ever resolve to an 12519 // enumeration type. Therefore it conflicts with any other non-type 12520 // declaration in the same scope. 12521 // FIXME: How should we check for dependent type-type conflicts at block 12522 // scope? 12523 if (Qual->isDependent() && !HasTypenameKeyword) { 12524 for (auto *D : Prev) { 12525 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) { 12526 bool OldCouldBeEnumerator = 12527 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D); 12528 Diag(NameLoc, 12529 OldCouldBeEnumerator ? diag::err_redefinition 12530 : diag::err_redefinition_different_kind) 12531 << Prev.getLookupName(); 12532 Diag(D->getLocation(), diag::note_previous_definition); 12533 return true; 12534 } 12535 } 12536 } 12537 return false; 12538 } 12539 12540 const NestedNameSpecifier *CNNS = 12541 Context.getCanonicalNestedNameSpecifier(Qual); 12542 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 12543 NamedDecl *D = *I; 12544 12545 bool DTypename; 12546 NestedNameSpecifier *DQual; 12547 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 12548 DTypename = UD->hasTypename(); 12549 DQual = UD->getQualifier(); 12550 } else if (UnresolvedUsingValueDecl *UD 12551 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 12552 DTypename = false; 12553 DQual = UD->getQualifier(); 12554 } else if (UnresolvedUsingTypenameDecl *UD 12555 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 12556 DTypename = true; 12557 DQual = UD->getQualifier(); 12558 } else continue; 12559 12560 // using decls differ if one says 'typename' and the other doesn't. 12561 // FIXME: non-dependent using decls? 12562 if (HasTypenameKeyword != DTypename) continue; 12563 12564 // using decls differ if they name different scopes (but note that 12565 // template instantiation can cause this check to trigger when it 12566 // didn't before instantiation). 12567 if (CNNS != Context.getCanonicalNestedNameSpecifier(DQual)) 12568 continue; 12569 12570 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 12571 Diag(D->getLocation(), diag::note_using_decl) << 1; 12572 return true; 12573 } 12574 12575 return false; 12576 } 12577 12578 /// Checks that the given nested-name qualifier used in a using decl 12579 /// in the current context is appropriately related to the current 12580 /// scope. If an error is found, diagnoses it and returns true. 12581 /// R is nullptr, if the caller has not (yet) done a lookup, otherwise it's the 12582 /// result of that lookup. UD is likewise nullptr, except when we have an 12583 /// already-populated UsingDecl whose shadow decls contain the same information 12584 /// (i.e. we're instantiating a UsingDecl with non-dependent scope). 12585 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename, 12586 const CXXScopeSpec &SS, 12587 const DeclarationNameInfo &NameInfo, 12588 SourceLocation NameLoc, 12589 const LookupResult *R, const UsingDecl *UD) { 12590 DeclContext *NamedContext = computeDeclContext(SS); 12591 assert(bool(NamedContext) == (R || UD) && !(R && UD) && 12592 "resolvable context must have exactly one set of decls"); 12593 12594 // C++ 20 permits using an enumerator that does not have a class-hierarchy 12595 // relationship. 12596 bool Cxx20Enumerator = false; 12597 if (NamedContext) { 12598 EnumConstantDecl *EC = nullptr; 12599 if (R) 12600 EC = R->getAsSingle<EnumConstantDecl>(); 12601 else if (UD && UD->shadow_size() == 1) 12602 EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl()); 12603 if (EC) 12604 Cxx20Enumerator = getLangOpts().CPlusPlus20; 12605 12606 if (auto *ED = dyn_cast<EnumDecl>(NamedContext)) { 12607 // C++14 [namespace.udecl]p7: 12608 // A using-declaration shall not name a scoped enumerator. 12609 // C++20 p1099 permits enumerators. 12610 if (EC && R && ED->isScoped()) 12611 Diag(SS.getBeginLoc(), 12612 getLangOpts().CPlusPlus20 12613 ? diag::warn_cxx17_compat_using_decl_scoped_enumerator 12614 : diag::ext_using_decl_scoped_enumerator) 12615 << SS.getRange(); 12616 12617 // We want to consider the scope of the enumerator 12618 NamedContext = ED->getDeclContext(); 12619 } 12620 } 12621 12622 if (!CurContext->isRecord()) { 12623 // C++03 [namespace.udecl]p3: 12624 // C++0x [namespace.udecl]p8: 12625 // A using-declaration for a class member shall be a member-declaration. 12626 // C++20 [namespace.udecl]p7 12627 // ... other than an enumerator ... 12628 12629 // If we weren't able to compute a valid scope, it might validly be a 12630 // dependent class or enumeration scope. If we have a 'typename' keyword, 12631 // the scope must resolve to a class type. 12632 if (NamedContext ? !NamedContext->getRedeclContext()->isRecord() 12633 : !HasTypename) 12634 return false; // OK 12635 12636 Diag(NameLoc, 12637 Cxx20Enumerator 12638 ? diag::warn_cxx17_compat_using_decl_class_member_enumerator 12639 : diag::err_using_decl_can_not_refer_to_class_member) 12640 << SS.getRange(); 12641 12642 if (Cxx20Enumerator) 12643 return false; // OK 12644 12645 auto *RD = NamedContext 12646 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext()) 12647 : nullptr; 12648 if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) { 12649 // See if there's a helpful fixit 12650 12651 if (!R) { 12652 // We will have already diagnosed the problem on the template 12653 // definition, Maybe we should do so again? 12654 } else if (R->getAsSingle<TypeDecl>()) { 12655 if (getLangOpts().CPlusPlus11) { 12656 // Convert 'using X::Y;' to 'using Y = X::Y;'. 12657 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 12658 << 0 // alias declaration 12659 << FixItHint::CreateInsertion(SS.getBeginLoc(), 12660 NameInfo.getName().getAsString() + 12661 " = "); 12662 } else { 12663 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 12664 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc()); 12665 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 12666 << 1 // typedef declaration 12667 << FixItHint::CreateReplacement(UsingLoc, "typedef") 12668 << FixItHint::CreateInsertion( 12669 InsertLoc, " " + NameInfo.getName().getAsString()); 12670 } 12671 } else if (R->getAsSingle<VarDecl>()) { 12672 // Don't provide a fixit outside C++11 mode; we don't want to suggest 12673 // repeating the type of the static data member here. 12674 FixItHint FixIt; 12675 if (getLangOpts().CPlusPlus11) { 12676 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 12677 FixIt = FixItHint::CreateReplacement( 12678 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 12679 } 12680 12681 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 12682 << 2 // reference declaration 12683 << FixIt; 12684 } else if (R->getAsSingle<EnumConstantDecl>()) { 12685 // Don't provide a fixit outside C++11 mode; we don't want to suggest 12686 // repeating the type of the enumeration here, and we can't do so if 12687 // the type is anonymous. 12688 FixItHint FixIt; 12689 if (getLangOpts().CPlusPlus11) { 12690 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 12691 FixIt = FixItHint::CreateReplacement( 12692 UsingLoc, 12693 "constexpr auto " + NameInfo.getName().getAsString() + " = "); 12694 } 12695 12696 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 12697 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable 12698 << FixIt; 12699 } 12700 } 12701 12702 return true; // Fail 12703 } 12704 12705 // If the named context is dependent, we can't decide much. 12706 if (!NamedContext) { 12707 // FIXME: in C++0x, we can diagnose if we can prove that the 12708 // nested-name-specifier does not refer to a base class, which is 12709 // still possible in some cases. 12710 12711 // Otherwise we have to conservatively report that things might be 12712 // okay. 12713 return false; 12714 } 12715 12716 // The current scope is a record. 12717 if (!NamedContext->isRecord()) { 12718 // Ideally this would point at the last name in the specifier, 12719 // but we don't have that level of source info. 12720 Diag(SS.getBeginLoc(), 12721 Cxx20Enumerator 12722 ? diag::warn_cxx17_compat_using_decl_non_member_enumerator 12723 : diag::err_using_decl_nested_name_specifier_is_not_class) 12724 << SS.getScopeRep() << SS.getRange(); 12725 12726 if (Cxx20Enumerator) 12727 return false; // OK 12728 12729 return true; 12730 } 12731 12732 if (!NamedContext->isDependentContext() && 12733 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 12734 return true; 12735 12736 if (getLangOpts().CPlusPlus11) { 12737 // C++11 [namespace.udecl]p3: 12738 // In a using-declaration used as a member-declaration, the 12739 // nested-name-specifier shall name a base class of the class 12740 // being defined. 12741 12742 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 12743 cast<CXXRecordDecl>(NamedContext))) { 12744 12745 if (Cxx20Enumerator) { 12746 Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator) 12747 << SS.getRange(); 12748 return false; 12749 } 12750 12751 if (CurContext == NamedContext) { 12752 Diag(SS.getBeginLoc(), 12753 diag::err_using_decl_nested_name_specifier_is_current_class) 12754 << SS.getRange(); 12755 return !getLangOpts().CPlusPlus20; 12756 } 12757 12758 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) { 12759 Diag(SS.getBeginLoc(), 12760 diag::err_using_decl_nested_name_specifier_is_not_base_class) 12761 << SS.getScopeRep() << cast<CXXRecordDecl>(CurContext) 12762 << SS.getRange(); 12763 } 12764 return true; 12765 } 12766 12767 return false; 12768 } 12769 12770 // C++03 [namespace.udecl]p4: 12771 // A using-declaration used as a member-declaration shall refer 12772 // to a member of a base class of the class being defined [etc.]. 12773 12774 // Salient point: SS doesn't have to name a base class as long as 12775 // lookup only finds members from base classes. Therefore we can 12776 // diagnose here only if we can prove that that can't happen, 12777 // i.e. if the class hierarchies provably don't intersect. 12778 12779 // TODO: it would be nice if "definitely valid" results were cached 12780 // in the UsingDecl and UsingShadowDecl so that these checks didn't 12781 // need to be repeated. 12782 12783 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases; 12784 auto Collect = [&Bases](const CXXRecordDecl *Base) { 12785 Bases.insert(Base); 12786 return true; 12787 }; 12788 12789 // Collect all bases. Return false if we find a dependent base. 12790 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect)) 12791 return false; 12792 12793 // Returns true if the base is dependent or is one of the accumulated base 12794 // classes. 12795 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) { 12796 return !Bases.count(Base); 12797 }; 12798 12799 // Return false if the class has a dependent base or if it or one 12800 // of its bases is present in the base set of the current context. 12801 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) || 12802 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase)) 12803 return false; 12804 12805 Diag(SS.getRange().getBegin(), 12806 diag::err_using_decl_nested_name_specifier_is_not_base_class) 12807 << SS.getScopeRep() 12808 << cast<CXXRecordDecl>(CurContext) 12809 << SS.getRange(); 12810 12811 return true; 12812 } 12813 12814 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS, 12815 MultiTemplateParamsArg TemplateParamLists, 12816 SourceLocation UsingLoc, UnqualifiedId &Name, 12817 const ParsedAttributesView &AttrList, 12818 TypeResult Type, Decl *DeclFromDeclSpec) { 12819 // Skip up to the relevant declaration scope. 12820 while (S->isTemplateParamScope()) 12821 S = S->getParent(); 12822 assert((S->getFlags() & Scope::DeclScope) && 12823 "got alias-declaration outside of declaration scope"); 12824 12825 if (Type.isInvalid()) 12826 return nullptr; 12827 12828 bool Invalid = false; 12829 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 12830 TypeSourceInfo *TInfo = nullptr; 12831 GetTypeFromParser(Type.get(), &TInfo); 12832 12833 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 12834 return nullptr; 12835 12836 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 12837 UPPC_DeclarationType)) { 12838 Invalid = true; 12839 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 12840 TInfo->getTypeLoc().getBeginLoc()); 12841 } 12842 12843 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 12844 TemplateParamLists.size() 12845 ? forRedeclarationInCurContext() 12846 : ForVisibleRedeclaration); 12847 LookupName(Previous, S); 12848 12849 // Warn about shadowing the name of a template parameter. 12850 if (Previous.isSingleResult() && 12851 Previous.getFoundDecl()->isTemplateParameter()) { 12852 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 12853 Previous.clear(); 12854 } 12855 12856 assert(Name.Kind == UnqualifiedIdKind::IK_Identifier && 12857 "name in alias declaration must be an identifier"); 12858 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 12859 Name.StartLocation, 12860 Name.Identifier, TInfo); 12861 12862 NewTD->setAccess(AS); 12863 12864 if (Invalid) 12865 NewTD->setInvalidDecl(); 12866 12867 ProcessDeclAttributeList(S, NewTD, AttrList); 12868 AddPragmaAttributes(S, NewTD); 12869 12870 CheckTypedefForVariablyModifiedType(S, NewTD); 12871 Invalid |= NewTD->isInvalidDecl(); 12872 12873 bool Redeclaration = false; 12874 12875 NamedDecl *NewND; 12876 if (TemplateParamLists.size()) { 12877 TypeAliasTemplateDecl *OldDecl = nullptr; 12878 TemplateParameterList *OldTemplateParams = nullptr; 12879 12880 if (TemplateParamLists.size() != 1) { 12881 Diag(UsingLoc, diag::err_alias_template_extra_headers) 12882 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 12883 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 12884 } 12885 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 12886 12887 // Check that we can declare a template here. 12888 if (CheckTemplateDeclScope(S, TemplateParams)) 12889 return nullptr; 12890 12891 // Only consider previous declarations in the same scope. 12892 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 12893 /*ExplicitInstantiationOrSpecialization*/false); 12894 if (!Previous.empty()) { 12895 Redeclaration = true; 12896 12897 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 12898 if (!OldDecl && !Invalid) { 12899 Diag(UsingLoc, diag::err_redefinition_different_kind) 12900 << Name.Identifier; 12901 12902 NamedDecl *OldD = Previous.getRepresentativeDecl(); 12903 if (OldD->getLocation().isValid()) 12904 Diag(OldD->getLocation(), diag::note_previous_definition); 12905 12906 Invalid = true; 12907 } 12908 12909 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 12910 if (TemplateParameterListsAreEqual(TemplateParams, 12911 OldDecl->getTemplateParameters(), 12912 /*Complain=*/true, 12913 TPL_TemplateMatch)) 12914 OldTemplateParams = 12915 OldDecl->getMostRecentDecl()->getTemplateParameters(); 12916 else 12917 Invalid = true; 12918 12919 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 12920 if (!Invalid && 12921 !Context.hasSameType(OldTD->getUnderlyingType(), 12922 NewTD->getUnderlyingType())) { 12923 // FIXME: The C++0x standard does not clearly say this is ill-formed, 12924 // but we can't reasonably accept it. 12925 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 12926 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 12927 if (OldTD->getLocation().isValid()) 12928 Diag(OldTD->getLocation(), diag::note_previous_definition); 12929 Invalid = true; 12930 } 12931 } 12932 } 12933 12934 // Merge any previous default template arguments into our parameters, 12935 // and check the parameter list. 12936 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 12937 TPC_TypeAliasTemplate)) 12938 return nullptr; 12939 12940 TypeAliasTemplateDecl *NewDecl = 12941 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 12942 Name.Identifier, TemplateParams, 12943 NewTD); 12944 NewTD->setDescribedAliasTemplate(NewDecl); 12945 12946 NewDecl->setAccess(AS); 12947 12948 if (Invalid) 12949 NewDecl->setInvalidDecl(); 12950 else if (OldDecl) { 12951 NewDecl->setPreviousDecl(OldDecl); 12952 CheckRedeclarationModuleOwnership(NewDecl, OldDecl); 12953 } 12954 12955 NewND = NewDecl; 12956 } else { 12957 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { 12958 setTagNameForLinkagePurposes(TD, NewTD); 12959 handleTagNumbering(TD, S); 12960 } 12961 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 12962 NewND = NewTD; 12963 } 12964 12965 PushOnScopeChains(NewND, S); 12966 ActOnDocumentableDecl(NewND); 12967 return NewND; 12968 } 12969 12970 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 12971 SourceLocation AliasLoc, 12972 IdentifierInfo *Alias, CXXScopeSpec &SS, 12973 SourceLocation IdentLoc, 12974 IdentifierInfo *Ident) { 12975 12976 // Lookup the namespace name. 12977 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 12978 LookupParsedName(R, S, &SS); 12979 12980 if (R.isAmbiguous()) 12981 return nullptr; 12982 12983 if (R.empty()) { 12984 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 12985 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 12986 return nullptr; 12987 } 12988 } 12989 assert(!R.isAmbiguous() && !R.empty()); 12990 NamedDecl *ND = R.getRepresentativeDecl(); 12991 12992 // Check if we have a previous declaration with the same name. 12993 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName, 12994 ForVisibleRedeclaration); 12995 LookupName(PrevR, S); 12996 12997 // Check we're not shadowing a template parameter. 12998 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) { 12999 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl()); 13000 PrevR.clear(); 13001 } 13002 13003 // Filter out any other lookup result from an enclosing scope. 13004 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false, 13005 /*AllowInlineNamespace*/false); 13006 13007 // Find the previous declaration and check that we can redeclare it. 13008 NamespaceAliasDecl *Prev = nullptr; 13009 if (PrevR.isSingleResult()) { 13010 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl(); 13011 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 13012 // We already have an alias with the same name that points to the same 13013 // namespace; check that it matches. 13014 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) { 13015 Prev = AD; 13016 } else if (isVisible(PrevDecl)) { 13017 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 13018 << Alias; 13019 Diag(AD->getLocation(), diag::note_previous_namespace_alias) 13020 << AD->getNamespace(); 13021 return nullptr; 13022 } 13023 } else if (isVisible(PrevDecl)) { 13024 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl()) 13025 ? diag::err_redefinition 13026 : diag::err_redefinition_different_kind; 13027 Diag(AliasLoc, DiagID) << Alias; 13028 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 13029 return nullptr; 13030 } 13031 } 13032 13033 // The use of a nested name specifier may trigger deprecation warnings. 13034 DiagnoseUseOfDecl(ND, IdentLoc); 13035 13036 NamespaceAliasDecl *AliasDecl = 13037 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 13038 Alias, SS.getWithLocInContext(Context), 13039 IdentLoc, ND); 13040 if (Prev) 13041 AliasDecl->setPreviousDecl(Prev); 13042 13043 PushOnScopeChains(AliasDecl, S); 13044 return AliasDecl; 13045 } 13046 13047 namespace { 13048 struct SpecialMemberExceptionSpecInfo 13049 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> { 13050 SourceLocation Loc; 13051 Sema::ImplicitExceptionSpecification ExceptSpec; 13052 13053 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD, 13054 Sema::CXXSpecialMember CSM, 13055 Sema::InheritedConstructorInfo *ICI, 13056 SourceLocation Loc) 13057 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {} 13058 13059 bool visitBase(CXXBaseSpecifier *Base); 13060 bool visitField(FieldDecl *FD); 13061 13062 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 13063 unsigned Quals); 13064 13065 void visitSubobjectCall(Subobject Subobj, 13066 Sema::SpecialMemberOverloadResult SMOR); 13067 }; 13068 } 13069 13070 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) { 13071 auto *RT = Base->getType()->getAs<RecordType>(); 13072 if (!RT) 13073 return false; 13074 13075 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl()); 13076 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 13077 if (auto *BaseCtor = SMOR.getMethod()) { 13078 visitSubobjectCall(Base, BaseCtor); 13079 return false; 13080 } 13081 13082 visitClassSubobject(BaseClass, Base, 0); 13083 return false; 13084 } 13085 13086 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) { 13087 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) { 13088 Expr *E = FD->getInClassInitializer(); 13089 if (!E) 13090 // FIXME: It's a little wasteful to build and throw away a 13091 // CXXDefaultInitExpr here. 13092 // FIXME: We should have a single context note pointing at Loc, and 13093 // this location should be MD->getLocation() instead, since that's 13094 // the location where we actually use the default init expression. 13095 E = S.BuildCXXDefaultInitExpr(Loc, FD).get(); 13096 if (E) 13097 ExceptSpec.CalledExpr(E); 13098 } else if (auto *RT = S.Context.getBaseElementType(FD->getType()) 13099 ->getAs<RecordType>()) { 13100 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD, 13101 FD->getType().getCVRQualifiers()); 13102 } 13103 return false; 13104 } 13105 13106 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class, 13107 Subobject Subobj, 13108 unsigned Quals) { 13109 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 13110 bool IsMutable = Field && Field->isMutable(); 13111 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable)); 13112 } 13113 13114 void SpecialMemberExceptionSpecInfo::visitSubobjectCall( 13115 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) { 13116 // Note, if lookup fails, it doesn't matter what exception specification we 13117 // choose because the special member will be deleted. 13118 if (CXXMethodDecl *MD = SMOR.getMethod()) 13119 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD); 13120 } 13121 13122 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) { 13123 llvm::APSInt Result; 13124 ExprResult Converted = CheckConvertedConstantExpression( 13125 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool); 13126 ExplicitSpec.setExpr(Converted.get()); 13127 if (Converted.isUsable() && !Converted.get()->isValueDependent()) { 13128 ExplicitSpec.setKind(Result.getBoolValue() 13129 ? ExplicitSpecKind::ResolvedTrue 13130 : ExplicitSpecKind::ResolvedFalse); 13131 return true; 13132 } 13133 ExplicitSpec.setKind(ExplicitSpecKind::Unresolved); 13134 return false; 13135 } 13136 13137 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) { 13138 ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved); 13139 if (!ExplicitExpr->isTypeDependent()) 13140 tryResolveExplicitSpecifier(ES); 13141 return ES; 13142 } 13143 13144 static Sema::ImplicitExceptionSpecification 13145 ComputeDefaultedSpecialMemberExceptionSpec( 13146 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 13147 Sema::InheritedConstructorInfo *ICI) { 13148 ComputingExceptionSpec CES(S, MD, Loc); 13149 13150 CXXRecordDecl *ClassDecl = MD->getParent(); 13151 13152 // C++ [except.spec]p14: 13153 // An implicitly declared special member function (Clause 12) shall have an 13154 // exception-specification. [...] 13155 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation()); 13156 if (ClassDecl->isInvalidDecl()) 13157 return Info.ExceptSpec; 13158 13159 // FIXME: If this diagnostic fires, we're probably missing a check for 13160 // attempting to resolve an exception specification before it's known 13161 // at a higher level. 13162 if (S.RequireCompleteType(MD->getLocation(), 13163 S.Context.getRecordType(ClassDecl), 13164 diag::err_exception_spec_incomplete_type)) 13165 return Info.ExceptSpec; 13166 13167 // C++1z [except.spec]p7: 13168 // [Look for exceptions thrown by] a constructor selected [...] to 13169 // initialize a potentially constructed subobject, 13170 // C++1z [except.spec]p8: 13171 // The exception specification for an implicitly-declared destructor, or a 13172 // destructor without a noexcept-specifier, is potentially-throwing if and 13173 // only if any of the destructors for any of its potentially constructed 13174 // subojects is potentially throwing. 13175 // FIXME: We respect the first rule but ignore the "potentially constructed" 13176 // in the second rule to resolve a core issue (no number yet) that would have 13177 // us reject: 13178 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; }; 13179 // struct B : A {}; 13180 // struct C : B { void f(); }; 13181 // ... due to giving B::~B() a non-throwing exception specification. 13182 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases 13183 : Info.VisitAllBases); 13184 13185 return Info.ExceptSpec; 13186 } 13187 13188 namespace { 13189 /// RAII object to register a special member as being currently declared. 13190 struct DeclaringSpecialMember { 13191 Sema &S; 13192 Sema::SpecialMemberDecl D; 13193 Sema::ContextRAII SavedContext; 13194 bool WasAlreadyBeingDeclared; 13195 13196 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 13197 : S(S), D(RD, CSM), SavedContext(S, RD) { 13198 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 13199 if (WasAlreadyBeingDeclared) 13200 // This almost never happens, but if it does, ensure that our cache 13201 // doesn't contain a stale result. 13202 S.SpecialMemberCache.clear(); 13203 else { 13204 // Register a note to be produced if we encounter an error while 13205 // declaring the special member. 13206 Sema::CodeSynthesisContext Ctx; 13207 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember; 13208 // FIXME: We don't have a location to use here. Using the class's 13209 // location maintains the fiction that we declare all special members 13210 // with the class, but (1) it's not clear that lying about that helps our 13211 // users understand what's going on, and (2) there may be outer contexts 13212 // on the stack (some of which are relevant) and printing them exposes 13213 // our lies. 13214 Ctx.PointOfInstantiation = RD->getLocation(); 13215 Ctx.Entity = RD; 13216 Ctx.SpecialMember = CSM; 13217 S.pushCodeSynthesisContext(Ctx); 13218 } 13219 } 13220 ~DeclaringSpecialMember() { 13221 if (!WasAlreadyBeingDeclared) { 13222 S.SpecialMembersBeingDeclared.erase(D); 13223 S.popCodeSynthesisContext(); 13224 } 13225 } 13226 13227 /// Are we already trying to declare this special member? 13228 bool isAlreadyBeingDeclared() const { 13229 return WasAlreadyBeingDeclared; 13230 } 13231 }; 13232 } 13233 13234 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) { 13235 // Look up any existing declarations, but don't trigger declaration of all 13236 // implicit special members with this name. 13237 DeclarationName Name = FD->getDeclName(); 13238 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName, 13239 ForExternalRedeclaration); 13240 for (auto *D : FD->getParent()->lookup(Name)) 13241 if (auto *Acceptable = R.getAcceptableDecl(D)) 13242 R.addDecl(Acceptable); 13243 R.resolveKind(); 13244 R.suppressDiagnostics(); 13245 13246 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false); 13247 } 13248 13249 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem, 13250 QualType ResultTy, 13251 ArrayRef<QualType> Args) { 13252 // Build an exception specification pointing back at this constructor. 13253 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem); 13254 13255 LangAS AS = getDefaultCXXMethodAddrSpace(); 13256 if (AS != LangAS::Default) { 13257 EPI.TypeQuals.addAddressSpace(AS); 13258 } 13259 13260 auto QT = Context.getFunctionType(ResultTy, Args, EPI); 13261 SpecialMem->setType(QT); 13262 13263 // During template instantiation of implicit special member functions we need 13264 // a reliable TypeSourceInfo for the function prototype in order to allow 13265 // functions to be substituted. 13266 if (inTemplateInstantiation() && 13267 cast<CXXRecordDecl>(SpecialMem->getParent())->isLambda()) { 13268 TypeSourceInfo *TSI = 13269 Context.getTrivialTypeSourceInfo(SpecialMem->getType()); 13270 SpecialMem->setTypeSourceInfo(TSI); 13271 } 13272 } 13273 13274 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 13275 CXXRecordDecl *ClassDecl) { 13276 // C++ [class.ctor]p5: 13277 // A default constructor for a class X is a constructor of class X 13278 // that can be called without an argument. If there is no 13279 // user-declared constructor for class X, a default constructor is 13280 // implicitly declared. An implicitly-declared default constructor 13281 // is an inline public member of its class. 13282 assert(ClassDecl->needsImplicitDefaultConstructor() && 13283 "Should not build implicit default constructor!"); 13284 13285 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 13286 if (DSM.isAlreadyBeingDeclared()) 13287 return nullptr; 13288 13289 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 13290 CXXDefaultConstructor, 13291 false); 13292 13293 // Create the actual constructor declaration. 13294 CanQualType ClassType 13295 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 13296 SourceLocation ClassLoc = ClassDecl->getLocation(); 13297 DeclarationName Name 13298 = Context.DeclarationNames.getCXXConstructorName(ClassType); 13299 DeclarationNameInfo NameInfo(Name, ClassLoc); 13300 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 13301 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(), 13302 /*TInfo=*/nullptr, ExplicitSpecifier(), 13303 getCurFPFeatures().isFPConstrained(), 13304 /*isInline=*/true, /*isImplicitlyDeclared=*/true, 13305 Constexpr ? ConstexprSpecKind::Constexpr 13306 : ConstexprSpecKind::Unspecified); 13307 DefaultCon->setAccess(AS_public); 13308 DefaultCon->setDefaulted(); 13309 13310 if (getLangOpts().CUDA) { 13311 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 13312 DefaultCon, 13313 /* ConstRHS */ false, 13314 /* Diagnose */ false); 13315 } 13316 13317 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None); 13318 13319 // We don't need to use SpecialMemberIsTrivial here; triviality for default 13320 // constructors is easy to compute. 13321 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 13322 13323 // Note that we have declared this constructor. 13324 ++getASTContext().NumImplicitDefaultConstructorsDeclared; 13325 13326 Scope *S = getScopeForContext(ClassDecl); 13327 CheckImplicitSpecialMemberDeclaration(S, DefaultCon); 13328 13329 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 13330 SetDeclDeleted(DefaultCon, ClassLoc); 13331 13332 if (S) 13333 PushOnScopeChains(DefaultCon, S, false); 13334 ClassDecl->addDecl(DefaultCon); 13335 13336 return DefaultCon; 13337 } 13338 13339 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 13340 CXXConstructorDecl *Constructor) { 13341 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 13342 !Constructor->doesThisDeclarationHaveABody() && 13343 !Constructor->isDeleted()) && 13344 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 13345 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 13346 return; 13347 13348 CXXRecordDecl *ClassDecl = Constructor->getParent(); 13349 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 13350 13351 SynthesizedFunctionScope Scope(*this, Constructor); 13352 13353 // The exception specification is needed because we are defining the 13354 // function. 13355 ResolveExceptionSpec(CurrentLocation, 13356 Constructor->getType()->castAs<FunctionProtoType>()); 13357 MarkVTableUsed(CurrentLocation, ClassDecl); 13358 13359 // Add a context note for diagnostics produced after this point. 13360 Scope.addContextNote(CurrentLocation); 13361 13362 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) { 13363 Constructor->setInvalidDecl(); 13364 return; 13365 } 13366 13367 SourceLocation Loc = Constructor->getEndLoc().isValid() 13368 ? Constructor->getEndLoc() 13369 : Constructor->getLocation(); 13370 Constructor->setBody(new (Context) CompoundStmt(Loc)); 13371 Constructor->markUsed(Context); 13372 13373 if (ASTMutationListener *L = getASTMutationListener()) { 13374 L->CompletedImplicitDefinition(Constructor); 13375 } 13376 13377 DiagnoseUninitializedFields(*this, Constructor); 13378 } 13379 13380 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 13381 // Perform any delayed checks on exception specifications. 13382 CheckDelayedMemberExceptionSpecs(); 13383 } 13384 13385 /// Find or create the fake constructor we synthesize to model constructing an 13386 /// object of a derived class via a constructor of a base class. 13387 CXXConstructorDecl * 13388 Sema::findInheritingConstructor(SourceLocation Loc, 13389 CXXConstructorDecl *BaseCtor, 13390 ConstructorUsingShadowDecl *Shadow) { 13391 CXXRecordDecl *Derived = Shadow->getParent(); 13392 SourceLocation UsingLoc = Shadow->getLocation(); 13393 13394 // FIXME: Add a new kind of DeclarationName for an inherited constructor. 13395 // For now we use the name of the base class constructor as a member of the 13396 // derived class to indicate a (fake) inherited constructor name. 13397 DeclarationName Name = BaseCtor->getDeclName(); 13398 13399 // Check to see if we already have a fake constructor for this inherited 13400 // constructor call. 13401 for (NamedDecl *Ctor : Derived->lookup(Name)) 13402 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor) 13403 ->getInheritedConstructor() 13404 .getConstructor(), 13405 BaseCtor)) 13406 return cast<CXXConstructorDecl>(Ctor); 13407 13408 DeclarationNameInfo NameInfo(Name, UsingLoc); 13409 TypeSourceInfo *TInfo = 13410 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc); 13411 FunctionProtoTypeLoc ProtoLoc = 13412 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 13413 13414 // Check the inherited constructor is valid and find the list of base classes 13415 // from which it was inherited. 13416 InheritedConstructorInfo ICI(*this, Loc, Shadow); 13417 13418 bool Constexpr = 13419 BaseCtor->isConstexpr() && 13420 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor, 13421 false, BaseCtor, &ICI); 13422 13423 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 13424 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo, 13425 BaseCtor->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(), 13426 /*isInline=*/true, 13427 /*isImplicitlyDeclared=*/true, 13428 Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified, 13429 InheritedConstructor(Shadow, BaseCtor), 13430 BaseCtor->getTrailingRequiresClause()); 13431 if (Shadow->isInvalidDecl()) 13432 DerivedCtor->setInvalidDecl(); 13433 13434 // Build an unevaluated exception specification for this fake constructor. 13435 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>(); 13436 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 13437 EPI.ExceptionSpec.Type = EST_Unevaluated; 13438 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 13439 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 13440 FPT->getParamTypes(), EPI)); 13441 13442 // Build the parameter declarations. 13443 SmallVector<ParmVarDecl *, 16> ParamDecls; 13444 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 13445 TypeSourceInfo *TInfo = 13446 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 13447 ParmVarDecl *PD = ParmVarDecl::Create( 13448 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 13449 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr); 13450 PD->setScopeInfo(0, I); 13451 PD->setImplicit(); 13452 // Ensure attributes are propagated onto parameters (this matters for 13453 // format, pass_object_size, ...). 13454 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I)); 13455 ParamDecls.push_back(PD); 13456 ProtoLoc.setParam(I, PD); 13457 } 13458 13459 // Set up the new constructor. 13460 assert(!BaseCtor->isDeleted() && "should not use deleted constructor"); 13461 DerivedCtor->setAccess(BaseCtor->getAccess()); 13462 DerivedCtor->setParams(ParamDecls); 13463 Derived->addDecl(DerivedCtor); 13464 13465 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI)) 13466 SetDeclDeleted(DerivedCtor, UsingLoc); 13467 13468 return DerivedCtor; 13469 } 13470 13471 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) { 13472 InheritedConstructorInfo ICI(*this, Ctor->getLocation(), 13473 Ctor->getInheritedConstructor().getShadowDecl()); 13474 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI, 13475 /*Diagnose*/true); 13476 } 13477 13478 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 13479 CXXConstructorDecl *Constructor) { 13480 CXXRecordDecl *ClassDecl = Constructor->getParent(); 13481 assert(Constructor->getInheritedConstructor() && 13482 !Constructor->doesThisDeclarationHaveABody() && 13483 !Constructor->isDeleted()); 13484 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 13485 return; 13486 13487 // Initializations are performed "as if by a defaulted default constructor", 13488 // so enter the appropriate scope. 13489 SynthesizedFunctionScope Scope(*this, Constructor); 13490 13491 // The exception specification is needed because we are defining the 13492 // function. 13493 ResolveExceptionSpec(CurrentLocation, 13494 Constructor->getType()->castAs<FunctionProtoType>()); 13495 MarkVTableUsed(CurrentLocation, ClassDecl); 13496 13497 // Add a context note for diagnostics produced after this point. 13498 Scope.addContextNote(CurrentLocation); 13499 13500 ConstructorUsingShadowDecl *Shadow = 13501 Constructor->getInheritedConstructor().getShadowDecl(); 13502 CXXConstructorDecl *InheritedCtor = 13503 Constructor->getInheritedConstructor().getConstructor(); 13504 13505 // [class.inhctor.init]p1: 13506 // initialization proceeds as if a defaulted default constructor is used to 13507 // initialize the D object and each base class subobject from which the 13508 // constructor was inherited 13509 13510 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow); 13511 CXXRecordDecl *RD = Shadow->getParent(); 13512 SourceLocation InitLoc = Shadow->getLocation(); 13513 13514 // Build explicit initializers for all base classes from which the 13515 // constructor was inherited. 13516 SmallVector<CXXCtorInitializer*, 8> Inits; 13517 for (bool VBase : {false, true}) { 13518 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) { 13519 if (B.isVirtual() != VBase) 13520 continue; 13521 13522 auto *BaseRD = B.getType()->getAsCXXRecordDecl(); 13523 if (!BaseRD) 13524 continue; 13525 13526 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor); 13527 if (!BaseCtor.first) 13528 continue; 13529 13530 MarkFunctionReferenced(CurrentLocation, BaseCtor.first); 13531 ExprResult Init = new (Context) CXXInheritedCtorInitExpr( 13532 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second); 13533 13534 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc); 13535 Inits.push_back(new (Context) CXXCtorInitializer( 13536 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc, 13537 SourceLocation())); 13538 } 13539 } 13540 13541 // We now proceed as if for a defaulted default constructor, with the relevant 13542 // initializers replaced. 13543 13544 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) { 13545 Constructor->setInvalidDecl(); 13546 return; 13547 } 13548 13549 Constructor->setBody(new (Context) CompoundStmt(InitLoc)); 13550 Constructor->markUsed(Context); 13551 13552 if (ASTMutationListener *L = getASTMutationListener()) { 13553 L->CompletedImplicitDefinition(Constructor); 13554 } 13555 13556 DiagnoseUninitializedFields(*this, Constructor); 13557 } 13558 13559 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 13560 // C++ [class.dtor]p2: 13561 // If a class has no user-declared destructor, a destructor is 13562 // declared implicitly. An implicitly-declared destructor is an 13563 // inline public member of its class. 13564 assert(ClassDecl->needsImplicitDestructor()); 13565 13566 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 13567 if (DSM.isAlreadyBeingDeclared()) 13568 return nullptr; 13569 13570 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 13571 CXXDestructor, 13572 false); 13573 13574 // Create the actual destructor declaration. 13575 CanQualType ClassType 13576 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 13577 SourceLocation ClassLoc = ClassDecl->getLocation(); 13578 DeclarationName Name 13579 = Context.DeclarationNames.getCXXDestructorName(ClassType); 13580 DeclarationNameInfo NameInfo(Name, ClassLoc); 13581 CXXDestructorDecl *Destructor = CXXDestructorDecl::Create( 13582 Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr, 13583 getCurFPFeatures().isFPConstrained(), 13584 /*isInline=*/true, 13585 /*isImplicitlyDeclared=*/true, 13586 Constexpr ? ConstexprSpecKind::Constexpr 13587 : ConstexprSpecKind::Unspecified); 13588 Destructor->setAccess(AS_public); 13589 Destructor->setDefaulted(); 13590 13591 if (getLangOpts().CUDA) { 13592 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 13593 Destructor, 13594 /* ConstRHS */ false, 13595 /* Diagnose */ false); 13596 } 13597 13598 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None); 13599 13600 // We don't need to use SpecialMemberIsTrivial here; triviality for 13601 // destructors is easy to compute. 13602 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 13603 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() || 13604 ClassDecl->hasTrivialDestructorForCall()); 13605 13606 // Note that we have declared this destructor. 13607 ++getASTContext().NumImplicitDestructorsDeclared; 13608 13609 Scope *S = getScopeForContext(ClassDecl); 13610 CheckImplicitSpecialMemberDeclaration(S, Destructor); 13611 13612 // We can't check whether an implicit destructor is deleted before we complete 13613 // the definition of the class, because its validity depends on the alignment 13614 // of the class. We'll check this from ActOnFields once the class is complete. 13615 if (ClassDecl->isCompleteDefinition() && 13616 ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 13617 SetDeclDeleted(Destructor, ClassLoc); 13618 13619 // Introduce this destructor into its scope. 13620 if (S) 13621 PushOnScopeChains(Destructor, S, false); 13622 ClassDecl->addDecl(Destructor); 13623 13624 return Destructor; 13625 } 13626 13627 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 13628 CXXDestructorDecl *Destructor) { 13629 assert((Destructor->isDefaulted() && 13630 !Destructor->doesThisDeclarationHaveABody() && 13631 !Destructor->isDeleted()) && 13632 "DefineImplicitDestructor - call it for implicit default dtor"); 13633 if (Destructor->willHaveBody() || Destructor->isInvalidDecl()) 13634 return; 13635 13636 CXXRecordDecl *ClassDecl = Destructor->getParent(); 13637 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 13638 13639 SynthesizedFunctionScope Scope(*this, Destructor); 13640 13641 // The exception specification is needed because we are defining the 13642 // function. 13643 ResolveExceptionSpec(CurrentLocation, 13644 Destructor->getType()->castAs<FunctionProtoType>()); 13645 MarkVTableUsed(CurrentLocation, ClassDecl); 13646 13647 // Add a context note for diagnostics produced after this point. 13648 Scope.addContextNote(CurrentLocation); 13649 13650 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 13651 Destructor->getParent()); 13652 13653 if (CheckDestructor(Destructor)) { 13654 Destructor->setInvalidDecl(); 13655 return; 13656 } 13657 13658 SourceLocation Loc = Destructor->getEndLoc().isValid() 13659 ? Destructor->getEndLoc() 13660 : Destructor->getLocation(); 13661 Destructor->setBody(new (Context) CompoundStmt(Loc)); 13662 Destructor->markUsed(Context); 13663 13664 if (ASTMutationListener *L = getASTMutationListener()) { 13665 L->CompletedImplicitDefinition(Destructor); 13666 } 13667 } 13668 13669 void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation, 13670 CXXDestructorDecl *Destructor) { 13671 if (Destructor->isInvalidDecl()) 13672 return; 13673 13674 CXXRecordDecl *ClassDecl = Destructor->getParent(); 13675 assert(Context.getTargetInfo().getCXXABI().isMicrosoft() && 13676 "implicit complete dtors unneeded outside MS ABI"); 13677 assert(ClassDecl->getNumVBases() > 0 && 13678 "complete dtor only exists for classes with vbases"); 13679 13680 SynthesizedFunctionScope Scope(*this, Destructor); 13681 13682 // Add a context note for diagnostics produced after this point. 13683 Scope.addContextNote(CurrentLocation); 13684 13685 MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl); 13686 } 13687 13688 /// Perform any semantic analysis which needs to be delayed until all 13689 /// pending class member declarations have been parsed. 13690 void Sema::ActOnFinishCXXMemberDecls() { 13691 // If the context is an invalid C++ class, just suppress these checks. 13692 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 13693 if (Record->isInvalidDecl()) { 13694 DelayedOverridingExceptionSpecChecks.clear(); 13695 DelayedEquivalentExceptionSpecChecks.clear(); 13696 return; 13697 } 13698 checkForMultipleExportedDefaultConstructors(*this, Record); 13699 } 13700 } 13701 13702 void Sema::ActOnFinishCXXNonNestedClass() { 13703 referenceDLLExportedClassMethods(); 13704 13705 if (!DelayedDllExportMemberFunctions.empty()) { 13706 SmallVector<CXXMethodDecl*, 4> WorkList; 13707 std::swap(DelayedDllExportMemberFunctions, WorkList); 13708 for (CXXMethodDecl *M : WorkList) { 13709 DefineDefaultedFunction(*this, M, M->getLocation()); 13710 13711 // Pass the method to the consumer to get emitted. This is not necessary 13712 // for explicit instantiation definitions, as they will get emitted 13713 // anyway. 13714 if (M->getParent()->getTemplateSpecializationKind() != 13715 TSK_ExplicitInstantiationDefinition) 13716 ActOnFinishInlineFunctionDef(M); 13717 } 13718 } 13719 } 13720 13721 void Sema::referenceDLLExportedClassMethods() { 13722 if (!DelayedDllExportClasses.empty()) { 13723 // Calling ReferenceDllExportedMembers might cause the current function to 13724 // be called again, so use a local copy of DelayedDllExportClasses. 13725 SmallVector<CXXRecordDecl *, 4> WorkList; 13726 std::swap(DelayedDllExportClasses, WorkList); 13727 for (CXXRecordDecl *Class : WorkList) 13728 ReferenceDllExportedMembers(*this, Class); 13729 } 13730 } 13731 13732 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) { 13733 assert(getLangOpts().CPlusPlus11 && 13734 "adjusting dtor exception specs was introduced in c++11"); 13735 13736 if (Destructor->isDependentContext()) 13737 return; 13738 13739 // C++11 [class.dtor]p3: 13740 // A declaration of a destructor that does not have an exception- 13741 // specification is implicitly considered to have the same exception- 13742 // specification as an implicit declaration. 13743 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>(); 13744 if (DtorType->hasExceptionSpec()) 13745 return; 13746 13747 // Replace the destructor's type, building off the existing one. Fortunately, 13748 // the only thing of interest in the destructor type is its extended info. 13749 // The return and arguments are fixed. 13750 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 13751 EPI.ExceptionSpec.Type = EST_Unevaluated; 13752 EPI.ExceptionSpec.SourceDecl = Destructor; 13753 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 13754 13755 // FIXME: If the destructor has a body that could throw, and the newly created 13756 // spec doesn't allow exceptions, we should emit a warning, because this 13757 // change in behavior can break conforming C++03 programs at runtime. 13758 // However, we don't have a body or an exception specification yet, so it 13759 // needs to be done somewhere else. 13760 } 13761 13762 namespace { 13763 /// An abstract base class for all helper classes used in building the 13764 // copy/move operators. These classes serve as factory functions and help us 13765 // avoid using the same Expr* in the AST twice. 13766 class ExprBuilder { 13767 ExprBuilder(const ExprBuilder&) = delete; 13768 ExprBuilder &operator=(const ExprBuilder&) = delete; 13769 13770 protected: 13771 static Expr *assertNotNull(Expr *E) { 13772 assert(E && "Expression construction must not fail."); 13773 return E; 13774 } 13775 13776 public: 13777 ExprBuilder() {} 13778 virtual ~ExprBuilder() {} 13779 13780 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 13781 }; 13782 13783 class RefBuilder: public ExprBuilder { 13784 VarDecl *Var; 13785 QualType VarType; 13786 13787 public: 13788 Expr *build(Sema &S, SourceLocation Loc) const override { 13789 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc)); 13790 } 13791 13792 RefBuilder(VarDecl *Var, QualType VarType) 13793 : Var(Var), VarType(VarType) {} 13794 }; 13795 13796 class ThisBuilder: public ExprBuilder { 13797 public: 13798 Expr *build(Sema &S, SourceLocation Loc) const override { 13799 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 13800 } 13801 }; 13802 13803 class CastBuilder: public ExprBuilder { 13804 const ExprBuilder &Builder; 13805 QualType Type; 13806 ExprValueKind Kind; 13807 const CXXCastPath &Path; 13808 13809 public: 13810 Expr *build(Sema &S, SourceLocation Loc) const override { 13811 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 13812 CK_UncheckedDerivedToBase, Kind, 13813 &Path).get()); 13814 } 13815 13816 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 13817 const CXXCastPath &Path) 13818 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 13819 }; 13820 13821 class DerefBuilder: public ExprBuilder { 13822 const ExprBuilder &Builder; 13823 13824 public: 13825 Expr *build(Sema &S, SourceLocation Loc) const override { 13826 return assertNotNull( 13827 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 13828 } 13829 13830 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13831 }; 13832 13833 class MemberBuilder: public ExprBuilder { 13834 const ExprBuilder &Builder; 13835 QualType Type; 13836 CXXScopeSpec SS; 13837 bool IsArrow; 13838 LookupResult &MemberLookup; 13839 13840 public: 13841 Expr *build(Sema &S, SourceLocation Loc) const override { 13842 return assertNotNull(S.BuildMemberReferenceExpr( 13843 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 13844 nullptr, MemberLookup, nullptr, nullptr).get()); 13845 } 13846 13847 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 13848 LookupResult &MemberLookup) 13849 : Builder(Builder), Type(Type), IsArrow(IsArrow), 13850 MemberLookup(MemberLookup) {} 13851 }; 13852 13853 class MoveCastBuilder: public ExprBuilder { 13854 const ExprBuilder &Builder; 13855 13856 public: 13857 Expr *build(Sema &S, SourceLocation Loc) const override { 13858 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 13859 } 13860 13861 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13862 }; 13863 13864 class LvalueConvBuilder: public ExprBuilder { 13865 const ExprBuilder &Builder; 13866 13867 public: 13868 Expr *build(Sema &S, SourceLocation Loc) const override { 13869 return assertNotNull( 13870 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 13871 } 13872 13873 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13874 }; 13875 13876 class SubscriptBuilder: public ExprBuilder { 13877 const ExprBuilder &Base; 13878 const ExprBuilder &Index; 13879 13880 public: 13881 Expr *build(Sema &S, SourceLocation Loc) const override { 13882 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 13883 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 13884 } 13885 13886 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 13887 : Base(Base), Index(Index) {} 13888 }; 13889 13890 } // end anonymous namespace 13891 13892 /// When generating a defaulted copy or move assignment operator, if a field 13893 /// should be copied with __builtin_memcpy rather than via explicit assignments, 13894 /// do so. This optimization only applies for arrays of scalars, and for arrays 13895 /// of class type where the selected copy/move-assignment operator is trivial. 13896 static StmtResult 13897 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 13898 const ExprBuilder &ToB, const ExprBuilder &FromB) { 13899 // Compute the size of the memory buffer to be copied. 13900 QualType SizeType = S.Context.getSizeType(); 13901 llvm::APInt Size(S.Context.getTypeSize(SizeType), 13902 S.Context.getTypeSizeInChars(T).getQuantity()); 13903 13904 // Take the address of the field references for "from" and "to". We 13905 // directly construct UnaryOperators here because semantic analysis 13906 // does not permit us to take the address of an xvalue. 13907 Expr *From = FromB.build(S, Loc); 13908 From = UnaryOperator::Create( 13909 S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()), 13910 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides()); 13911 Expr *To = ToB.build(S, Loc); 13912 To = UnaryOperator::Create( 13913 S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()), 13914 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides()); 13915 13916 const Type *E = T->getBaseElementTypeUnsafe(); 13917 bool NeedsCollectableMemCpy = 13918 E->isRecordType() && 13919 E->castAs<RecordType>()->getDecl()->hasObjectMember(); 13920 13921 // Create a reference to the __builtin_objc_memmove_collectable function 13922 StringRef MemCpyName = NeedsCollectableMemCpy ? 13923 "__builtin_objc_memmove_collectable" : 13924 "__builtin_memcpy"; 13925 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 13926 Sema::LookupOrdinaryName); 13927 S.LookupName(R, S.TUScope, true); 13928 13929 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 13930 if (!MemCpy) 13931 // Something went horribly wrong earlier, and we will have complained 13932 // about it. 13933 return StmtError(); 13934 13935 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 13936 VK_PRValue, Loc, nullptr); 13937 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 13938 13939 Expr *CallArgs[] = { 13940 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 13941 }; 13942 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 13943 Loc, CallArgs, Loc); 13944 13945 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 13946 return Call.getAs<Stmt>(); 13947 } 13948 13949 /// Builds a statement that copies/moves the given entity from \p From to 13950 /// \c To. 13951 /// 13952 /// This routine is used to copy/move the members of a class with an 13953 /// implicitly-declared copy/move assignment operator. When the entities being 13954 /// copied are arrays, this routine builds for loops to copy them. 13955 /// 13956 /// \param S The Sema object used for type-checking. 13957 /// 13958 /// \param Loc The location where the implicit copy/move is being generated. 13959 /// 13960 /// \param T The type of the expressions being copied/moved. Both expressions 13961 /// must have this type. 13962 /// 13963 /// \param To The expression we are copying/moving to. 13964 /// 13965 /// \param From The expression we are copying/moving from. 13966 /// 13967 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 13968 /// Otherwise, it's a non-static member subobject. 13969 /// 13970 /// \param Copying Whether we're copying or moving. 13971 /// 13972 /// \param Depth Internal parameter recording the depth of the recursion. 13973 /// 13974 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 13975 /// if a memcpy should be used instead. 13976 static StmtResult 13977 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 13978 const ExprBuilder &To, const ExprBuilder &From, 13979 bool CopyingBaseSubobject, bool Copying, 13980 unsigned Depth = 0) { 13981 // C++11 [class.copy]p28: 13982 // Each subobject is assigned in the manner appropriate to its type: 13983 // 13984 // - if the subobject is of class type, as if by a call to operator= with 13985 // the subobject as the object expression and the corresponding 13986 // subobject of x as a single function argument (as if by explicit 13987 // qualification; that is, ignoring any possible virtual overriding 13988 // functions in more derived classes); 13989 // 13990 // C++03 [class.copy]p13: 13991 // - if the subobject is of class type, the copy assignment operator for 13992 // the class is used (as if by explicit qualification; that is, 13993 // ignoring any possible virtual overriding functions in more derived 13994 // classes); 13995 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 13996 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 13997 13998 // Look for operator=. 13999 DeclarationName Name 14000 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 14001 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 14002 S.LookupQualifiedName(OpLookup, ClassDecl, false); 14003 14004 // Prior to C++11, filter out any result that isn't a copy/move-assignment 14005 // operator. 14006 if (!S.getLangOpts().CPlusPlus11) { 14007 LookupResult::Filter F = OpLookup.makeFilter(); 14008 while (F.hasNext()) { 14009 NamedDecl *D = F.next(); 14010 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 14011 if (Method->isCopyAssignmentOperator() || 14012 (!Copying && Method->isMoveAssignmentOperator())) 14013 continue; 14014 14015 F.erase(); 14016 } 14017 F.done(); 14018 } 14019 14020 // Suppress the protected check (C++ [class.protected]) for each of the 14021 // assignment operators we found. This strange dance is required when 14022 // we're assigning via a base classes's copy-assignment operator. To 14023 // ensure that we're getting the right base class subobject (without 14024 // ambiguities), we need to cast "this" to that subobject type; to 14025 // ensure that we don't go through the virtual call mechanism, we need 14026 // to qualify the operator= name with the base class (see below). However, 14027 // this means that if the base class has a protected copy assignment 14028 // operator, the protected member access check will fail. So, we 14029 // rewrite "protected" access to "public" access in this case, since we 14030 // know by construction that we're calling from a derived class. 14031 if (CopyingBaseSubobject) { 14032 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 14033 L != LEnd; ++L) { 14034 if (L.getAccess() == AS_protected) 14035 L.setAccess(AS_public); 14036 } 14037 } 14038 14039 // Create the nested-name-specifier that will be used to qualify the 14040 // reference to operator=; this is required to suppress the virtual 14041 // call mechanism. 14042 CXXScopeSpec SS; 14043 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 14044 SS.MakeTrivial(S.Context, 14045 NestedNameSpecifier::Create(S.Context, nullptr, false, 14046 CanonicalT), 14047 Loc); 14048 14049 // Create the reference to operator=. 14050 ExprResult OpEqualRef 14051 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false, 14052 SS, /*TemplateKWLoc=*/SourceLocation(), 14053 /*FirstQualifierInScope=*/nullptr, 14054 OpLookup, 14055 /*TemplateArgs=*/nullptr, /*S*/nullptr, 14056 /*SuppressQualifierCheck=*/true); 14057 if (OpEqualRef.isInvalid()) 14058 return StmtError(); 14059 14060 // Build the call to the assignment operator. 14061 14062 Expr *FromInst = From.build(S, Loc); 14063 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 14064 OpEqualRef.getAs<Expr>(), 14065 Loc, FromInst, Loc); 14066 if (Call.isInvalid()) 14067 return StmtError(); 14068 14069 // If we built a call to a trivial 'operator=' while copying an array, 14070 // bail out. We'll replace the whole shebang with a memcpy. 14071 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 14072 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 14073 return StmtResult((Stmt*)nullptr); 14074 14075 // Convert to an expression-statement, and clean up any produced 14076 // temporaries. 14077 return S.ActOnExprStmt(Call); 14078 } 14079 14080 // - if the subobject is of scalar type, the built-in assignment 14081 // operator is used. 14082 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 14083 if (!ArrayTy) { 14084 ExprResult Assignment = S.CreateBuiltinBinOp( 14085 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 14086 if (Assignment.isInvalid()) 14087 return StmtError(); 14088 return S.ActOnExprStmt(Assignment); 14089 } 14090 14091 // - if the subobject is an array, each element is assigned, in the 14092 // manner appropriate to the element type; 14093 14094 // Construct a loop over the array bounds, e.g., 14095 // 14096 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 14097 // 14098 // that will copy each of the array elements. 14099 QualType SizeType = S.Context.getSizeType(); 14100 14101 // Create the iteration variable. 14102 IdentifierInfo *IterationVarName = nullptr; 14103 { 14104 SmallString<8> Str; 14105 llvm::raw_svector_ostream OS(Str); 14106 OS << "__i" << Depth; 14107 IterationVarName = &S.Context.Idents.get(OS.str()); 14108 } 14109 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 14110 IterationVarName, SizeType, 14111 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 14112 SC_None); 14113 14114 // Initialize the iteration variable to zero. 14115 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 14116 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 14117 14118 // Creates a reference to the iteration variable. 14119 RefBuilder IterationVarRef(IterationVar, SizeType); 14120 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 14121 14122 // Create the DeclStmt that holds the iteration variable. 14123 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 14124 14125 // Subscript the "from" and "to" expressions with the iteration variable. 14126 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 14127 MoveCastBuilder FromIndexMove(FromIndexCopy); 14128 const ExprBuilder *FromIndex; 14129 if (Copying) 14130 FromIndex = &FromIndexCopy; 14131 else 14132 FromIndex = &FromIndexMove; 14133 14134 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 14135 14136 // Build the copy/move for an individual element of the array. 14137 StmtResult Copy = 14138 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 14139 ToIndex, *FromIndex, CopyingBaseSubobject, 14140 Copying, Depth + 1); 14141 // Bail out if copying fails or if we determined that we should use memcpy. 14142 if (Copy.isInvalid() || !Copy.get()) 14143 return Copy; 14144 14145 // Create the comparison against the array bound. 14146 llvm::APInt Upper 14147 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 14148 Expr *Comparison = BinaryOperator::Create( 14149 S.Context, IterationVarRefRVal.build(S, Loc), 14150 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE, 14151 S.Context.BoolTy, VK_PRValue, OK_Ordinary, Loc, 14152 S.CurFPFeatureOverrides()); 14153 14154 // Create the pre-increment of the iteration variable. We can determine 14155 // whether the increment will overflow based on the value of the array 14156 // bound. 14157 Expr *Increment = UnaryOperator::Create( 14158 S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue, 14159 OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides()); 14160 14161 // Construct the loop that copies all elements of this array. 14162 return S.ActOnForStmt( 14163 Loc, Loc, InitStmt, 14164 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean), 14165 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get()); 14166 } 14167 14168 static StmtResult 14169 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 14170 const ExprBuilder &To, const ExprBuilder &From, 14171 bool CopyingBaseSubobject, bool Copying) { 14172 // Maybe we should use a memcpy? 14173 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 14174 T.isTriviallyCopyableType(S.Context)) 14175 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 14176 14177 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 14178 CopyingBaseSubobject, 14179 Copying, 0)); 14180 14181 // If we ended up picking a trivial assignment operator for an array of a 14182 // non-trivially-copyable class type, just emit a memcpy. 14183 if (!Result.isInvalid() && !Result.get()) 14184 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 14185 14186 return Result; 14187 } 14188 14189 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 14190 // Note: The following rules are largely analoguous to the copy 14191 // constructor rules. Note that virtual bases are not taken into account 14192 // for determining the argument type of the operator. Note also that 14193 // operators taking an object instead of a reference are allowed. 14194 assert(ClassDecl->needsImplicitCopyAssignment()); 14195 14196 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 14197 if (DSM.isAlreadyBeingDeclared()) 14198 return nullptr; 14199 14200 QualType ArgType = Context.getTypeDeclType(ClassDecl); 14201 LangAS AS = getDefaultCXXMethodAddrSpace(); 14202 if (AS != LangAS::Default) 14203 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 14204 QualType RetType = Context.getLValueReferenceType(ArgType); 14205 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 14206 if (Const) 14207 ArgType = ArgType.withConst(); 14208 14209 ArgType = Context.getLValueReferenceType(ArgType); 14210 14211 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14212 CXXCopyAssignment, 14213 Const); 14214 14215 // An implicitly-declared copy assignment operator is an inline public 14216 // member of its class. 14217 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 14218 SourceLocation ClassLoc = ClassDecl->getLocation(); 14219 DeclarationNameInfo NameInfo(Name, ClassLoc); 14220 CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create( 14221 Context, ClassDecl, ClassLoc, NameInfo, QualType(), 14222 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 14223 getCurFPFeatures().isFPConstrained(), 14224 /*isInline=*/true, 14225 Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified, 14226 SourceLocation()); 14227 CopyAssignment->setAccess(AS_public); 14228 CopyAssignment->setDefaulted(); 14229 CopyAssignment->setImplicit(); 14230 14231 if (getLangOpts().CUDA) { 14232 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 14233 CopyAssignment, 14234 /* ConstRHS */ Const, 14235 /* Diagnose */ false); 14236 } 14237 14238 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType); 14239 14240 // Add the parameter to the operator. 14241 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 14242 ClassLoc, ClassLoc, 14243 /*Id=*/nullptr, ArgType, 14244 /*TInfo=*/nullptr, SC_None, 14245 nullptr); 14246 CopyAssignment->setParams(FromParam); 14247 14248 CopyAssignment->setTrivial( 14249 ClassDecl->needsOverloadResolutionForCopyAssignment() 14250 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 14251 : ClassDecl->hasTrivialCopyAssignment()); 14252 14253 // Note that we have added this copy-assignment operator. 14254 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared; 14255 14256 Scope *S = getScopeForContext(ClassDecl); 14257 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment); 14258 14259 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) { 14260 ClassDecl->setImplicitCopyAssignmentIsDeleted(); 14261 SetDeclDeleted(CopyAssignment, ClassLoc); 14262 } 14263 14264 if (S) 14265 PushOnScopeChains(CopyAssignment, S, false); 14266 ClassDecl->addDecl(CopyAssignment); 14267 14268 return CopyAssignment; 14269 } 14270 14271 /// Diagnose an implicit copy operation for a class which is odr-used, but 14272 /// which is deprecated because the class has a user-declared copy constructor, 14273 /// copy assignment operator, or destructor. 14274 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) { 14275 assert(CopyOp->isImplicit()); 14276 14277 CXXRecordDecl *RD = CopyOp->getParent(); 14278 CXXMethodDecl *UserDeclaredOperation = nullptr; 14279 14280 // In Microsoft mode, assignment operations don't affect constructors and 14281 // vice versa. 14282 if (RD->hasUserDeclaredDestructor()) { 14283 UserDeclaredOperation = RD->getDestructor(); 14284 } else if (!isa<CXXConstructorDecl>(CopyOp) && 14285 RD->hasUserDeclaredCopyConstructor() && 14286 !S.getLangOpts().MSVCCompat) { 14287 // Find any user-declared copy constructor. 14288 for (auto *I : RD->ctors()) { 14289 if (I->isCopyConstructor()) { 14290 UserDeclaredOperation = I; 14291 break; 14292 } 14293 } 14294 assert(UserDeclaredOperation); 14295 } else if (isa<CXXConstructorDecl>(CopyOp) && 14296 RD->hasUserDeclaredCopyAssignment() && 14297 !S.getLangOpts().MSVCCompat) { 14298 // Find any user-declared move assignment operator. 14299 for (auto *I : RD->methods()) { 14300 if (I->isCopyAssignmentOperator()) { 14301 UserDeclaredOperation = I; 14302 break; 14303 } 14304 } 14305 assert(UserDeclaredOperation); 14306 } 14307 14308 if (UserDeclaredOperation) { 14309 bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided(); 14310 bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation); 14311 bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp); 14312 unsigned DiagID = 14313 (UDOIsUserProvided && UDOIsDestructor) 14314 ? diag::warn_deprecated_copy_with_user_provided_dtor 14315 : (UDOIsUserProvided && !UDOIsDestructor) 14316 ? diag::warn_deprecated_copy_with_user_provided_copy 14317 : (!UDOIsUserProvided && UDOIsDestructor) 14318 ? diag::warn_deprecated_copy_with_dtor 14319 : diag::warn_deprecated_copy; 14320 S.Diag(UserDeclaredOperation->getLocation(), DiagID) 14321 << RD << IsCopyAssignment; 14322 } 14323 } 14324 14325 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 14326 CXXMethodDecl *CopyAssignOperator) { 14327 assert((CopyAssignOperator->isDefaulted() && 14328 CopyAssignOperator->isOverloadedOperator() && 14329 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 14330 !CopyAssignOperator->doesThisDeclarationHaveABody() && 14331 !CopyAssignOperator->isDeleted()) && 14332 "DefineImplicitCopyAssignment called for wrong function"); 14333 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl()) 14334 return; 14335 14336 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 14337 if (ClassDecl->isInvalidDecl()) { 14338 CopyAssignOperator->setInvalidDecl(); 14339 return; 14340 } 14341 14342 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 14343 14344 // The exception specification is needed because we are defining the 14345 // function. 14346 ResolveExceptionSpec(CurrentLocation, 14347 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 14348 14349 // Add a context note for diagnostics produced after this point. 14350 Scope.addContextNote(CurrentLocation); 14351 14352 // C++11 [class.copy]p18: 14353 // The [definition of an implicitly declared copy assignment operator] is 14354 // deprecated if the class has a user-declared copy constructor or a 14355 // user-declared destructor. 14356 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 14357 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator); 14358 14359 // C++0x [class.copy]p30: 14360 // The implicitly-defined or explicitly-defaulted copy assignment operator 14361 // for a non-union class X performs memberwise copy assignment of its 14362 // subobjects. The direct base classes of X are assigned first, in the 14363 // order of their declaration in the base-specifier-list, and then the 14364 // immediate non-static data members of X are assigned, in the order in 14365 // which they were declared in the class definition. 14366 14367 // The statements that form the synthesized function body. 14368 SmallVector<Stmt*, 8> Statements; 14369 14370 // The parameter for the "other" object, which we are copying from. 14371 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 14372 Qualifiers OtherQuals = Other->getType().getQualifiers(); 14373 QualType OtherRefType = Other->getType(); 14374 if (const LValueReferenceType *OtherRef 14375 = OtherRefType->getAs<LValueReferenceType>()) { 14376 OtherRefType = OtherRef->getPointeeType(); 14377 OtherQuals = OtherRefType.getQualifiers(); 14378 } 14379 14380 // Our location for everything implicitly-generated. 14381 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid() 14382 ? CopyAssignOperator->getEndLoc() 14383 : CopyAssignOperator->getLocation(); 14384 14385 // Builds a DeclRefExpr for the "other" object. 14386 RefBuilder OtherRef(Other, OtherRefType); 14387 14388 // Builds the "this" pointer. 14389 ThisBuilder This; 14390 14391 // Assign base classes. 14392 bool Invalid = false; 14393 for (auto &Base : ClassDecl->bases()) { 14394 // Form the assignment: 14395 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 14396 QualType BaseType = Base.getType().getUnqualifiedType(); 14397 if (!BaseType->isRecordType()) { 14398 Invalid = true; 14399 continue; 14400 } 14401 14402 CXXCastPath BasePath; 14403 BasePath.push_back(&Base); 14404 14405 // Construct the "from" expression, which is an implicit cast to the 14406 // appropriately-qualified base type. 14407 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 14408 VK_LValue, BasePath); 14409 14410 // Dereference "this". 14411 DerefBuilder DerefThis(This); 14412 CastBuilder To(DerefThis, 14413 Context.getQualifiedType( 14414 BaseType, CopyAssignOperator->getMethodQualifiers()), 14415 VK_LValue, BasePath); 14416 14417 // Build the copy. 14418 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 14419 To, From, 14420 /*CopyingBaseSubobject=*/true, 14421 /*Copying=*/true); 14422 if (Copy.isInvalid()) { 14423 CopyAssignOperator->setInvalidDecl(); 14424 return; 14425 } 14426 14427 // Success! Record the copy. 14428 Statements.push_back(Copy.getAs<Expr>()); 14429 } 14430 14431 // Assign non-static members. 14432 for (auto *Field : ClassDecl->fields()) { 14433 // FIXME: We should form some kind of AST representation for the implied 14434 // memcpy in a union copy operation. 14435 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 14436 continue; 14437 14438 if (Field->isInvalidDecl()) { 14439 Invalid = true; 14440 continue; 14441 } 14442 14443 // Check for members of reference type; we can't copy those. 14444 if (Field->getType()->isReferenceType()) { 14445 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14446 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 14447 Diag(Field->getLocation(), diag::note_declared_at); 14448 Invalid = true; 14449 continue; 14450 } 14451 14452 // Check for members of const-qualified, non-class type. 14453 QualType BaseType = Context.getBaseElementType(Field->getType()); 14454 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 14455 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14456 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 14457 Diag(Field->getLocation(), diag::note_declared_at); 14458 Invalid = true; 14459 continue; 14460 } 14461 14462 // Suppress assigning zero-width bitfields. 14463 if (Field->isZeroLengthBitField(Context)) 14464 continue; 14465 14466 QualType FieldType = Field->getType().getNonReferenceType(); 14467 if (FieldType->isIncompleteArrayType()) { 14468 assert(ClassDecl->hasFlexibleArrayMember() && 14469 "Incomplete array type is not valid"); 14470 continue; 14471 } 14472 14473 // Build references to the field in the object we're copying from and to. 14474 CXXScopeSpec SS; // Intentionally empty 14475 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 14476 LookupMemberName); 14477 MemberLookup.addDecl(Field); 14478 MemberLookup.resolveKind(); 14479 14480 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 14481 14482 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 14483 14484 // Build the copy of this field. 14485 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 14486 To, From, 14487 /*CopyingBaseSubobject=*/false, 14488 /*Copying=*/true); 14489 if (Copy.isInvalid()) { 14490 CopyAssignOperator->setInvalidDecl(); 14491 return; 14492 } 14493 14494 // Success! Record the copy. 14495 Statements.push_back(Copy.getAs<Stmt>()); 14496 } 14497 14498 if (!Invalid) { 14499 // Add a "return *this;" 14500 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 14501 14502 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 14503 if (Return.isInvalid()) 14504 Invalid = true; 14505 else 14506 Statements.push_back(Return.getAs<Stmt>()); 14507 } 14508 14509 if (Invalid) { 14510 CopyAssignOperator->setInvalidDecl(); 14511 return; 14512 } 14513 14514 StmtResult Body; 14515 { 14516 CompoundScopeRAII CompoundScope(*this); 14517 Body = ActOnCompoundStmt(Loc, Loc, Statements, 14518 /*isStmtExpr=*/false); 14519 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 14520 } 14521 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 14522 CopyAssignOperator->markUsed(Context); 14523 14524 if (ASTMutationListener *L = getASTMutationListener()) { 14525 L->CompletedImplicitDefinition(CopyAssignOperator); 14526 } 14527 } 14528 14529 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 14530 assert(ClassDecl->needsImplicitMoveAssignment()); 14531 14532 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 14533 if (DSM.isAlreadyBeingDeclared()) 14534 return nullptr; 14535 14536 // Note: The following rules are largely analoguous to the move 14537 // constructor rules. 14538 14539 QualType ArgType = Context.getTypeDeclType(ClassDecl); 14540 LangAS AS = getDefaultCXXMethodAddrSpace(); 14541 if (AS != LangAS::Default) 14542 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 14543 QualType RetType = Context.getLValueReferenceType(ArgType); 14544 ArgType = Context.getRValueReferenceType(ArgType); 14545 14546 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14547 CXXMoveAssignment, 14548 false); 14549 14550 // An implicitly-declared move assignment operator is an inline public 14551 // member of its class. 14552 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 14553 SourceLocation ClassLoc = ClassDecl->getLocation(); 14554 DeclarationNameInfo NameInfo(Name, ClassLoc); 14555 CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create( 14556 Context, ClassDecl, ClassLoc, NameInfo, QualType(), 14557 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 14558 getCurFPFeatures().isFPConstrained(), 14559 /*isInline=*/true, 14560 Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified, 14561 SourceLocation()); 14562 MoveAssignment->setAccess(AS_public); 14563 MoveAssignment->setDefaulted(); 14564 MoveAssignment->setImplicit(); 14565 14566 if (getLangOpts().CUDA) { 14567 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 14568 MoveAssignment, 14569 /* ConstRHS */ false, 14570 /* Diagnose */ false); 14571 } 14572 14573 setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType); 14574 14575 // Add the parameter to the operator. 14576 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 14577 ClassLoc, ClassLoc, 14578 /*Id=*/nullptr, ArgType, 14579 /*TInfo=*/nullptr, SC_None, 14580 nullptr); 14581 MoveAssignment->setParams(FromParam); 14582 14583 MoveAssignment->setTrivial( 14584 ClassDecl->needsOverloadResolutionForMoveAssignment() 14585 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 14586 : ClassDecl->hasTrivialMoveAssignment()); 14587 14588 // Note that we have added this copy-assignment operator. 14589 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared; 14590 14591 Scope *S = getScopeForContext(ClassDecl); 14592 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment); 14593 14594 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 14595 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 14596 SetDeclDeleted(MoveAssignment, ClassLoc); 14597 } 14598 14599 if (S) 14600 PushOnScopeChains(MoveAssignment, S, false); 14601 ClassDecl->addDecl(MoveAssignment); 14602 14603 return MoveAssignment; 14604 } 14605 14606 /// Check if we're implicitly defining a move assignment operator for a class 14607 /// with virtual bases. Such a move assignment might move-assign the virtual 14608 /// base multiple times. 14609 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 14610 SourceLocation CurrentLocation) { 14611 assert(!Class->isDependentContext() && "should not define dependent move"); 14612 14613 // Only a virtual base could get implicitly move-assigned multiple times. 14614 // Only a non-trivial move assignment can observe this. We only want to 14615 // diagnose if we implicitly define an assignment operator that assigns 14616 // two base classes, both of which move-assign the same virtual base. 14617 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 14618 Class->getNumBases() < 2) 14619 return; 14620 14621 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 14622 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 14623 VBaseMap VBases; 14624 14625 for (auto &BI : Class->bases()) { 14626 Worklist.push_back(&BI); 14627 while (!Worklist.empty()) { 14628 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 14629 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 14630 14631 // If the base has no non-trivial move assignment operators, 14632 // we don't care about moves from it. 14633 if (!Base->hasNonTrivialMoveAssignment()) 14634 continue; 14635 14636 // If there's nothing virtual here, skip it. 14637 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 14638 continue; 14639 14640 // If we're not actually going to call a move assignment for this base, 14641 // or the selected move assignment is trivial, skip it. 14642 Sema::SpecialMemberOverloadResult SMOR = 14643 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 14644 /*ConstArg*/false, /*VolatileArg*/false, 14645 /*RValueThis*/true, /*ConstThis*/false, 14646 /*VolatileThis*/false); 14647 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() || 14648 !SMOR.getMethod()->isMoveAssignmentOperator()) 14649 continue; 14650 14651 if (BaseSpec->isVirtual()) { 14652 // We're going to move-assign this virtual base, and its move 14653 // assignment operator is not trivial. If this can happen for 14654 // multiple distinct direct bases of Class, diagnose it. (If it 14655 // only happens in one base, we'll diagnose it when synthesizing 14656 // that base class's move assignment operator.) 14657 CXXBaseSpecifier *&Existing = 14658 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 14659 .first->second; 14660 if (Existing && Existing != &BI) { 14661 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 14662 << Class << Base; 14663 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here) 14664 << (Base->getCanonicalDecl() == 14665 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 14666 << Base << Existing->getType() << Existing->getSourceRange(); 14667 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here) 14668 << (Base->getCanonicalDecl() == 14669 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 14670 << Base << BI.getType() << BaseSpec->getSourceRange(); 14671 14672 // Only diagnose each vbase once. 14673 Existing = nullptr; 14674 } 14675 } else { 14676 // Only walk over bases that have defaulted move assignment operators. 14677 // We assume that any user-provided move assignment operator handles 14678 // the multiple-moves-of-vbase case itself somehow. 14679 if (!SMOR.getMethod()->isDefaulted()) 14680 continue; 14681 14682 // We're going to move the base classes of Base. Add them to the list. 14683 for (auto &BI : Base->bases()) 14684 Worklist.push_back(&BI); 14685 } 14686 } 14687 } 14688 } 14689 14690 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 14691 CXXMethodDecl *MoveAssignOperator) { 14692 assert((MoveAssignOperator->isDefaulted() && 14693 MoveAssignOperator->isOverloadedOperator() && 14694 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 14695 !MoveAssignOperator->doesThisDeclarationHaveABody() && 14696 !MoveAssignOperator->isDeleted()) && 14697 "DefineImplicitMoveAssignment called for wrong function"); 14698 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl()) 14699 return; 14700 14701 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 14702 if (ClassDecl->isInvalidDecl()) { 14703 MoveAssignOperator->setInvalidDecl(); 14704 return; 14705 } 14706 14707 // C++0x [class.copy]p28: 14708 // The implicitly-defined or move assignment operator for a non-union class 14709 // X performs memberwise move assignment of its subobjects. The direct base 14710 // classes of X are assigned first, in the order of their declaration in the 14711 // base-specifier-list, and then the immediate non-static data members of X 14712 // are assigned, in the order in which they were declared in the class 14713 // definition. 14714 14715 // Issue a warning if our implicit move assignment operator will move 14716 // from a virtual base more than once. 14717 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 14718 14719 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 14720 14721 // The exception specification is needed because we are defining the 14722 // function. 14723 ResolveExceptionSpec(CurrentLocation, 14724 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 14725 14726 // Add a context note for diagnostics produced after this point. 14727 Scope.addContextNote(CurrentLocation); 14728 14729 // The statements that form the synthesized function body. 14730 SmallVector<Stmt*, 8> Statements; 14731 14732 // The parameter for the "other" object, which we are move from. 14733 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 14734 QualType OtherRefType = 14735 Other->getType()->castAs<RValueReferenceType>()->getPointeeType(); 14736 14737 // Our location for everything implicitly-generated. 14738 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid() 14739 ? MoveAssignOperator->getEndLoc() 14740 : MoveAssignOperator->getLocation(); 14741 14742 // Builds a reference to the "other" object. 14743 RefBuilder OtherRef(Other, OtherRefType); 14744 // Cast to rvalue. 14745 MoveCastBuilder MoveOther(OtherRef); 14746 14747 // Builds the "this" pointer. 14748 ThisBuilder This; 14749 14750 // Assign base classes. 14751 bool Invalid = false; 14752 for (auto &Base : ClassDecl->bases()) { 14753 // C++11 [class.copy]p28: 14754 // It is unspecified whether subobjects representing virtual base classes 14755 // are assigned more than once by the implicitly-defined copy assignment 14756 // operator. 14757 // FIXME: Do not assign to a vbase that will be assigned by some other base 14758 // class. For a move-assignment, this can result in the vbase being moved 14759 // multiple times. 14760 14761 // Form the assignment: 14762 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 14763 QualType BaseType = Base.getType().getUnqualifiedType(); 14764 if (!BaseType->isRecordType()) { 14765 Invalid = true; 14766 continue; 14767 } 14768 14769 CXXCastPath BasePath; 14770 BasePath.push_back(&Base); 14771 14772 // Construct the "from" expression, which is an implicit cast to the 14773 // appropriately-qualified base type. 14774 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 14775 14776 // Dereference "this". 14777 DerefBuilder DerefThis(This); 14778 14779 // Implicitly cast "this" to the appropriately-qualified base type. 14780 CastBuilder To(DerefThis, 14781 Context.getQualifiedType( 14782 BaseType, MoveAssignOperator->getMethodQualifiers()), 14783 VK_LValue, BasePath); 14784 14785 // Build the move. 14786 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 14787 To, From, 14788 /*CopyingBaseSubobject=*/true, 14789 /*Copying=*/false); 14790 if (Move.isInvalid()) { 14791 MoveAssignOperator->setInvalidDecl(); 14792 return; 14793 } 14794 14795 // Success! Record the move. 14796 Statements.push_back(Move.getAs<Expr>()); 14797 } 14798 14799 // Assign non-static members. 14800 for (auto *Field : ClassDecl->fields()) { 14801 // FIXME: We should form some kind of AST representation for the implied 14802 // memcpy in a union copy operation. 14803 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 14804 continue; 14805 14806 if (Field->isInvalidDecl()) { 14807 Invalid = true; 14808 continue; 14809 } 14810 14811 // Check for members of reference type; we can't move those. 14812 if (Field->getType()->isReferenceType()) { 14813 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14814 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 14815 Diag(Field->getLocation(), diag::note_declared_at); 14816 Invalid = true; 14817 continue; 14818 } 14819 14820 // Check for members of const-qualified, non-class type. 14821 QualType BaseType = Context.getBaseElementType(Field->getType()); 14822 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 14823 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14824 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 14825 Diag(Field->getLocation(), diag::note_declared_at); 14826 Invalid = true; 14827 continue; 14828 } 14829 14830 // Suppress assigning zero-width bitfields. 14831 if (Field->isZeroLengthBitField(Context)) 14832 continue; 14833 14834 QualType FieldType = Field->getType().getNonReferenceType(); 14835 if (FieldType->isIncompleteArrayType()) { 14836 assert(ClassDecl->hasFlexibleArrayMember() && 14837 "Incomplete array type is not valid"); 14838 continue; 14839 } 14840 14841 // Build references to the field in the object we're copying from and to. 14842 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 14843 LookupMemberName); 14844 MemberLookup.addDecl(Field); 14845 MemberLookup.resolveKind(); 14846 MemberBuilder From(MoveOther, OtherRefType, 14847 /*IsArrow=*/false, MemberLookup); 14848 MemberBuilder To(This, getCurrentThisType(), 14849 /*IsArrow=*/true, MemberLookup); 14850 14851 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 14852 "Member reference with rvalue base must be rvalue except for reference " 14853 "members, which aren't allowed for move assignment."); 14854 14855 // Build the move of this field. 14856 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 14857 To, From, 14858 /*CopyingBaseSubobject=*/false, 14859 /*Copying=*/false); 14860 if (Move.isInvalid()) { 14861 MoveAssignOperator->setInvalidDecl(); 14862 return; 14863 } 14864 14865 // Success! Record the copy. 14866 Statements.push_back(Move.getAs<Stmt>()); 14867 } 14868 14869 if (!Invalid) { 14870 // Add a "return *this;" 14871 ExprResult ThisObj = 14872 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 14873 14874 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 14875 if (Return.isInvalid()) 14876 Invalid = true; 14877 else 14878 Statements.push_back(Return.getAs<Stmt>()); 14879 } 14880 14881 if (Invalid) { 14882 MoveAssignOperator->setInvalidDecl(); 14883 return; 14884 } 14885 14886 StmtResult Body; 14887 { 14888 CompoundScopeRAII CompoundScope(*this); 14889 Body = ActOnCompoundStmt(Loc, Loc, Statements, 14890 /*isStmtExpr=*/false); 14891 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 14892 } 14893 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 14894 MoveAssignOperator->markUsed(Context); 14895 14896 if (ASTMutationListener *L = getASTMutationListener()) { 14897 L->CompletedImplicitDefinition(MoveAssignOperator); 14898 } 14899 } 14900 14901 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 14902 CXXRecordDecl *ClassDecl) { 14903 // C++ [class.copy]p4: 14904 // If the class definition does not explicitly declare a copy 14905 // constructor, one is declared implicitly. 14906 assert(ClassDecl->needsImplicitCopyConstructor()); 14907 14908 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 14909 if (DSM.isAlreadyBeingDeclared()) 14910 return nullptr; 14911 14912 QualType ClassType = Context.getTypeDeclType(ClassDecl); 14913 QualType ArgType = ClassType; 14914 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 14915 if (Const) 14916 ArgType = ArgType.withConst(); 14917 14918 LangAS AS = getDefaultCXXMethodAddrSpace(); 14919 if (AS != LangAS::Default) 14920 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 14921 14922 ArgType = Context.getLValueReferenceType(ArgType); 14923 14924 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14925 CXXCopyConstructor, 14926 Const); 14927 14928 DeclarationName Name 14929 = Context.DeclarationNames.getCXXConstructorName( 14930 Context.getCanonicalType(ClassType)); 14931 SourceLocation ClassLoc = ClassDecl->getLocation(); 14932 DeclarationNameInfo NameInfo(Name, ClassLoc); 14933 14934 // An implicitly-declared copy constructor is an inline public 14935 // member of its class. 14936 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 14937 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 14938 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(), 14939 /*isInline=*/true, 14940 /*isImplicitlyDeclared=*/true, 14941 Constexpr ? ConstexprSpecKind::Constexpr 14942 : ConstexprSpecKind::Unspecified); 14943 CopyConstructor->setAccess(AS_public); 14944 CopyConstructor->setDefaulted(); 14945 14946 if (getLangOpts().CUDA) { 14947 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 14948 CopyConstructor, 14949 /* ConstRHS */ Const, 14950 /* Diagnose */ false); 14951 } 14952 14953 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType); 14954 14955 // During template instantiation of special member functions we need a 14956 // reliable TypeSourceInfo for the parameter types in order to allow functions 14957 // to be substituted. 14958 TypeSourceInfo *TSI = nullptr; 14959 if (inTemplateInstantiation() && ClassDecl->isLambda()) 14960 TSI = Context.getTrivialTypeSourceInfo(ArgType); 14961 14962 // Add the parameter to the constructor. 14963 ParmVarDecl *FromParam = 14964 ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc, 14965 /*IdentifierInfo=*/nullptr, ArgType, 14966 /*TInfo=*/TSI, SC_None, nullptr); 14967 CopyConstructor->setParams(FromParam); 14968 14969 CopyConstructor->setTrivial( 14970 ClassDecl->needsOverloadResolutionForCopyConstructor() 14971 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 14972 : ClassDecl->hasTrivialCopyConstructor()); 14973 14974 CopyConstructor->setTrivialForCall( 14975 ClassDecl->hasAttr<TrivialABIAttr>() || 14976 (ClassDecl->needsOverloadResolutionForCopyConstructor() 14977 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor, 14978 TAH_ConsiderTrivialABI) 14979 : ClassDecl->hasTrivialCopyConstructorForCall())); 14980 14981 // Note that we have declared this constructor. 14982 ++getASTContext().NumImplicitCopyConstructorsDeclared; 14983 14984 Scope *S = getScopeForContext(ClassDecl); 14985 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor); 14986 14987 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) { 14988 ClassDecl->setImplicitCopyConstructorIsDeleted(); 14989 SetDeclDeleted(CopyConstructor, ClassLoc); 14990 } 14991 14992 if (S) 14993 PushOnScopeChains(CopyConstructor, S, false); 14994 ClassDecl->addDecl(CopyConstructor); 14995 14996 return CopyConstructor; 14997 } 14998 14999 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 15000 CXXConstructorDecl *CopyConstructor) { 15001 assert((CopyConstructor->isDefaulted() && 15002 CopyConstructor->isCopyConstructor() && 15003 !CopyConstructor->doesThisDeclarationHaveABody() && 15004 !CopyConstructor->isDeleted()) && 15005 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 15006 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl()) 15007 return; 15008 15009 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 15010 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 15011 15012 SynthesizedFunctionScope Scope(*this, CopyConstructor); 15013 15014 // The exception specification is needed because we are defining the 15015 // function. 15016 ResolveExceptionSpec(CurrentLocation, 15017 CopyConstructor->getType()->castAs<FunctionProtoType>()); 15018 MarkVTableUsed(CurrentLocation, ClassDecl); 15019 15020 // Add a context note for diagnostics produced after this point. 15021 Scope.addContextNote(CurrentLocation); 15022 15023 // C++11 [class.copy]p7: 15024 // The [definition of an implicitly declared copy constructor] is 15025 // deprecated if the class has a user-declared copy assignment operator 15026 // or a user-declared destructor. 15027 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 15028 diagnoseDeprecatedCopyOperation(*this, CopyConstructor); 15029 15030 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) { 15031 CopyConstructor->setInvalidDecl(); 15032 } else { 15033 SourceLocation Loc = CopyConstructor->getEndLoc().isValid() 15034 ? CopyConstructor->getEndLoc() 15035 : CopyConstructor->getLocation(); 15036 Sema::CompoundScopeRAII CompoundScope(*this); 15037 CopyConstructor->setBody( 15038 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 15039 CopyConstructor->markUsed(Context); 15040 } 15041 15042 if (ASTMutationListener *L = getASTMutationListener()) { 15043 L->CompletedImplicitDefinition(CopyConstructor); 15044 } 15045 } 15046 15047 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 15048 CXXRecordDecl *ClassDecl) { 15049 assert(ClassDecl->needsImplicitMoveConstructor()); 15050 15051 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 15052 if (DSM.isAlreadyBeingDeclared()) 15053 return nullptr; 15054 15055 QualType ClassType = Context.getTypeDeclType(ClassDecl); 15056 15057 QualType ArgType = ClassType; 15058 LangAS AS = getDefaultCXXMethodAddrSpace(); 15059 if (AS != LangAS::Default) 15060 ArgType = Context.getAddrSpaceQualType(ClassType, AS); 15061 ArgType = Context.getRValueReferenceType(ArgType); 15062 15063 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 15064 CXXMoveConstructor, 15065 false); 15066 15067 DeclarationName Name 15068 = Context.DeclarationNames.getCXXConstructorName( 15069 Context.getCanonicalType(ClassType)); 15070 SourceLocation ClassLoc = ClassDecl->getLocation(); 15071 DeclarationNameInfo NameInfo(Name, ClassLoc); 15072 15073 // C++11 [class.copy]p11: 15074 // An implicitly-declared copy/move constructor is an inline public 15075 // member of its class. 15076 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 15077 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 15078 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(), 15079 /*isInline=*/true, 15080 /*isImplicitlyDeclared=*/true, 15081 Constexpr ? ConstexprSpecKind::Constexpr 15082 : ConstexprSpecKind::Unspecified); 15083 MoveConstructor->setAccess(AS_public); 15084 MoveConstructor->setDefaulted(); 15085 15086 if (getLangOpts().CUDA) { 15087 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 15088 MoveConstructor, 15089 /* ConstRHS */ false, 15090 /* Diagnose */ false); 15091 } 15092 15093 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType); 15094 15095 // Add the parameter to the constructor. 15096 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 15097 ClassLoc, ClassLoc, 15098 /*IdentifierInfo=*/nullptr, 15099 ArgType, /*TInfo=*/nullptr, 15100 SC_None, nullptr); 15101 MoveConstructor->setParams(FromParam); 15102 15103 MoveConstructor->setTrivial( 15104 ClassDecl->needsOverloadResolutionForMoveConstructor() 15105 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 15106 : ClassDecl->hasTrivialMoveConstructor()); 15107 15108 MoveConstructor->setTrivialForCall( 15109 ClassDecl->hasAttr<TrivialABIAttr>() || 15110 (ClassDecl->needsOverloadResolutionForMoveConstructor() 15111 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor, 15112 TAH_ConsiderTrivialABI) 15113 : ClassDecl->hasTrivialMoveConstructorForCall())); 15114 15115 // Note that we have declared this constructor. 15116 ++getASTContext().NumImplicitMoveConstructorsDeclared; 15117 15118 Scope *S = getScopeForContext(ClassDecl); 15119 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor); 15120 15121 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 15122 ClassDecl->setImplicitMoveConstructorIsDeleted(); 15123 SetDeclDeleted(MoveConstructor, ClassLoc); 15124 } 15125 15126 if (S) 15127 PushOnScopeChains(MoveConstructor, S, false); 15128 ClassDecl->addDecl(MoveConstructor); 15129 15130 return MoveConstructor; 15131 } 15132 15133 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 15134 CXXConstructorDecl *MoveConstructor) { 15135 assert((MoveConstructor->isDefaulted() && 15136 MoveConstructor->isMoveConstructor() && 15137 !MoveConstructor->doesThisDeclarationHaveABody() && 15138 !MoveConstructor->isDeleted()) && 15139 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 15140 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl()) 15141 return; 15142 15143 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 15144 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 15145 15146 SynthesizedFunctionScope Scope(*this, MoveConstructor); 15147 15148 // The exception specification is needed because we are defining the 15149 // function. 15150 ResolveExceptionSpec(CurrentLocation, 15151 MoveConstructor->getType()->castAs<FunctionProtoType>()); 15152 MarkVTableUsed(CurrentLocation, ClassDecl); 15153 15154 // Add a context note for diagnostics produced after this point. 15155 Scope.addContextNote(CurrentLocation); 15156 15157 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) { 15158 MoveConstructor->setInvalidDecl(); 15159 } else { 15160 SourceLocation Loc = MoveConstructor->getEndLoc().isValid() 15161 ? MoveConstructor->getEndLoc() 15162 : MoveConstructor->getLocation(); 15163 Sema::CompoundScopeRAII CompoundScope(*this); 15164 MoveConstructor->setBody(ActOnCompoundStmt( 15165 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 15166 MoveConstructor->markUsed(Context); 15167 } 15168 15169 if (ASTMutationListener *L = getASTMutationListener()) { 15170 L->CompletedImplicitDefinition(MoveConstructor); 15171 } 15172 } 15173 15174 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 15175 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 15176 } 15177 15178 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 15179 SourceLocation CurrentLocation, 15180 CXXConversionDecl *Conv) { 15181 SynthesizedFunctionScope Scope(*this, Conv); 15182 assert(!Conv->getReturnType()->isUndeducedType()); 15183 15184 QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType(); 15185 CallingConv CC = 15186 ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv(); 15187 15188 CXXRecordDecl *Lambda = Conv->getParent(); 15189 FunctionDecl *CallOp = Lambda->getLambdaCallOperator(); 15190 FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(CC); 15191 15192 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) { 15193 CallOp = InstantiateFunctionDeclaration( 15194 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 15195 if (!CallOp) 15196 return; 15197 15198 Invoker = InstantiateFunctionDeclaration( 15199 Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 15200 if (!Invoker) 15201 return; 15202 } 15203 15204 if (CallOp->isInvalidDecl()) 15205 return; 15206 15207 // Mark the call operator referenced (and add to pending instantiations 15208 // if necessary). 15209 // For both the conversion and static-invoker template specializations 15210 // we construct their body's in this function, so no need to add them 15211 // to the PendingInstantiations. 15212 MarkFunctionReferenced(CurrentLocation, CallOp); 15213 15214 // Fill in the __invoke function with a dummy implementation. IR generation 15215 // will fill in the actual details. Update its type in case it contained 15216 // an 'auto'. 15217 Invoker->markUsed(Context); 15218 Invoker->setReferenced(); 15219 Invoker->setType(Conv->getReturnType()->getPointeeType()); 15220 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 15221 15222 // Construct the body of the conversion function { return __invoke; }. 15223 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 15224 VK_LValue, Conv->getLocation()); 15225 assert(FunctionRef && "Can't refer to __invoke function?"); 15226 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 15227 Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(), 15228 Conv->getLocation())); 15229 Conv->markUsed(Context); 15230 Conv->setReferenced(); 15231 15232 if (ASTMutationListener *L = getASTMutationListener()) { 15233 L->CompletedImplicitDefinition(Conv); 15234 L->CompletedImplicitDefinition(Invoker); 15235 } 15236 } 15237 15238 15239 15240 void Sema::DefineImplicitLambdaToBlockPointerConversion( 15241 SourceLocation CurrentLocation, 15242 CXXConversionDecl *Conv) 15243 { 15244 assert(!Conv->getParent()->isGenericLambda()); 15245 15246 SynthesizedFunctionScope Scope(*this, Conv); 15247 15248 // Copy-initialize the lambda object as needed to capture it. 15249 Expr *This = ActOnCXXThis(CurrentLocation).get(); 15250 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 15251 15252 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 15253 Conv->getLocation(), 15254 Conv, DerefThis); 15255 15256 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 15257 // behavior. Note that only the general conversion function does this 15258 // (since it's unusable otherwise); in the case where we inline the 15259 // block literal, it has block literal lifetime semantics. 15260 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 15261 BuildBlock = ImplicitCastExpr::Create( 15262 Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject, 15263 BuildBlock.get(), nullptr, VK_PRValue, FPOptionsOverride()); 15264 15265 if (BuildBlock.isInvalid()) { 15266 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 15267 Conv->setInvalidDecl(); 15268 return; 15269 } 15270 15271 // Create the return statement that returns the block from the conversion 15272 // function. 15273 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 15274 if (Return.isInvalid()) { 15275 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 15276 Conv->setInvalidDecl(); 15277 return; 15278 } 15279 15280 // Set the body of the conversion function. 15281 Stmt *ReturnS = Return.get(); 15282 Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(), 15283 Conv->getLocation())); 15284 Conv->markUsed(Context); 15285 15286 // We're done; notify the mutation listener, if any. 15287 if (ASTMutationListener *L = getASTMutationListener()) { 15288 L->CompletedImplicitDefinition(Conv); 15289 } 15290 } 15291 15292 /// Determine whether the given list arguments contains exactly one 15293 /// "real" (non-default) argument. 15294 static bool hasOneRealArgument(MultiExprArg Args) { 15295 switch (Args.size()) { 15296 case 0: 15297 return false; 15298 15299 default: 15300 if (!Args[1]->isDefaultArgument()) 15301 return false; 15302 15303 LLVM_FALLTHROUGH; 15304 case 1: 15305 return !Args[0]->isDefaultArgument(); 15306 } 15307 15308 return false; 15309 } 15310 15311 ExprResult 15312 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 15313 NamedDecl *FoundDecl, 15314 CXXConstructorDecl *Constructor, 15315 MultiExprArg ExprArgs, 15316 bool HadMultipleCandidates, 15317 bool IsListInitialization, 15318 bool IsStdInitListInitialization, 15319 bool RequiresZeroInit, 15320 unsigned ConstructKind, 15321 SourceRange ParenRange) { 15322 bool Elidable = false; 15323 15324 // C++0x [class.copy]p34: 15325 // When certain criteria are met, an implementation is allowed to 15326 // omit the copy/move construction of a class object, even if the 15327 // copy/move constructor and/or destructor for the object have 15328 // side effects. [...] 15329 // - when a temporary class object that has not been bound to a 15330 // reference (12.2) would be copied/moved to a class object 15331 // with the same cv-unqualified type, the copy/move operation 15332 // can be omitted by constructing the temporary object 15333 // directly into the target of the omitted copy/move 15334 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor && 15335 // FIXME: Converting constructors should also be accepted. 15336 // But to fix this, the logic that digs down into a CXXConstructExpr 15337 // to find the source object needs to handle it. 15338 // Right now it assumes the source object is passed directly as the 15339 // first argument. 15340 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 15341 Expr *SubExpr = ExprArgs[0]; 15342 // FIXME: Per above, this is also incorrect if we want to accept 15343 // converting constructors, as isTemporaryObject will 15344 // reject temporaries with different type from the 15345 // CXXRecord itself. 15346 Elidable = SubExpr->isTemporaryObject( 15347 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 15348 } 15349 15350 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, 15351 FoundDecl, Constructor, 15352 Elidable, ExprArgs, HadMultipleCandidates, 15353 IsListInitialization, 15354 IsStdInitListInitialization, RequiresZeroInit, 15355 ConstructKind, ParenRange); 15356 } 15357 15358 ExprResult 15359 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 15360 NamedDecl *FoundDecl, 15361 CXXConstructorDecl *Constructor, 15362 bool Elidable, 15363 MultiExprArg ExprArgs, 15364 bool HadMultipleCandidates, 15365 bool IsListInitialization, 15366 bool IsStdInitListInitialization, 15367 bool RequiresZeroInit, 15368 unsigned ConstructKind, 15369 SourceRange ParenRange) { 15370 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) { 15371 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow); 15372 if (DiagnoseUseOfDecl(Constructor, ConstructLoc)) 15373 return ExprError(); 15374 } 15375 15376 return BuildCXXConstructExpr( 15377 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs, 15378 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 15379 RequiresZeroInit, ConstructKind, ParenRange); 15380 } 15381 15382 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 15383 /// including handling of its default argument expressions. 15384 ExprResult 15385 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 15386 CXXConstructorDecl *Constructor, 15387 bool Elidable, 15388 MultiExprArg ExprArgs, 15389 bool HadMultipleCandidates, 15390 bool IsListInitialization, 15391 bool IsStdInitListInitialization, 15392 bool RequiresZeroInit, 15393 unsigned ConstructKind, 15394 SourceRange ParenRange) { 15395 assert(declaresSameEntity( 15396 Constructor->getParent(), 15397 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && 15398 "given constructor for wrong type"); 15399 MarkFunctionReferenced(ConstructLoc, Constructor); 15400 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor)) 15401 return ExprError(); 15402 if (getLangOpts().SYCLIsDevice && 15403 !checkSYCLDeviceFunction(ConstructLoc, Constructor)) 15404 return ExprError(); 15405 15406 return CheckForImmediateInvocation( 15407 CXXConstructExpr::Create( 15408 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs, 15409 HadMultipleCandidates, IsListInitialization, 15410 IsStdInitListInitialization, RequiresZeroInit, 15411 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 15412 ParenRange), 15413 Constructor); 15414 } 15415 15416 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 15417 assert(Field->hasInClassInitializer()); 15418 15419 // If we already have the in-class initializer nothing needs to be done. 15420 if (Field->getInClassInitializer()) 15421 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext); 15422 15423 // If we might have already tried and failed to instantiate, don't try again. 15424 if (Field->isInvalidDecl()) 15425 return ExprError(); 15426 15427 // Maybe we haven't instantiated the in-class initializer. Go check the 15428 // pattern FieldDecl to see if it has one. 15429 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 15430 15431 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 15432 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 15433 DeclContext::lookup_result Lookup = 15434 ClassPattern->lookup(Field->getDeclName()); 15435 15436 FieldDecl *Pattern = nullptr; 15437 for (auto L : Lookup) { 15438 if (isa<FieldDecl>(L)) { 15439 Pattern = cast<FieldDecl>(L); 15440 break; 15441 } 15442 } 15443 assert(Pattern && "We must have set the Pattern!"); 15444 15445 if (!Pattern->hasInClassInitializer() || 15446 InstantiateInClassInitializer(Loc, Field, Pattern, 15447 getTemplateInstantiationArgs(Field))) { 15448 // Don't diagnose this again. 15449 Field->setInvalidDecl(); 15450 return ExprError(); 15451 } 15452 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext); 15453 } 15454 15455 // DR1351: 15456 // If the brace-or-equal-initializer of a non-static data member 15457 // invokes a defaulted default constructor of its class or of an 15458 // enclosing class in a potentially evaluated subexpression, the 15459 // program is ill-formed. 15460 // 15461 // This resolution is unworkable: the exception specification of the 15462 // default constructor can be needed in an unevaluated context, in 15463 // particular, in the operand of a noexcept-expression, and we can be 15464 // unable to compute an exception specification for an enclosed class. 15465 // 15466 // Any attempt to resolve the exception specification of a defaulted default 15467 // constructor before the initializer is lexically complete will ultimately 15468 // come here at which point we can diagnose it. 15469 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 15470 Diag(Loc, diag::err_default_member_initializer_not_yet_parsed) 15471 << OutermostClass << Field; 15472 Diag(Field->getEndLoc(), 15473 diag::note_default_member_initializer_not_yet_parsed); 15474 // Recover by marking the field invalid, unless we're in a SFINAE context. 15475 if (!isSFINAEContext()) 15476 Field->setInvalidDecl(); 15477 return ExprError(); 15478 } 15479 15480 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 15481 if (VD->isInvalidDecl()) return; 15482 // If initializing the variable failed, don't also diagnose problems with 15483 // the destructor, they're likely related. 15484 if (VD->getInit() && VD->getInit()->containsErrors()) 15485 return; 15486 15487 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 15488 if (ClassDecl->isInvalidDecl()) return; 15489 if (ClassDecl->hasIrrelevantDestructor()) return; 15490 if (ClassDecl->isDependentContext()) return; 15491 15492 if (VD->isNoDestroy(getASTContext())) 15493 return; 15494 15495 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 15496 15497 // If this is an array, we'll require the destructor during initialization, so 15498 // we can skip over this. We still want to emit exit-time destructor warnings 15499 // though. 15500 if (!VD->getType()->isArrayType()) { 15501 MarkFunctionReferenced(VD->getLocation(), Destructor); 15502 CheckDestructorAccess(VD->getLocation(), Destructor, 15503 PDiag(diag::err_access_dtor_var) 15504 << VD->getDeclName() << VD->getType()); 15505 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 15506 } 15507 15508 if (Destructor->isTrivial()) return; 15509 15510 // If the destructor is constexpr, check whether the variable has constant 15511 // destruction now. 15512 if (Destructor->isConstexpr()) { 15513 bool HasConstantInit = false; 15514 if (VD->getInit() && !VD->getInit()->isValueDependent()) 15515 HasConstantInit = VD->evaluateValue(); 15516 SmallVector<PartialDiagnosticAt, 8> Notes; 15517 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() && 15518 HasConstantInit) { 15519 Diag(VD->getLocation(), 15520 diag::err_constexpr_var_requires_const_destruction) << VD; 15521 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 15522 Diag(Notes[I].first, Notes[I].second); 15523 } 15524 } 15525 15526 if (!VD->hasGlobalStorage()) return; 15527 15528 // Emit warning for non-trivial dtor in global scope (a real global, 15529 // class-static, function-static). 15530 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 15531 15532 // TODO: this should be re-enabled for static locals by !CXAAtExit 15533 if (!VD->isStaticLocal()) 15534 Diag(VD->getLocation(), diag::warn_global_destructor); 15535 } 15536 15537 /// Given a constructor and the set of arguments provided for the 15538 /// constructor, convert the arguments and add any required default arguments 15539 /// to form a proper call to this constructor. 15540 /// 15541 /// \returns true if an error occurred, false otherwise. 15542 bool Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 15543 QualType DeclInitType, MultiExprArg ArgsPtr, 15544 SourceLocation Loc, 15545 SmallVectorImpl<Expr *> &ConvertedArgs, 15546 bool AllowExplicit, 15547 bool IsListInitialization) { 15548 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 15549 unsigned NumArgs = ArgsPtr.size(); 15550 Expr **Args = ArgsPtr.data(); 15551 15552 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>(); 15553 unsigned NumParams = Proto->getNumParams(); 15554 15555 // If too few arguments are available, we'll fill in the rest with defaults. 15556 if (NumArgs < NumParams) 15557 ConvertedArgs.reserve(NumParams); 15558 else 15559 ConvertedArgs.reserve(NumArgs); 15560 15561 VariadicCallType CallType = 15562 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 15563 SmallVector<Expr *, 8> AllArgs; 15564 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 15565 Proto, 0, 15566 llvm::makeArrayRef(Args, NumArgs), 15567 AllArgs, 15568 CallType, AllowExplicit, 15569 IsListInitialization); 15570 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 15571 15572 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 15573 15574 CheckConstructorCall(Constructor, DeclInitType, 15575 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 15576 Proto, Loc); 15577 15578 return Invalid; 15579 } 15580 15581 static inline bool 15582 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 15583 const FunctionDecl *FnDecl) { 15584 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 15585 if (isa<NamespaceDecl>(DC)) { 15586 return SemaRef.Diag(FnDecl->getLocation(), 15587 diag::err_operator_new_delete_declared_in_namespace) 15588 << FnDecl->getDeclName(); 15589 } 15590 15591 if (isa<TranslationUnitDecl>(DC) && 15592 FnDecl->getStorageClass() == SC_Static) { 15593 return SemaRef.Diag(FnDecl->getLocation(), 15594 diag::err_operator_new_delete_declared_static) 15595 << FnDecl->getDeclName(); 15596 } 15597 15598 return false; 15599 } 15600 15601 static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef, 15602 const PointerType *PtrTy) { 15603 auto &Ctx = SemaRef.Context; 15604 Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers(); 15605 PtrQuals.removeAddressSpace(); 15606 return Ctx.getPointerType(Ctx.getCanonicalType(Ctx.getQualifiedType( 15607 PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals))); 15608 } 15609 15610 static inline bool 15611 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 15612 CanQualType ExpectedResultType, 15613 CanQualType ExpectedFirstParamType, 15614 unsigned DependentParamTypeDiag, 15615 unsigned InvalidParamTypeDiag) { 15616 QualType ResultType = 15617 FnDecl->getType()->castAs<FunctionType>()->getReturnType(); 15618 15619 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 15620 // The operator is valid on any address space for OpenCL. 15621 // Drop address space from actual and expected result types. 15622 if (const auto *PtrTy = ResultType->getAs<PointerType>()) 15623 ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 15624 15625 if (auto ExpectedPtrTy = ExpectedResultType->getAs<PointerType>()) 15626 ExpectedResultType = RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy); 15627 } 15628 15629 // Check that the result type is what we expect. 15630 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) { 15631 // Reject even if the type is dependent; an operator delete function is 15632 // required to have a non-dependent result type. 15633 return SemaRef.Diag( 15634 FnDecl->getLocation(), 15635 ResultType->isDependentType() 15636 ? diag::err_operator_new_delete_dependent_result_type 15637 : diag::err_operator_new_delete_invalid_result_type) 15638 << FnDecl->getDeclName() << ExpectedResultType; 15639 } 15640 15641 // A function template must have at least 2 parameters. 15642 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 15643 return SemaRef.Diag(FnDecl->getLocation(), 15644 diag::err_operator_new_delete_template_too_few_parameters) 15645 << FnDecl->getDeclName(); 15646 15647 // The function decl must have at least 1 parameter. 15648 if (FnDecl->getNumParams() == 0) 15649 return SemaRef.Diag(FnDecl->getLocation(), 15650 diag::err_operator_new_delete_too_few_parameters) 15651 << FnDecl->getDeclName(); 15652 15653 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 15654 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 15655 // The operator is valid on any address space for OpenCL. 15656 // Drop address space from actual and expected first parameter types. 15657 if (const auto *PtrTy = 15658 FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) 15659 FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 15660 15661 if (auto ExpectedPtrTy = ExpectedFirstParamType->getAs<PointerType>()) 15662 ExpectedFirstParamType = 15663 RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy); 15664 } 15665 15666 // Check that the first parameter type is what we expect. 15667 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 15668 ExpectedFirstParamType) { 15669 // The first parameter type is not allowed to be dependent. As a tentative 15670 // DR resolution, we allow a dependent parameter type if it is the right 15671 // type anyway, to allow destroying operator delete in class templates. 15672 return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType() 15673 ? DependentParamTypeDiag 15674 : InvalidParamTypeDiag) 15675 << FnDecl->getDeclName() << ExpectedFirstParamType; 15676 } 15677 15678 return false; 15679 } 15680 15681 static bool 15682 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 15683 // C++ [basic.stc.dynamic.allocation]p1: 15684 // A program is ill-formed if an allocation function is declared in a 15685 // namespace scope other than global scope or declared static in global 15686 // scope. 15687 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 15688 return true; 15689 15690 CanQualType SizeTy = 15691 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 15692 15693 // C++ [basic.stc.dynamic.allocation]p1: 15694 // The return type shall be void*. The first parameter shall have type 15695 // std::size_t. 15696 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 15697 SizeTy, 15698 diag::err_operator_new_dependent_param_type, 15699 diag::err_operator_new_param_type)) 15700 return true; 15701 15702 // C++ [basic.stc.dynamic.allocation]p1: 15703 // The first parameter shall not have an associated default argument. 15704 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 15705 return SemaRef.Diag(FnDecl->getLocation(), 15706 diag::err_operator_new_default_arg) 15707 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 15708 15709 return false; 15710 } 15711 15712 static bool 15713 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 15714 // C++ [basic.stc.dynamic.deallocation]p1: 15715 // A program is ill-formed if deallocation functions are declared in a 15716 // namespace scope other than global scope or declared static in global 15717 // scope. 15718 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 15719 return true; 15720 15721 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl); 15722 15723 // C++ P0722: 15724 // Within a class C, the first parameter of a destroying operator delete 15725 // shall be of type C *. The first parameter of any other deallocation 15726 // function shall be of type void *. 15727 CanQualType ExpectedFirstParamType = 15728 MD && MD->isDestroyingOperatorDelete() 15729 ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType( 15730 SemaRef.Context.getRecordType(MD->getParent()))) 15731 : SemaRef.Context.VoidPtrTy; 15732 15733 // C++ [basic.stc.dynamic.deallocation]p2: 15734 // Each deallocation function shall return void 15735 if (CheckOperatorNewDeleteTypes( 15736 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType, 15737 diag::err_operator_delete_dependent_param_type, 15738 diag::err_operator_delete_param_type)) 15739 return true; 15740 15741 // C++ P0722: 15742 // A destroying operator delete shall be a usual deallocation function. 15743 if (MD && !MD->getParent()->isDependentContext() && 15744 MD->isDestroyingOperatorDelete() && 15745 !SemaRef.isUsualDeallocationFunction(MD)) { 15746 SemaRef.Diag(MD->getLocation(), 15747 diag::err_destroying_operator_delete_not_usual); 15748 return true; 15749 } 15750 15751 return false; 15752 } 15753 15754 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 15755 /// of this overloaded operator is well-formed. If so, returns false; 15756 /// otherwise, emits appropriate diagnostics and returns true. 15757 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 15758 assert(FnDecl && FnDecl->isOverloadedOperator() && 15759 "Expected an overloaded operator declaration"); 15760 15761 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 15762 15763 // C++ [over.oper]p5: 15764 // The allocation and deallocation functions, operator new, 15765 // operator new[], operator delete and operator delete[], are 15766 // described completely in 3.7.3. The attributes and restrictions 15767 // found in the rest of this subclause do not apply to them unless 15768 // explicitly stated in 3.7.3. 15769 if (Op == OO_Delete || Op == OO_Array_Delete) 15770 return CheckOperatorDeleteDeclaration(*this, FnDecl); 15771 15772 if (Op == OO_New || Op == OO_Array_New) 15773 return CheckOperatorNewDeclaration(*this, FnDecl); 15774 15775 // C++ [over.oper]p6: 15776 // An operator function shall either be a non-static member 15777 // function or be a non-member function and have at least one 15778 // parameter whose type is a class, a reference to a class, an 15779 // enumeration, or a reference to an enumeration. 15780 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 15781 if (MethodDecl->isStatic()) 15782 return Diag(FnDecl->getLocation(), 15783 diag::err_operator_overload_static) << FnDecl->getDeclName(); 15784 } else { 15785 bool ClassOrEnumParam = false; 15786 for (auto Param : FnDecl->parameters()) { 15787 QualType ParamType = Param->getType().getNonReferenceType(); 15788 if (ParamType->isDependentType() || ParamType->isRecordType() || 15789 ParamType->isEnumeralType()) { 15790 ClassOrEnumParam = true; 15791 break; 15792 } 15793 } 15794 15795 if (!ClassOrEnumParam) 15796 return Diag(FnDecl->getLocation(), 15797 diag::err_operator_overload_needs_class_or_enum) 15798 << FnDecl->getDeclName(); 15799 } 15800 15801 // C++ [over.oper]p8: 15802 // An operator function cannot have default arguments (8.3.6), 15803 // except where explicitly stated below. 15804 // 15805 // Only the function-call operator allows default arguments 15806 // (C++ [over.call]p1). 15807 if (Op != OO_Call) { 15808 for (auto Param : FnDecl->parameters()) { 15809 if (Param->hasDefaultArg()) 15810 return Diag(Param->getLocation(), 15811 diag::err_operator_overload_default_arg) 15812 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 15813 } 15814 } 15815 15816 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 15817 { false, false, false } 15818 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 15819 , { Unary, Binary, MemberOnly } 15820 #include "clang/Basic/OperatorKinds.def" 15821 }; 15822 15823 bool CanBeUnaryOperator = OperatorUses[Op][0]; 15824 bool CanBeBinaryOperator = OperatorUses[Op][1]; 15825 bool MustBeMemberOperator = OperatorUses[Op][2]; 15826 15827 // C++ [over.oper]p8: 15828 // [...] Operator functions cannot have more or fewer parameters 15829 // than the number required for the corresponding operator, as 15830 // described in the rest of this subclause. 15831 unsigned NumParams = FnDecl->getNumParams() 15832 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 15833 if (Op != OO_Call && 15834 ((NumParams == 1 && !CanBeUnaryOperator) || 15835 (NumParams == 2 && !CanBeBinaryOperator) || 15836 (NumParams < 1) || (NumParams > 2))) { 15837 // We have the wrong number of parameters. 15838 unsigned ErrorKind; 15839 if (CanBeUnaryOperator && CanBeBinaryOperator) { 15840 ErrorKind = 2; // 2 -> unary or binary. 15841 } else if (CanBeUnaryOperator) { 15842 ErrorKind = 0; // 0 -> unary 15843 } else { 15844 assert(CanBeBinaryOperator && 15845 "All non-call overloaded operators are unary or binary!"); 15846 ErrorKind = 1; // 1 -> binary 15847 } 15848 15849 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 15850 << FnDecl->getDeclName() << NumParams << ErrorKind; 15851 } 15852 15853 // Overloaded operators other than operator() cannot be variadic. 15854 if (Op != OO_Call && 15855 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) { 15856 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 15857 << FnDecl->getDeclName(); 15858 } 15859 15860 // Some operators must be non-static member functions. 15861 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 15862 return Diag(FnDecl->getLocation(), 15863 diag::err_operator_overload_must_be_member) 15864 << FnDecl->getDeclName(); 15865 } 15866 15867 // C++ [over.inc]p1: 15868 // The user-defined function called operator++ implements the 15869 // prefix and postfix ++ operator. If this function is a member 15870 // function with no parameters, or a non-member function with one 15871 // parameter of class or enumeration type, it defines the prefix 15872 // increment operator ++ for objects of that type. If the function 15873 // is a member function with one parameter (which shall be of type 15874 // int) or a non-member function with two parameters (the second 15875 // of which shall be of type int), it defines the postfix 15876 // increment operator ++ for objects of that type. 15877 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 15878 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 15879 QualType ParamType = LastParam->getType(); 15880 15881 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 15882 !ParamType->isDependentType()) 15883 return Diag(LastParam->getLocation(), 15884 diag::err_operator_overload_post_incdec_must_be_int) 15885 << LastParam->getType() << (Op == OO_MinusMinus); 15886 } 15887 15888 return false; 15889 } 15890 15891 static bool 15892 checkLiteralOperatorTemplateParameterList(Sema &SemaRef, 15893 FunctionTemplateDecl *TpDecl) { 15894 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters(); 15895 15896 // Must have one or two template parameters. 15897 if (TemplateParams->size() == 1) { 15898 NonTypeTemplateParmDecl *PmDecl = 15899 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0)); 15900 15901 // The template parameter must be a char parameter pack. 15902 if (PmDecl && PmDecl->isTemplateParameterPack() && 15903 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy)) 15904 return false; 15905 15906 // C++20 [over.literal]p5: 15907 // A string literal operator template is a literal operator template 15908 // whose template-parameter-list comprises a single non-type 15909 // template-parameter of class type. 15910 // 15911 // As a DR resolution, we also allow placeholders for deduced class 15912 // template specializations. 15913 if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl && 15914 !PmDecl->isTemplateParameterPack() && 15915 (PmDecl->getType()->isRecordType() || 15916 PmDecl->getType()->getAs<DeducedTemplateSpecializationType>())) 15917 return false; 15918 } else if (TemplateParams->size() == 2) { 15919 TemplateTypeParmDecl *PmType = 15920 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0)); 15921 NonTypeTemplateParmDecl *PmArgs = 15922 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1)); 15923 15924 // The second template parameter must be a parameter pack with the 15925 // first template parameter as its type. 15926 if (PmType && PmArgs && !PmType->isTemplateParameterPack() && 15927 PmArgs->isTemplateParameterPack()) { 15928 const TemplateTypeParmType *TArgs = 15929 PmArgs->getType()->getAs<TemplateTypeParmType>(); 15930 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 15931 TArgs->getIndex() == PmType->getIndex()) { 15932 if (!SemaRef.inTemplateInstantiation()) 15933 SemaRef.Diag(TpDecl->getLocation(), 15934 diag::ext_string_literal_operator_template); 15935 return false; 15936 } 15937 } 15938 } 15939 15940 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(), 15941 diag::err_literal_operator_template) 15942 << TpDecl->getTemplateParameters()->getSourceRange(); 15943 return true; 15944 } 15945 15946 /// CheckLiteralOperatorDeclaration - Check whether the declaration 15947 /// of this literal operator function is well-formed. If so, returns 15948 /// false; otherwise, emits appropriate diagnostics and returns true. 15949 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 15950 if (isa<CXXMethodDecl>(FnDecl)) { 15951 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 15952 << FnDecl->getDeclName(); 15953 return true; 15954 } 15955 15956 if (FnDecl->isExternC()) { 15957 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 15958 if (const LinkageSpecDecl *LSD = 15959 FnDecl->getDeclContext()->getExternCContext()) 15960 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here); 15961 return true; 15962 } 15963 15964 // This might be the definition of a literal operator template. 15965 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 15966 15967 // This might be a specialization of a literal operator template. 15968 if (!TpDecl) 15969 TpDecl = FnDecl->getPrimaryTemplate(); 15970 15971 // template <char...> type operator "" name() and 15972 // template <class T, T...> type operator "" name() are the only valid 15973 // template signatures, and the only valid signatures with no parameters. 15974 // 15975 // C++20 also allows template <SomeClass T> type operator "" name(). 15976 if (TpDecl) { 15977 if (FnDecl->param_size() != 0) { 15978 Diag(FnDecl->getLocation(), 15979 diag::err_literal_operator_template_with_params); 15980 return true; 15981 } 15982 15983 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl)) 15984 return true; 15985 15986 } else if (FnDecl->param_size() == 1) { 15987 const ParmVarDecl *Param = FnDecl->getParamDecl(0); 15988 15989 QualType ParamType = Param->getType().getUnqualifiedType(); 15990 15991 // Only unsigned long long int, long double, any character type, and const 15992 // char * are allowed as the only parameters. 15993 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) || 15994 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) || 15995 Context.hasSameType(ParamType, Context.CharTy) || 15996 Context.hasSameType(ParamType, Context.WideCharTy) || 15997 Context.hasSameType(ParamType, Context.Char8Ty) || 15998 Context.hasSameType(ParamType, Context.Char16Ty) || 15999 Context.hasSameType(ParamType, Context.Char32Ty)) { 16000 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) { 16001 QualType InnerType = Ptr->getPointeeType(); 16002 16003 // Pointer parameter must be a const char *. 16004 if (!(Context.hasSameType(InnerType.getUnqualifiedType(), 16005 Context.CharTy) && 16006 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) { 16007 Diag(Param->getSourceRange().getBegin(), 16008 diag::err_literal_operator_param) 16009 << ParamType << "'const char *'" << Param->getSourceRange(); 16010 return true; 16011 } 16012 16013 } else if (ParamType->isRealFloatingType()) { 16014 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 16015 << ParamType << Context.LongDoubleTy << Param->getSourceRange(); 16016 return true; 16017 16018 } else if (ParamType->isIntegerType()) { 16019 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 16020 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange(); 16021 return true; 16022 16023 } else { 16024 Diag(Param->getSourceRange().getBegin(), 16025 diag::err_literal_operator_invalid_param) 16026 << ParamType << Param->getSourceRange(); 16027 return true; 16028 } 16029 16030 } else if (FnDecl->param_size() == 2) { 16031 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 16032 16033 // First, verify that the first parameter is correct. 16034 16035 QualType FirstParamType = (*Param)->getType().getUnqualifiedType(); 16036 16037 // Two parameter function must have a pointer to const as a 16038 // first parameter; let's strip those qualifiers. 16039 const PointerType *PT = FirstParamType->getAs<PointerType>(); 16040 16041 if (!PT) { 16042 Diag((*Param)->getSourceRange().getBegin(), 16043 diag::err_literal_operator_param) 16044 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 16045 return true; 16046 } 16047 16048 QualType PointeeType = PT->getPointeeType(); 16049 // First parameter must be const 16050 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) { 16051 Diag((*Param)->getSourceRange().getBegin(), 16052 diag::err_literal_operator_param) 16053 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 16054 return true; 16055 } 16056 16057 QualType InnerType = PointeeType.getUnqualifiedType(); 16058 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and 16059 // const char32_t* are allowed as the first parameter to a two-parameter 16060 // function 16061 if (!(Context.hasSameType(InnerType, Context.CharTy) || 16062 Context.hasSameType(InnerType, Context.WideCharTy) || 16063 Context.hasSameType(InnerType, Context.Char8Ty) || 16064 Context.hasSameType(InnerType, Context.Char16Ty) || 16065 Context.hasSameType(InnerType, Context.Char32Ty))) { 16066 Diag((*Param)->getSourceRange().getBegin(), 16067 diag::err_literal_operator_param) 16068 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 16069 return true; 16070 } 16071 16072 // Move on to the second and final parameter. 16073 ++Param; 16074 16075 // The second parameter must be a std::size_t. 16076 QualType SecondParamType = (*Param)->getType().getUnqualifiedType(); 16077 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) { 16078 Diag((*Param)->getSourceRange().getBegin(), 16079 diag::err_literal_operator_param) 16080 << SecondParamType << Context.getSizeType() 16081 << (*Param)->getSourceRange(); 16082 return true; 16083 } 16084 } else { 16085 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count); 16086 return true; 16087 } 16088 16089 // Parameters are good. 16090 16091 // A parameter-declaration-clause containing a default argument is not 16092 // equivalent to any of the permitted forms. 16093 for (auto Param : FnDecl->parameters()) { 16094 if (Param->hasDefaultArg()) { 16095 Diag(Param->getDefaultArgRange().getBegin(), 16096 diag::err_literal_operator_default_argument) 16097 << Param->getDefaultArgRange(); 16098 break; 16099 } 16100 } 16101 16102 StringRef LiteralName 16103 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 16104 if (LiteralName[0] != '_' && 16105 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) { 16106 // C++11 [usrlit.suffix]p1: 16107 // Literal suffix identifiers that do not start with an underscore 16108 // are reserved for future standardization. 16109 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 16110 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 16111 } 16112 16113 return false; 16114 } 16115 16116 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 16117 /// linkage specification, including the language and (if present) 16118 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 16119 /// language string literal. LBraceLoc, if valid, provides the location of 16120 /// the '{' brace. Otherwise, this linkage specification does not 16121 /// have any braces. 16122 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 16123 Expr *LangStr, 16124 SourceLocation LBraceLoc) { 16125 StringLiteral *Lit = cast<StringLiteral>(LangStr); 16126 if (!Lit->isAscii()) { 16127 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 16128 << LangStr->getSourceRange(); 16129 return nullptr; 16130 } 16131 16132 StringRef Lang = Lit->getString(); 16133 LinkageSpecDecl::LanguageIDs Language; 16134 if (Lang == "C") 16135 Language = LinkageSpecDecl::lang_c; 16136 else if (Lang == "C++") 16137 Language = LinkageSpecDecl::lang_cxx; 16138 else { 16139 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 16140 << LangStr->getSourceRange(); 16141 return nullptr; 16142 } 16143 16144 // FIXME: Add all the various semantics of linkage specifications 16145 16146 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 16147 LangStr->getExprLoc(), Language, 16148 LBraceLoc.isValid()); 16149 CurContext->addDecl(D); 16150 PushDeclContext(S, D); 16151 return D; 16152 } 16153 16154 /// ActOnFinishLinkageSpecification - Complete the definition of 16155 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 16156 /// valid, it's the position of the closing '}' brace in a linkage 16157 /// specification that uses braces. 16158 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 16159 Decl *LinkageSpec, 16160 SourceLocation RBraceLoc) { 16161 if (RBraceLoc.isValid()) { 16162 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 16163 LSDecl->setRBraceLoc(RBraceLoc); 16164 } 16165 PopDeclContext(); 16166 return LinkageSpec; 16167 } 16168 16169 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 16170 const ParsedAttributesView &AttrList, 16171 SourceLocation SemiLoc) { 16172 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 16173 // Attribute declarations appertain to empty declaration so we handle 16174 // them here. 16175 ProcessDeclAttributeList(S, ED, AttrList); 16176 16177 CurContext->addDecl(ED); 16178 return ED; 16179 } 16180 16181 /// Perform semantic analysis for the variable declaration that 16182 /// occurs within a C++ catch clause, returning the newly-created 16183 /// variable. 16184 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 16185 TypeSourceInfo *TInfo, 16186 SourceLocation StartLoc, 16187 SourceLocation Loc, 16188 IdentifierInfo *Name) { 16189 bool Invalid = false; 16190 QualType ExDeclType = TInfo->getType(); 16191 16192 // Arrays and functions decay. 16193 if (ExDeclType->isArrayType()) 16194 ExDeclType = Context.getArrayDecayedType(ExDeclType); 16195 else if (ExDeclType->isFunctionType()) 16196 ExDeclType = Context.getPointerType(ExDeclType); 16197 16198 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 16199 // The exception-declaration shall not denote a pointer or reference to an 16200 // incomplete type, other than [cv] void*. 16201 // N2844 forbids rvalue references. 16202 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 16203 Diag(Loc, diag::err_catch_rvalue_ref); 16204 Invalid = true; 16205 } 16206 16207 if (ExDeclType->isVariablyModifiedType()) { 16208 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType; 16209 Invalid = true; 16210 } 16211 16212 QualType BaseType = ExDeclType; 16213 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 16214 unsigned DK = diag::err_catch_incomplete; 16215 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 16216 BaseType = Ptr->getPointeeType(); 16217 Mode = 1; 16218 DK = diag::err_catch_incomplete_ptr; 16219 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 16220 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 16221 BaseType = Ref->getPointeeType(); 16222 Mode = 2; 16223 DK = diag::err_catch_incomplete_ref; 16224 } 16225 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 16226 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 16227 Invalid = true; 16228 16229 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) { 16230 Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType; 16231 Invalid = true; 16232 } 16233 16234 if (!Invalid && !ExDeclType->isDependentType() && 16235 RequireNonAbstractType(Loc, ExDeclType, 16236 diag::err_abstract_type_in_decl, 16237 AbstractVariableType)) 16238 Invalid = true; 16239 16240 // Only the non-fragile NeXT runtime currently supports C++ catches 16241 // of ObjC types, and no runtime supports catching ObjC types by value. 16242 if (!Invalid && getLangOpts().ObjC) { 16243 QualType T = ExDeclType; 16244 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 16245 T = RT->getPointeeType(); 16246 16247 if (T->isObjCObjectType()) { 16248 Diag(Loc, diag::err_objc_object_catch); 16249 Invalid = true; 16250 } else if (T->isObjCObjectPointerType()) { 16251 // FIXME: should this be a test for macosx-fragile specifically? 16252 if (getLangOpts().ObjCRuntime.isFragile()) 16253 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 16254 } 16255 } 16256 16257 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 16258 ExDeclType, TInfo, SC_None); 16259 ExDecl->setExceptionVariable(true); 16260 16261 // In ARC, infer 'retaining' for variables of retainable type. 16262 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 16263 Invalid = true; 16264 16265 if (!Invalid && !ExDeclType->isDependentType()) { 16266 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 16267 // Insulate this from anything else we might currently be parsing. 16268 EnterExpressionEvaluationContext scope( 16269 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 16270 16271 // C++ [except.handle]p16: 16272 // The object declared in an exception-declaration or, if the 16273 // exception-declaration does not specify a name, a temporary (12.2) is 16274 // copy-initialized (8.5) from the exception object. [...] 16275 // The object is destroyed when the handler exits, after the destruction 16276 // of any automatic objects initialized within the handler. 16277 // 16278 // We just pretend to initialize the object with itself, then make sure 16279 // it can be destroyed later. 16280 QualType initType = Context.getExceptionObjectType(ExDeclType); 16281 16282 InitializedEntity entity = 16283 InitializedEntity::InitializeVariable(ExDecl); 16284 InitializationKind initKind = 16285 InitializationKind::CreateCopy(Loc, SourceLocation()); 16286 16287 Expr *opaqueValue = 16288 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 16289 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 16290 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 16291 if (result.isInvalid()) 16292 Invalid = true; 16293 else { 16294 // If the constructor used was non-trivial, set this as the 16295 // "initializer". 16296 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 16297 if (!construct->getConstructor()->isTrivial()) { 16298 Expr *init = MaybeCreateExprWithCleanups(construct); 16299 ExDecl->setInit(init); 16300 } 16301 16302 // And make sure it's destructable. 16303 FinalizeVarWithDestructor(ExDecl, recordType); 16304 } 16305 } 16306 } 16307 16308 if (Invalid) 16309 ExDecl->setInvalidDecl(); 16310 16311 return ExDecl; 16312 } 16313 16314 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 16315 /// handler. 16316 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 16317 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16318 bool Invalid = D.isInvalidType(); 16319 16320 // Check for unexpanded parameter packs. 16321 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 16322 UPPC_ExceptionType)) { 16323 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 16324 D.getIdentifierLoc()); 16325 Invalid = true; 16326 } 16327 16328 IdentifierInfo *II = D.getIdentifier(); 16329 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 16330 LookupOrdinaryName, 16331 ForVisibleRedeclaration)) { 16332 // The scope should be freshly made just for us. There is just no way 16333 // it contains any previous declaration, except for function parameters in 16334 // a function-try-block's catch statement. 16335 assert(!S->isDeclScope(PrevDecl)); 16336 if (isDeclInScope(PrevDecl, CurContext, S)) { 16337 Diag(D.getIdentifierLoc(), diag::err_redefinition) 16338 << D.getIdentifier(); 16339 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 16340 Invalid = true; 16341 } else if (PrevDecl->isTemplateParameter()) 16342 // Maybe we will complain about the shadowed template parameter. 16343 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 16344 } 16345 16346 if (D.getCXXScopeSpec().isSet() && !Invalid) { 16347 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 16348 << D.getCXXScopeSpec().getRange(); 16349 Invalid = true; 16350 } 16351 16352 VarDecl *ExDecl = BuildExceptionDeclaration( 16353 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier()); 16354 if (Invalid) 16355 ExDecl->setInvalidDecl(); 16356 16357 // Add the exception declaration into this scope. 16358 if (II) 16359 PushOnScopeChains(ExDecl, S); 16360 else 16361 CurContext->addDecl(ExDecl); 16362 16363 ProcessDeclAttributes(S, ExDecl, D); 16364 return ExDecl; 16365 } 16366 16367 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 16368 Expr *AssertExpr, 16369 Expr *AssertMessageExpr, 16370 SourceLocation RParenLoc) { 16371 StringLiteral *AssertMessage = 16372 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 16373 16374 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 16375 return nullptr; 16376 16377 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 16378 AssertMessage, RParenLoc, false); 16379 } 16380 16381 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 16382 Expr *AssertExpr, 16383 StringLiteral *AssertMessage, 16384 SourceLocation RParenLoc, 16385 bool Failed) { 16386 assert(AssertExpr != nullptr && "Expected non-null condition"); 16387 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 16388 !Failed) { 16389 // In a static_assert-declaration, the constant-expression shall be a 16390 // constant expression that can be contextually converted to bool. 16391 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 16392 if (Converted.isInvalid()) 16393 Failed = true; 16394 16395 ExprResult FullAssertExpr = 16396 ActOnFinishFullExpr(Converted.get(), StaticAssertLoc, 16397 /*DiscardedValue*/ false, 16398 /*IsConstexpr*/ true); 16399 if (FullAssertExpr.isInvalid()) 16400 Failed = true; 16401 else 16402 AssertExpr = FullAssertExpr.get(); 16403 16404 llvm::APSInt Cond; 16405 if (!Failed && VerifyIntegerConstantExpression( 16406 AssertExpr, &Cond, 16407 diag::err_static_assert_expression_is_not_constant) 16408 .isInvalid()) 16409 Failed = true; 16410 16411 if (!Failed && !Cond) { 16412 SmallString<256> MsgBuffer; 16413 llvm::raw_svector_ostream Msg(MsgBuffer); 16414 if (AssertMessage) 16415 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 16416 16417 Expr *InnerCond = nullptr; 16418 std::string InnerCondDescription; 16419 std::tie(InnerCond, InnerCondDescription) = 16420 findFailedBooleanCondition(Converted.get()); 16421 if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) { 16422 // Drill down into concept specialization expressions to see why they 16423 // weren't satisfied. 16424 Diag(StaticAssertLoc, diag::err_static_assert_failed) 16425 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 16426 ConstraintSatisfaction Satisfaction; 16427 if (!CheckConstraintSatisfaction(InnerCond, Satisfaction)) 16428 DiagnoseUnsatisfiedConstraint(Satisfaction); 16429 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond) 16430 && !isa<IntegerLiteral>(InnerCond)) { 16431 Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed) 16432 << InnerCondDescription << !AssertMessage 16433 << Msg.str() << InnerCond->getSourceRange(); 16434 } else { 16435 Diag(StaticAssertLoc, diag::err_static_assert_failed) 16436 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 16437 } 16438 Failed = true; 16439 } 16440 } else { 16441 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc, 16442 /*DiscardedValue*/false, 16443 /*IsConstexpr*/true); 16444 if (FullAssertExpr.isInvalid()) 16445 Failed = true; 16446 else 16447 AssertExpr = FullAssertExpr.get(); 16448 } 16449 16450 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 16451 AssertExpr, AssertMessage, RParenLoc, 16452 Failed); 16453 16454 CurContext->addDecl(Decl); 16455 return Decl; 16456 } 16457 16458 /// Perform semantic analysis of the given friend type declaration. 16459 /// 16460 /// \returns A friend declaration that. 16461 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 16462 SourceLocation FriendLoc, 16463 TypeSourceInfo *TSInfo) { 16464 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 16465 16466 QualType T = TSInfo->getType(); 16467 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 16468 16469 // C++03 [class.friend]p2: 16470 // An elaborated-type-specifier shall be used in a friend declaration 16471 // for a class.* 16472 // 16473 // * The class-key of the elaborated-type-specifier is required. 16474 if (!CodeSynthesisContexts.empty()) { 16475 // Do not complain about the form of friend template types during any kind 16476 // of code synthesis. For template instantiation, we will have complained 16477 // when the template was defined. 16478 } else { 16479 if (!T->isElaboratedTypeSpecifier()) { 16480 // If we evaluated the type to a record type, suggest putting 16481 // a tag in front. 16482 if (const RecordType *RT = T->getAs<RecordType>()) { 16483 RecordDecl *RD = RT->getDecl(); 16484 16485 SmallString<16> InsertionText(" "); 16486 InsertionText += RD->getKindName(); 16487 16488 Diag(TypeRange.getBegin(), 16489 getLangOpts().CPlusPlus11 ? 16490 diag::warn_cxx98_compat_unelaborated_friend_type : 16491 diag::ext_unelaborated_friend_type) 16492 << (unsigned) RD->getTagKind() 16493 << T 16494 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc), 16495 InsertionText); 16496 } else { 16497 Diag(FriendLoc, 16498 getLangOpts().CPlusPlus11 ? 16499 diag::warn_cxx98_compat_nonclass_type_friend : 16500 diag::ext_nonclass_type_friend) 16501 << T 16502 << TypeRange; 16503 } 16504 } else if (T->getAs<EnumType>()) { 16505 Diag(FriendLoc, 16506 getLangOpts().CPlusPlus11 ? 16507 diag::warn_cxx98_compat_enum_friend : 16508 diag::ext_enum_friend) 16509 << T 16510 << TypeRange; 16511 } 16512 16513 // C++11 [class.friend]p3: 16514 // A friend declaration that does not declare a function shall have one 16515 // of the following forms: 16516 // friend elaborated-type-specifier ; 16517 // friend simple-type-specifier ; 16518 // friend typename-specifier ; 16519 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 16520 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 16521 } 16522 16523 // If the type specifier in a friend declaration designates a (possibly 16524 // cv-qualified) class type, that class is declared as a friend; otherwise, 16525 // the friend declaration is ignored. 16526 return FriendDecl::Create(Context, CurContext, 16527 TSInfo->getTypeLoc().getBeginLoc(), TSInfo, 16528 FriendLoc); 16529 } 16530 16531 /// Handle a friend tag declaration where the scope specifier was 16532 /// templated. 16533 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 16534 unsigned TagSpec, SourceLocation TagLoc, 16535 CXXScopeSpec &SS, IdentifierInfo *Name, 16536 SourceLocation NameLoc, 16537 const ParsedAttributesView &Attr, 16538 MultiTemplateParamsArg TempParamLists) { 16539 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 16540 16541 bool IsMemberSpecialization = false; 16542 bool Invalid = false; 16543 16544 if (TemplateParameterList *TemplateParams = 16545 MatchTemplateParametersToScopeSpecifier( 16546 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 16547 IsMemberSpecialization, Invalid)) { 16548 if (TemplateParams->size() > 0) { 16549 // This is a declaration of a class template. 16550 if (Invalid) 16551 return nullptr; 16552 16553 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 16554 NameLoc, Attr, TemplateParams, AS_public, 16555 /*ModulePrivateLoc=*/SourceLocation(), 16556 FriendLoc, TempParamLists.size() - 1, 16557 TempParamLists.data()).get(); 16558 } else { 16559 // The "template<>" header is extraneous. 16560 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 16561 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 16562 IsMemberSpecialization = true; 16563 } 16564 } 16565 16566 if (Invalid) return nullptr; 16567 16568 bool isAllExplicitSpecializations = true; 16569 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 16570 if (TempParamLists[I]->size()) { 16571 isAllExplicitSpecializations = false; 16572 break; 16573 } 16574 } 16575 16576 // FIXME: don't ignore attributes. 16577 16578 // If it's explicit specializations all the way down, just forget 16579 // about the template header and build an appropriate non-templated 16580 // friend. TODO: for source fidelity, remember the headers. 16581 if (isAllExplicitSpecializations) { 16582 if (SS.isEmpty()) { 16583 bool Owned = false; 16584 bool IsDependent = false; 16585 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 16586 Attr, AS_public, 16587 /*ModulePrivateLoc=*/SourceLocation(), 16588 MultiTemplateParamsArg(), Owned, IsDependent, 16589 /*ScopedEnumKWLoc=*/SourceLocation(), 16590 /*ScopedEnumUsesClassTag=*/false, 16591 /*UnderlyingType=*/TypeResult(), 16592 /*IsTypeSpecifier=*/false, 16593 /*IsTemplateParamOrArg=*/false); 16594 } 16595 16596 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 16597 ElaboratedTypeKeyword Keyword 16598 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 16599 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 16600 *Name, NameLoc); 16601 if (T.isNull()) 16602 return nullptr; 16603 16604 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 16605 if (isa<DependentNameType>(T)) { 16606 DependentNameTypeLoc TL = 16607 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 16608 TL.setElaboratedKeywordLoc(TagLoc); 16609 TL.setQualifierLoc(QualifierLoc); 16610 TL.setNameLoc(NameLoc); 16611 } else { 16612 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 16613 TL.setElaboratedKeywordLoc(TagLoc); 16614 TL.setQualifierLoc(QualifierLoc); 16615 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 16616 } 16617 16618 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 16619 TSI, FriendLoc, TempParamLists); 16620 Friend->setAccess(AS_public); 16621 CurContext->addDecl(Friend); 16622 return Friend; 16623 } 16624 16625 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 16626 16627 16628 16629 // Handle the case of a templated-scope friend class. e.g. 16630 // template <class T> class A<T>::B; 16631 // FIXME: we don't support these right now. 16632 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 16633 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 16634 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 16635 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 16636 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 16637 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 16638 TL.setElaboratedKeywordLoc(TagLoc); 16639 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 16640 TL.setNameLoc(NameLoc); 16641 16642 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 16643 TSI, FriendLoc, TempParamLists); 16644 Friend->setAccess(AS_public); 16645 Friend->setUnsupportedFriend(true); 16646 CurContext->addDecl(Friend); 16647 return Friend; 16648 } 16649 16650 /// Handle a friend type declaration. This works in tandem with 16651 /// ActOnTag. 16652 /// 16653 /// Notes on friend class templates: 16654 /// 16655 /// We generally treat friend class declarations as if they were 16656 /// declaring a class. So, for example, the elaborated type specifier 16657 /// in a friend declaration is required to obey the restrictions of a 16658 /// class-head (i.e. no typedefs in the scope chain), template 16659 /// parameters are required to match up with simple template-ids, &c. 16660 /// However, unlike when declaring a template specialization, it's 16661 /// okay to refer to a template specialization without an empty 16662 /// template parameter declaration, e.g. 16663 /// friend class A<T>::B<unsigned>; 16664 /// We permit this as a special case; if there are any template 16665 /// parameters present at all, require proper matching, i.e. 16666 /// template <> template \<class T> friend class A<int>::B; 16667 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 16668 MultiTemplateParamsArg TempParams) { 16669 SourceLocation Loc = DS.getBeginLoc(); 16670 16671 assert(DS.isFriendSpecified()); 16672 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 16673 16674 // C++ [class.friend]p3: 16675 // A friend declaration that does not declare a function shall have one of 16676 // the following forms: 16677 // friend elaborated-type-specifier ; 16678 // friend simple-type-specifier ; 16679 // friend typename-specifier ; 16680 // 16681 // Any declaration with a type qualifier does not have that form. (It's 16682 // legal to specify a qualified type as a friend, you just can't write the 16683 // keywords.) 16684 if (DS.getTypeQualifiers()) { 16685 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 16686 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const"; 16687 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 16688 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile"; 16689 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 16690 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict"; 16691 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 16692 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic"; 16693 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 16694 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned"; 16695 } 16696 16697 // Try to convert the decl specifier to a type. This works for 16698 // friend templates because ActOnTag never produces a ClassTemplateDecl 16699 // for a TUK_Friend. 16700 Declarator TheDeclarator(DS, DeclaratorContext::Member); 16701 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 16702 QualType T = TSI->getType(); 16703 if (TheDeclarator.isInvalidType()) 16704 return nullptr; 16705 16706 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 16707 return nullptr; 16708 16709 // This is definitely an error in C++98. It's probably meant to 16710 // be forbidden in C++0x, too, but the specification is just 16711 // poorly written. 16712 // 16713 // The problem is with declarations like the following: 16714 // template <T> friend A<T>::foo; 16715 // where deciding whether a class C is a friend or not now hinges 16716 // on whether there exists an instantiation of A that causes 16717 // 'foo' to equal C. There are restrictions on class-heads 16718 // (which we declare (by fiat) elaborated friend declarations to 16719 // be) that makes this tractable. 16720 // 16721 // FIXME: handle "template <> friend class A<T>;", which 16722 // is possibly well-formed? Who even knows? 16723 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 16724 Diag(Loc, diag::err_tagless_friend_type_template) 16725 << DS.getSourceRange(); 16726 return nullptr; 16727 } 16728 16729 // C++98 [class.friend]p1: A friend of a class is a function 16730 // or class that is not a member of the class . . . 16731 // This is fixed in DR77, which just barely didn't make the C++03 16732 // deadline. It's also a very silly restriction that seriously 16733 // affects inner classes and which nobody else seems to implement; 16734 // thus we never diagnose it, not even in -pedantic. 16735 // 16736 // But note that we could warn about it: it's always useless to 16737 // friend one of your own members (it's not, however, worthless to 16738 // friend a member of an arbitrary specialization of your template). 16739 16740 Decl *D; 16741 if (!TempParams.empty()) 16742 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 16743 TempParams, 16744 TSI, 16745 DS.getFriendSpecLoc()); 16746 else 16747 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 16748 16749 if (!D) 16750 return nullptr; 16751 16752 D->setAccess(AS_public); 16753 CurContext->addDecl(D); 16754 16755 return D; 16756 } 16757 16758 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 16759 MultiTemplateParamsArg TemplateParams) { 16760 const DeclSpec &DS = D.getDeclSpec(); 16761 16762 assert(DS.isFriendSpecified()); 16763 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 16764 16765 SourceLocation Loc = D.getIdentifierLoc(); 16766 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16767 16768 // C++ [class.friend]p1 16769 // A friend of a class is a function or class.... 16770 // Note that this sees through typedefs, which is intended. 16771 // It *doesn't* see through dependent types, which is correct 16772 // according to [temp.arg.type]p3: 16773 // If a declaration acquires a function type through a 16774 // type dependent on a template-parameter and this causes 16775 // a declaration that does not use the syntactic form of a 16776 // function declarator to have a function type, the program 16777 // is ill-formed. 16778 if (!TInfo->getType()->isFunctionType()) { 16779 Diag(Loc, diag::err_unexpected_friend); 16780 16781 // It might be worthwhile to try to recover by creating an 16782 // appropriate declaration. 16783 return nullptr; 16784 } 16785 16786 // C++ [namespace.memdef]p3 16787 // - If a friend declaration in a non-local class first declares a 16788 // class or function, the friend class or function is a member 16789 // of the innermost enclosing namespace. 16790 // - The name of the friend is not found by simple name lookup 16791 // until a matching declaration is provided in that namespace 16792 // scope (either before or after the class declaration granting 16793 // friendship). 16794 // - If a friend function is called, its name may be found by the 16795 // name lookup that considers functions from namespaces and 16796 // classes associated with the types of the function arguments. 16797 // - When looking for a prior declaration of a class or a function 16798 // declared as a friend, scopes outside the innermost enclosing 16799 // namespace scope are not considered. 16800 16801 CXXScopeSpec &SS = D.getCXXScopeSpec(); 16802 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 16803 assert(NameInfo.getName()); 16804 16805 // Check for unexpanded parameter packs. 16806 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 16807 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 16808 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 16809 return nullptr; 16810 16811 // The context we found the declaration in, or in which we should 16812 // create the declaration. 16813 DeclContext *DC; 16814 Scope *DCScope = S; 16815 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 16816 ForExternalRedeclaration); 16817 16818 // There are five cases here. 16819 // - There's no scope specifier and we're in a local class. Only look 16820 // for functions declared in the immediately-enclosing block scope. 16821 // We recover from invalid scope qualifiers as if they just weren't there. 16822 FunctionDecl *FunctionContainingLocalClass = nullptr; 16823 if ((SS.isInvalid() || !SS.isSet()) && 16824 (FunctionContainingLocalClass = 16825 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 16826 // C++11 [class.friend]p11: 16827 // If a friend declaration appears in a local class and the name 16828 // specified is an unqualified name, a prior declaration is 16829 // looked up without considering scopes that are outside the 16830 // innermost enclosing non-class scope. For a friend function 16831 // declaration, if there is no prior declaration, the program is 16832 // ill-formed. 16833 16834 // Find the innermost enclosing non-class scope. This is the block 16835 // scope containing the local class definition (or for a nested class, 16836 // the outer local class). 16837 DCScope = S->getFnParent(); 16838 16839 // Look up the function name in the scope. 16840 Previous.clear(LookupLocalFriendName); 16841 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 16842 16843 if (!Previous.empty()) { 16844 // All possible previous declarations must have the same context: 16845 // either they were declared at block scope or they are members of 16846 // one of the enclosing local classes. 16847 DC = Previous.getRepresentativeDecl()->getDeclContext(); 16848 } else { 16849 // This is ill-formed, but provide the context that we would have 16850 // declared the function in, if we were permitted to, for error recovery. 16851 DC = FunctionContainingLocalClass; 16852 } 16853 adjustContextForLocalExternDecl(DC); 16854 16855 // C++ [class.friend]p6: 16856 // A function can be defined in a friend declaration of a class if and 16857 // only if the class is a non-local class (9.8), the function name is 16858 // unqualified, and the function has namespace scope. 16859 if (D.isFunctionDefinition()) { 16860 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 16861 } 16862 16863 // - There's no scope specifier, in which case we just go to the 16864 // appropriate scope and look for a function or function template 16865 // there as appropriate. 16866 } else if (SS.isInvalid() || !SS.isSet()) { 16867 // C++11 [namespace.memdef]p3: 16868 // If the name in a friend declaration is neither qualified nor 16869 // a template-id and the declaration is a function or an 16870 // elaborated-type-specifier, the lookup to determine whether 16871 // the entity has been previously declared shall not consider 16872 // any scopes outside the innermost enclosing namespace. 16873 bool isTemplateId = 16874 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId; 16875 16876 // Find the appropriate context according to the above. 16877 DC = CurContext; 16878 16879 // Skip class contexts. If someone can cite chapter and verse 16880 // for this behavior, that would be nice --- it's what GCC and 16881 // EDG do, and it seems like a reasonable intent, but the spec 16882 // really only says that checks for unqualified existing 16883 // declarations should stop at the nearest enclosing namespace, 16884 // not that they should only consider the nearest enclosing 16885 // namespace. 16886 while (DC->isRecord()) 16887 DC = DC->getParent(); 16888 16889 DeclContext *LookupDC = DC->getNonTransparentContext(); 16890 while (true) { 16891 LookupQualifiedName(Previous, LookupDC); 16892 16893 if (!Previous.empty()) { 16894 DC = LookupDC; 16895 break; 16896 } 16897 16898 if (isTemplateId) { 16899 if (isa<TranslationUnitDecl>(LookupDC)) break; 16900 } else { 16901 if (LookupDC->isFileContext()) break; 16902 } 16903 LookupDC = LookupDC->getParent(); 16904 } 16905 16906 DCScope = getScopeForDeclContext(S, DC); 16907 16908 // - There's a non-dependent scope specifier, in which case we 16909 // compute it and do a previous lookup there for a function 16910 // or function template. 16911 } else if (!SS.getScopeRep()->isDependent()) { 16912 DC = computeDeclContext(SS); 16913 if (!DC) return nullptr; 16914 16915 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 16916 16917 LookupQualifiedName(Previous, DC); 16918 16919 // C++ [class.friend]p1: A friend of a class is a function or 16920 // class that is not a member of the class . . . 16921 if (DC->Equals(CurContext)) 16922 Diag(DS.getFriendSpecLoc(), 16923 getLangOpts().CPlusPlus11 ? 16924 diag::warn_cxx98_compat_friend_is_member : 16925 diag::err_friend_is_member); 16926 16927 if (D.isFunctionDefinition()) { 16928 // C++ [class.friend]p6: 16929 // A function can be defined in a friend declaration of a class if and 16930 // only if the class is a non-local class (9.8), the function name is 16931 // unqualified, and the function has namespace scope. 16932 // 16933 // FIXME: We should only do this if the scope specifier names the 16934 // innermost enclosing namespace; otherwise the fixit changes the 16935 // meaning of the code. 16936 SemaDiagnosticBuilder DB 16937 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 16938 16939 DB << SS.getScopeRep(); 16940 if (DC->isFileContext()) 16941 DB << FixItHint::CreateRemoval(SS.getRange()); 16942 SS.clear(); 16943 } 16944 16945 // - There's a scope specifier that does not match any template 16946 // parameter lists, in which case we use some arbitrary context, 16947 // create a method or method template, and wait for instantiation. 16948 // - There's a scope specifier that does match some template 16949 // parameter lists, which we don't handle right now. 16950 } else { 16951 if (D.isFunctionDefinition()) { 16952 // C++ [class.friend]p6: 16953 // A function can be defined in a friend declaration of a class if and 16954 // only if the class is a non-local class (9.8), the function name is 16955 // unqualified, and the function has namespace scope. 16956 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 16957 << SS.getScopeRep(); 16958 } 16959 16960 DC = CurContext; 16961 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 16962 } 16963 16964 if (!DC->isRecord()) { 16965 int DiagArg = -1; 16966 switch (D.getName().getKind()) { 16967 case UnqualifiedIdKind::IK_ConstructorTemplateId: 16968 case UnqualifiedIdKind::IK_ConstructorName: 16969 DiagArg = 0; 16970 break; 16971 case UnqualifiedIdKind::IK_DestructorName: 16972 DiagArg = 1; 16973 break; 16974 case UnqualifiedIdKind::IK_ConversionFunctionId: 16975 DiagArg = 2; 16976 break; 16977 case UnqualifiedIdKind::IK_DeductionGuideName: 16978 DiagArg = 3; 16979 break; 16980 case UnqualifiedIdKind::IK_Identifier: 16981 case UnqualifiedIdKind::IK_ImplicitSelfParam: 16982 case UnqualifiedIdKind::IK_LiteralOperatorId: 16983 case UnqualifiedIdKind::IK_OperatorFunctionId: 16984 case UnqualifiedIdKind::IK_TemplateId: 16985 break; 16986 } 16987 // This implies that it has to be an operator or function. 16988 if (DiagArg >= 0) { 16989 Diag(Loc, diag::err_introducing_special_friend) << DiagArg; 16990 return nullptr; 16991 } 16992 } 16993 16994 // FIXME: This is an egregious hack to cope with cases where the scope stack 16995 // does not contain the declaration context, i.e., in an out-of-line 16996 // definition of a class. 16997 Scope FakeDCScope(S, Scope::DeclScope, Diags); 16998 if (!DCScope) { 16999 FakeDCScope.setEntity(DC); 17000 DCScope = &FakeDCScope; 17001 } 17002 17003 bool AddToScope = true; 17004 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 17005 TemplateParams, AddToScope); 17006 if (!ND) return nullptr; 17007 17008 assert(ND->getLexicalDeclContext() == CurContext); 17009 17010 // If we performed typo correction, we might have added a scope specifier 17011 // and changed the decl context. 17012 DC = ND->getDeclContext(); 17013 17014 // Add the function declaration to the appropriate lookup tables, 17015 // adjusting the redeclarations list as necessary. We don't 17016 // want to do this yet if the friending class is dependent. 17017 // 17018 // Also update the scope-based lookup if the target context's 17019 // lookup context is in lexical scope. 17020 if (!CurContext->isDependentContext()) { 17021 DC = DC->getRedeclContext(); 17022 DC->makeDeclVisibleInContext(ND); 17023 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 17024 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 17025 } 17026 17027 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 17028 D.getIdentifierLoc(), ND, 17029 DS.getFriendSpecLoc()); 17030 FrD->setAccess(AS_public); 17031 CurContext->addDecl(FrD); 17032 17033 if (ND->isInvalidDecl()) { 17034 FrD->setInvalidDecl(); 17035 } else { 17036 if (DC->isRecord()) CheckFriendAccess(ND); 17037 17038 FunctionDecl *FD; 17039 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 17040 FD = FTD->getTemplatedDecl(); 17041 else 17042 FD = cast<FunctionDecl>(ND); 17043 17044 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 17045 // default argument expression, that declaration shall be a definition 17046 // and shall be the only declaration of the function or function 17047 // template in the translation unit. 17048 if (functionDeclHasDefaultArgument(FD)) { 17049 // We can't look at FD->getPreviousDecl() because it may not have been set 17050 // if we're in a dependent context. If the function is known to be a 17051 // redeclaration, we will have narrowed Previous down to the right decl. 17052 if (D.isRedeclaration()) { 17053 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 17054 Diag(Previous.getRepresentativeDecl()->getLocation(), 17055 diag::note_previous_declaration); 17056 } else if (!D.isFunctionDefinition()) 17057 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 17058 } 17059 17060 // Mark templated-scope function declarations as unsupported. 17061 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 17062 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 17063 << SS.getScopeRep() << SS.getRange() 17064 << cast<CXXRecordDecl>(CurContext); 17065 FrD->setUnsupportedFriend(true); 17066 } 17067 } 17068 17069 warnOnReservedIdentifier(ND); 17070 17071 return ND; 17072 } 17073 17074 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 17075 AdjustDeclIfTemplate(Dcl); 17076 17077 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 17078 if (!Fn) { 17079 Diag(DelLoc, diag::err_deleted_non_function); 17080 return; 17081 } 17082 17083 // Deleted function does not have a body. 17084 Fn->setWillHaveBody(false); 17085 17086 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 17087 // Don't consider the implicit declaration we generate for explicit 17088 // specializations. FIXME: Do not generate these implicit declarations. 17089 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 17090 Prev->getPreviousDecl()) && 17091 !Prev->isDefined()) { 17092 Diag(DelLoc, diag::err_deleted_decl_not_first); 17093 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 17094 Prev->isImplicit() ? diag::note_previous_implicit_declaration 17095 : diag::note_previous_declaration); 17096 // We can't recover from this; the declaration might have already 17097 // been used. 17098 Fn->setInvalidDecl(); 17099 return; 17100 } 17101 17102 // To maintain the invariant that functions are only deleted on their first 17103 // declaration, mark the implicitly-instantiated declaration of the 17104 // explicitly-specialized function as deleted instead of marking the 17105 // instantiated redeclaration. 17106 Fn = Fn->getCanonicalDecl(); 17107 } 17108 17109 // dllimport/dllexport cannot be deleted. 17110 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 17111 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 17112 Fn->setInvalidDecl(); 17113 } 17114 17115 // C++11 [basic.start.main]p3: 17116 // A program that defines main as deleted [...] is ill-formed. 17117 if (Fn->isMain()) 17118 Diag(DelLoc, diag::err_deleted_main); 17119 17120 // C++11 [dcl.fct.def.delete]p4: 17121 // A deleted function is implicitly inline. 17122 Fn->setImplicitlyInline(); 17123 Fn->setDeletedAsWritten(); 17124 } 17125 17126 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 17127 if (!Dcl || Dcl->isInvalidDecl()) 17128 return; 17129 17130 auto *FD = dyn_cast<FunctionDecl>(Dcl); 17131 if (!FD) { 17132 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) { 17133 if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) { 17134 Diag(DefaultLoc, diag::err_defaulted_comparison_template); 17135 return; 17136 } 17137 } 17138 17139 Diag(DefaultLoc, diag::err_default_special_members) 17140 << getLangOpts().CPlusPlus20; 17141 return; 17142 } 17143 17144 // Reject if this can't possibly be a defaultable function. 17145 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD); 17146 if (!DefKind && 17147 // A dependent function that doesn't locally look defaultable can 17148 // still instantiate to a defaultable function if it's a constructor 17149 // or assignment operator. 17150 (!FD->isDependentContext() || 17151 (!isa<CXXConstructorDecl>(FD) && 17152 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) { 17153 Diag(DefaultLoc, diag::err_default_special_members) 17154 << getLangOpts().CPlusPlus20; 17155 return; 17156 } 17157 17158 if (DefKind.isComparison() && 17159 !isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 17160 Diag(FD->getLocation(), diag::err_defaulted_comparison_out_of_class) 17161 << (int)DefKind.asComparison(); 17162 return; 17163 } 17164 17165 // Issue compatibility warning. We already warned if the operator is 17166 // 'operator<=>' when parsing the '<=>' token. 17167 if (DefKind.isComparison() && 17168 DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) { 17169 Diag(DefaultLoc, getLangOpts().CPlusPlus20 17170 ? diag::warn_cxx17_compat_defaulted_comparison 17171 : diag::ext_defaulted_comparison); 17172 } 17173 17174 FD->setDefaulted(); 17175 FD->setExplicitlyDefaulted(); 17176 17177 // Defer checking functions that are defaulted in a dependent context. 17178 if (FD->isDependentContext()) 17179 return; 17180 17181 // Unset that we will have a body for this function. We might not, 17182 // if it turns out to be trivial, and we don't need this marking now 17183 // that we've marked it as defaulted. 17184 FD->setWillHaveBody(false); 17185 17186 // If this definition appears within the record, do the checking when 17187 // the record is complete. This is always the case for a defaulted 17188 // comparison. 17189 if (DefKind.isComparison()) 17190 return; 17191 auto *MD = cast<CXXMethodDecl>(FD); 17192 17193 const FunctionDecl *Primary = FD; 17194 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern()) 17195 // Ask the template instantiation pattern that actually had the 17196 // '= default' on it. 17197 Primary = Pattern; 17198 17199 // If the method was defaulted on its first declaration, we will have 17200 // already performed the checking in CheckCompletedCXXClass. Such a 17201 // declaration doesn't trigger an implicit definition. 17202 if (Primary->getCanonicalDecl()->isDefaulted()) 17203 return; 17204 17205 // FIXME: Once we support defining comparisons out of class, check for a 17206 // defaulted comparison here. 17207 if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember())) 17208 MD->setInvalidDecl(); 17209 else 17210 DefineDefaultedFunction(*this, MD, DefaultLoc); 17211 } 17212 17213 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 17214 for (Stmt *SubStmt : S->children()) { 17215 if (!SubStmt) 17216 continue; 17217 if (isa<ReturnStmt>(SubStmt)) 17218 Self.Diag(SubStmt->getBeginLoc(), 17219 diag::err_return_in_constructor_handler); 17220 if (!isa<Expr>(SubStmt)) 17221 SearchForReturnInStmt(Self, SubStmt); 17222 } 17223 } 17224 17225 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 17226 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 17227 CXXCatchStmt *Handler = TryBlock->getHandler(I); 17228 SearchForReturnInStmt(*this, Handler); 17229 } 17230 } 17231 17232 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 17233 const CXXMethodDecl *Old) { 17234 const auto *NewFT = New->getType()->castAs<FunctionProtoType>(); 17235 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>(); 17236 17237 if (OldFT->hasExtParameterInfos()) { 17238 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I) 17239 // A parameter of the overriding method should be annotated with noescape 17240 // if the corresponding parameter of the overridden method is annotated. 17241 if (OldFT->getExtParameterInfo(I).isNoEscape() && 17242 !NewFT->getExtParameterInfo(I).isNoEscape()) { 17243 Diag(New->getParamDecl(I)->getLocation(), 17244 diag::warn_overriding_method_missing_noescape); 17245 Diag(Old->getParamDecl(I)->getLocation(), 17246 diag::note_overridden_marked_noescape); 17247 } 17248 } 17249 17250 // Virtual overrides must have the same code_seg. 17251 const auto *OldCSA = Old->getAttr<CodeSegAttr>(); 17252 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 17253 if ((NewCSA || OldCSA) && 17254 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) { 17255 Diag(New->getLocation(), diag::err_mismatched_code_seg_override); 17256 Diag(Old->getLocation(), diag::note_previous_declaration); 17257 return true; 17258 } 17259 17260 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 17261 17262 // If the calling conventions match, everything is fine 17263 if (NewCC == OldCC) 17264 return false; 17265 17266 // If the calling conventions mismatch because the new function is static, 17267 // suppress the calling convention mismatch error; the error about static 17268 // function override (err_static_overrides_virtual from 17269 // Sema::CheckFunctionDeclaration) is more clear. 17270 if (New->getStorageClass() == SC_Static) 17271 return false; 17272 17273 Diag(New->getLocation(), 17274 diag::err_conflicting_overriding_cc_attributes) 17275 << New->getDeclName() << New->getType() << Old->getType(); 17276 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 17277 return true; 17278 } 17279 17280 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 17281 const CXXMethodDecl *Old) { 17282 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType(); 17283 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType(); 17284 17285 if (Context.hasSameType(NewTy, OldTy) || 17286 NewTy->isDependentType() || OldTy->isDependentType()) 17287 return false; 17288 17289 // Check if the return types are covariant 17290 QualType NewClassTy, OldClassTy; 17291 17292 /// Both types must be pointers or references to classes. 17293 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 17294 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 17295 NewClassTy = NewPT->getPointeeType(); 17296 OldClassTy = OldPT->getPointeeType(); 17297 } 17298 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 17299 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 17300 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 17301 NewClassTy = NewRT->getPointeeType(); 17302 OldClassTy = OldRT->getPointeeType(); 17303 } 17304 } 17305 } 17306 17307 // The return types aren't either both pointers or references to a class type. 17308 if (NewClassTy.isNull()) { 17309 Diag(New->getLocation(), 17310 diag::err_different_return_type_for_overriding_virtual_function) 17311 << New->getDeclName() << NewTy << OldTy 17312 << New->getReturnTypeSourceRange(); 17313 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17314 << Old->getReturnTypeSourceRange(); 17315 17316 return true; 17317 } 17318 17319 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 17320 // C++14 [class.virtual]p8: 17321 // If the class type in the covariant return type of D::f differs from 17322 // that of B::f, the class type in the return type of D::f shall be 17323 // complete at the point of declaration of D::f or shall be the class 17324 // type D. 17325 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 17326 if (!RT->isBeingDefined() && 17327 RequireCompleteType(New->getLocation(), NewClassTy, 17328 diag::err_covariant_return_incomplete, 17329 New->getDeclName())) 17330 return true; 17331 } 17332 17333 // Check if the new class derives from the old class. 17334 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) { 17335 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 17336 << New->getDeclName() << NewTy << OldTy 17337 << New->getReturnTypeSourceRange(); 17338 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17339 << Old->getReturnTypeSourceRange(); 17340 return true; 17341 } 17342 17343 // Check if we the conversion from derived to base is valid. 17344 if (CheckDerivedToBaseConversion( 17345 NewClassTy, OldClassTy, 17346 diag::err_covariant_return_inaccessible_base, 17347 diag::err_covariant_return_ambiguous_derived_to_base_conv, 17348 New->getLocation(), New->getReturnTypeSourceRange(), 17349 New->getDeclName(), nullptr)) { 17350 // FIXME: this note won't trigger for delayed access control 17351 // diagnostics, and it's impossible to get an undelayed error 17352 // here from access control during the original parse because 17353 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 17354 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17355 << Old->getReturnTypeSourceRange(); 17356 return true; 17357 } 17358 } 17359 17360 // The qualifiers of the return types must be the same. 17361 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 17362 Diag(New->getLocation(), 17363 diag::err_covariant_return_type_different_qualifications) 17364 << New->getDeclName() << NewTy << OldTy 17365 << New->getReturnTypeSourceRange(); 17366 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17367 << Old->getReturnTypeSourceRange(); 17368 return true; 17369 } 17370 17371 17372 // The new class type must have the same or less qualifiers as the old type. 17373 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 17374 Diag(New->getLocation(), 17375 diag::err_covariant_return_type_class_type_more_qualified) 17376 << New->getDeclName() << NewTy << OldTy 17377 << New->getReturnTypeSourceRange(); 17378 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17379 << Old->getReturnTypeSourceRange(); 17380 return true; 17381 } 17382 17383 return false; 17384 } 17385 17386 /// Mark the given method pure. 17387 /// 17388 /// \param Method the method to be marked pure. 17389 /// 17390 /// \param InitRange the source range that covers the "0" initializer. 17391 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 17392 SourceLocation EndLoc = InitRange.getEnd(); 17393 if (EndLoc.isValid()) 17394 Method->setRangeEnd(EndLoc); 17395 17396 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 17397 Method->setPure(); 17398 return false; 17399 } 17400 17401 if (!Method->isInvalidDecl()) 17402 Diag(Method->getLocation(), diag::err_non_virtual_pure) 17403 << Method->getDeclName() << InitRange; 17404 return true; 17405 } 17406 17407 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) { 17408 if (D->getFriendObjectKind()) 17409 Diag(D->getLocation(), diag::err_pure_friend); 17410 else if (auto *M = dyn_cast<CXXMethodDecl>(D)) 17411 CheckPureMethod(M, ZeroLoc); 17412 else 17413 Diag(D->getLocation(), diag::err_illegal_initializer); 17414 } 17415 17416 /// Determine whether the given declaration is a global variable or 17417 /// static data member. 17418 static bool isNonlocalVariable(const Decl *D) { 17419 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 17420 return Var->hasGlobalStorage(); 17421 17422 return false; 17423 } 17424 17425 /// Invoked when we are about to parse an initializer for the declaration 17426 /// 'Dcl'. 17427 /// 17428 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 17429 /// static data member of class X, names should be looked up in the scope of 17430 /// class X. If the declaration had a scope specifier, a scope will have 17431 /// been created and passed in for this purpose. Otherwise, S will be null. 17432 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 17433 // If there is no declaration, there was an error parsing it. 17434 if (!D || D->isInvalidDecl()) 17435 return; 17436 17437 // We will always have a nested name specifier here, but this declaration 17438 // might not be out of line if the specifier names the current namespace: 17439 // extern int n; 17440 // int ::n = 0; 17441 if (S && D->isOutOfLine()) 17442 EnterDeclaratorContext(S, D->getDeclContext()); 17443 17444 // If we are parsing the initializer for a static data member, push a 17445 // new expression evaluation context that is associated with this static 17446 // data member. 17447 if (isNonlocalVariable(D)) 17448 PushExpressionEvaluationContext( 17449 ExpressionEvaluationContext::PotentiallyEvaluated, D); 17450 } 17451 17452 /// Invoked after we are finished parsing an initializer for the declaration D. 17453 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 17454 // If there is no declaration, there was an error parsing it. 17455 if (!D || D->isInvalidDecl()) 17456 return; 17457 17458 if (isNonlocalVariable(D)) 17459 PopExpressionEvaluationContext(); 17460 17461 if (S && D->isOutOfLine()) 17462 ExitDeclaratorContext(S); 17463 } 17464 17465 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 17466 /// C++ if/switch/while/for statement. 17467 /// e.g: "if (int x = f()) {...}" 17468 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 17469 // C++ 6.4p2: 17470 // The declarator shall not specify a function or an array. 17471 // The type-specifier-seq shall not contain typedef and shall not declare a 17472 // new class or enumeration. 17473 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 17474 "Parser allowed 'typedef' as storage class of condition decl."); 17475 17476 Decl *Dcl = ActOnDeclarator(S, D); 17477 if (!Dcl) 17478 return true; 17479 17480 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 17481 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 17482 << D.getSourceRange(); 17483 return true; 17484 } 17485 17486 return Dcl; 17487 } 17488 17489 void Sema::LoadExternalVTableUses() { 17490 if (!ExternalSource) 17491 return; 17492 17493 SmallVector<ExternalVTableUse, 4> VTables; 17494 ExternalSource->ReadUsedVTables(VTables); 17495 SmallVector<VTableUse, 4> NewUses; 17496 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 17497 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 17498 = VTablesUsed.find(VTables[I].Record); 17499 // Even if a definition wasn't required before, it may be required now. 17500 if (Pos != VTablesUsed.end()) { 17501 if (!Pos->second && VTables[I].DefinitionRequired) 17502 Pos->second = true; 17503 continue; 17504 } 17505 17506 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 17507 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 17508 } 17509 17510 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 17511 } 17512 17513 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 17514 bool DefinitionRequired) { 17515 // Ignore any vtable uses in unevaluated operands or for classes that do 17516 // not have a vtable. 17517 if (!Class->isDynamicClass() || Class->isDependentContext() || 17518 CurContext->isDependentContext() || isUnevaluatedContext()) 17519 return; 17520 // Do not mark as used if compiling for the device outside of the target 17521 // region. 17522 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice && 17523 !isInOpenMPDeclareTargetContext() && 17524 !isInOpenMPTargetExecutionDirective()) { 17525 if (!DefinitionRequired) 17526 MarkVirtualMembersReferenced(Loc, Class); 17527 return; 17528 } 17529 17530 // Try to insert this class into the map. 17531 LoadExternalVTableUses(); 17532 Class = Class->getCanonicalDecl(); 17533 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 17534 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 17535 if (!Pos.second) { 17536 // If we already had an entry, check to see if we are promoting this vtable 17537 // to require a definition. If so, we need to reappend to the VTableUses 17538 // list, since we may have already processed the first entry. 17539 if (DefinitionRequired && !Pos.first->second) { 17540 Pos.first->second = true; 17541 } else { 17542 // Otherwise, we can early exit. 17543 return; 17544 } 17545 } else { 17546 // The Microsoft ABI requires that we perform the destructor body 17547 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 17548 // the deleting destructor is emitted with the vtable, not with the 17549 // destructor definition as in the Itanium ABI. 17550 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 17551 CXXDestructorDecl *DD = Class->getDestructor(); 17552 if (DD && DD->isVirtual() && !DD->isDeleted()) { 17553 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) { 17554 // If this is an out-of-line declaration, marking it referenced will 17555 // not do anything. Manually call CheckDestructor to look up operator 17556 // delete(). 17557 ContextRAII SavedContext(*this, DD); 17558 CheckDestructor(DD); 17559 } else { 17560 MarkFunctionReferenced(Loc, Class->getDestructor()); 17561 } 17562 } 17563 } 17564 } 17565 17566 // Local classes need to have their virtual members marked 17567 // immediately. For all other classes, we mark their virtual members 17568 // at the end of the translation unit. 17569 if (Class->isLocalClass()) 17570 MarkVirtualMembersReferenced(Loc, Class); 17571 else 17572 VTableUses.push_back(std::make_pair(Class, Loc)); 17573 } 17574 17575 bool Sema::DefineUsedVTables() { 17576 LoadExternalVTableUses(); 17577 if (VTableUses.empty()) 17578 return false; 17579 17580 // Note: The VTableUses vector could grow as a result of marking 17581 // the members of a class as "used", so we check the size each 17582 // time through the loop and prefer indices (which are stable) to 17583 // iterators (which are not). 17584 bool DefinedAnything = false; 17585 for (unsigned I = 0; I != VTableUses.size(); ++I) { 17586 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 17587 if (!Class) 17588 continue; 17589 TemplateSpecializationKind ClassTSK = 17590 Class->getTemplateSpecializationKind(); 17591 17592 SourceLocation Loc = VTableUses[I].second; 17593 17594 bool DefineVTable = true; 17595 17596 // If this class has a key function, but that key function is 17597 // defined in another translation unit, we don't need to emit the 17598 // vtable even though we're using it. 17599 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 17600 if (KeyFunction && !KeyFunction->hasBody()) { 17601 // The key function is in another translation unit. 17602 DefineVTable = false; 17603 TemplateSpecializationKind TSK = 17604 KeyFunction->getTemplateSpecializationKind(); 17605 assert(TSK != TSK_ExplicitInstantiationDefinition && 17606 TSK != TSK_ImplicitInstantiation && 17607 "Instantiations don't have key functions"); 17608 (void)TSK; 17609 } else if (!KeyFunction) { 17610 // If we have a class with no key function that is the subject 17611 // of an explicit instantiation declaration, suppress the 17612 // vtable; it will live with the explicit instantiation 17613 // definition. 17614 bool IsExplicitInstantiationDeclaration = 17615 ClassTSK == TSK_ExplicitInstantiationDeclaration; 17616 for (auto R : Class->redecls()) { 17617 TemplateSpecializationKind TSK 17618 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 17619 if (TSK == TSK_ExplicitInstantiationDeclaration) 17620 IsExplicitInstantiationDeclaration = true; 17621 else if (TSK == TSK_ExplicitInstantiationDefinition) { 17622 IsExplicitInstantiationDeclaration = false; 17623 break; 17624 } 17625 } 17626 17627 if (IsExplicitInstantiationDeclaration) 17628 DefineVTable = false; 17629 } 17630 17631 // The exception specifications for all virtual members may be needed even 17632 // if we are not providing an authoritative form of the vtable in this TU. 17633 // We may choose to emit it available_externally anyway. 17634 if (!DefineVTable) { 17635 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 17636 continue; 17637 } 17638 17639 // Mark all of the virtual members of this class as referenced, so 17640 // that we can build a vtable. Then, tell the AST consumer that a 17641 // vtable for this class is required. 17642 DefinedAnything = true; 17643 MarkVirtualMembersReferenced(Loc, Class); 17644 CXXRecordDecl *Canonical = Class->getCanonicalDecl(); 17645 if (VTablesUsed[Canonical]) 17646 Consumer.HandleVTable(Class); 17647 17648 // Warn if we're emitting a weak vtable. The vtable will be weak if there is 17649 // no key function or the key function is inlined. Don't warn in C++ ABIs 17650 // that lack key functions, since the user won't be able to make one. 17651 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() && 17652 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation && 17653 ClassTSK != TSK_ExplicitInstantiationDefinition) { 17654 const FunctionDecl *KeyFunctionDef = nullptr; 17655 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) && 17656 KeyFunctionDef->isInlined())) 17657 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class; 17658 } 17659 } 17660 VTableUses.clear(); 17661 17662 return DefinedAnything; 17663 } 17664 17665 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 17666 const CXXRecordDecl *RD) { 17667 for (const auto *I : RD->methods()) 17668 if (I->isVirtual() && !I->isPure()) 17669 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 17670 } 17671 17672 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 17673 const CXXRecordDecl *RD, 17674 bool ConstexprOnly) { 17675 // Mark all functions which will appear in RD's vtable as used. 17676 CXXFinalOverriderMap FinalOverriders; 17677 RD->getFinalOverriders(FinalOverriders); 17678 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 17679 E = FinalOverriders.end(); 17680 I != E; ++I) { 17681 for (OverridingMethods::const_iterator OI = I->second.begin(), 17682 OE = I->second.end(); 17683 OI != OE; ++OI) { 17684 assert(OI->second.size() > 0 && "no final overrider"); 17685 CXXMethodDecl *Overrider = OI->second.front().Method; 17686 17687 // C++ [basic.def.odr]p2: 17688 // [...] A virtual member function is used if it is not pure. [...] 17689 if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr())) 17690 MarkFunctionReferenced(Loc, Overrider); 17691 } 17692 } 17693 17694 // Only classes that have virtual bases need a VTT. 17695 if (RD->getNumVBases() == 0) 17696 return; 17697 17698 for (const auto &I : RD->bases()) { 17699 const auto *Base = 17700 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 17701 if (Base->getNumVBases() == 0) 17702 continue; 17703 MarkVirtualMembersReferenced(Loc, Base); 17704 } 17705 } 17706 17707 /// SetIvarInitializers - This routine builds initialization ASTs for the 17708 /// Objective-C implementation whose ivars need be initialized. 17709 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 17710 if (!getLangOpts().CPlusPlus) 17711 return; 17712 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 17713 SmallVector<ObjCIvarDecl*, 8> ivars; 17714 CollectIvarsToConstructOrDestruct(OID, ivars); 17715 if (ivars.empty()) 17716 return; 17717 SmallVector<CXXCtorInitializer*, 32> AllToInit; 17718 for (unsigned i = 0; i < ivars.size(); i++) { 17719 FieldDecl *Field = ivars[i]; 17720 if (Field->isInvalidDecl()) 17721 continue; 17722 17723 CXXCtorInitializer *Member; 17724 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 17725 InitializationKind InitKind = 17726 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 17727 17728 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 17729 ExprResult MemberInit = 17730 InitSeq.Perform(*this, InitEntity, InitKind, None); 17731 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 17732 // Note, MemberInit could actually come back empty if no initialization 17733 // is required (e.g., because it would call a trivial default constructor) 17734 if (!MemberInit.get() || MemberInit.isInvalid()) 17735 continue; 17736 17737 Member = 17738 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 17739 SourceLocation(), 17740 MemberInit.getAs<Expr>(), 17741 SourceLocation()); 17742 AllToInit.push_back(Member); 17743 17744 // Be sure that the destructor is accessible and is marked as referenced. 17745 if (const RecordType *RecordTy = 17746 Context.getBaseElementType(Field->getType()) 17747 ->getAs<RecordType>()) { 17748 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 17749 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 17750 MarkFunctionReferenced(Field->getLocation(), Destructor); 17751 CheckDestructorAccess(Field->getLocation(), Destructor, 17752 PDiag(diag::err_access_dtor_ivar) 17753 << Context.getBaseElementType(Field->getType())); 17754 } 17755 } 17756 } 17757 ObjCImplementation->setIvarInitializers(Context, 17758 AllToInit.data(), AllToInit.size()); 17759 } 17760 } 17761 17762 static 17763 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 17764 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid, 17765 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid, 17766 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current, 17767 Sema &S) { 17768 if (Ctor->isInvalidDecl()) 17769 return; 17770 17771 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 17772 17773 // Target may not be determinable yet, for instance if this is a dependent 17774 // call in an uninstantiated template. 17775 if (Target) { 17776 const FunctionDecl *FNTarget = nullptr; 17777 (void)Target->hasBody(FNTarget); 17778 Target = const_cast<CXXConstructorDecl*>( 17779 cast_or_null<CXXConstructorDecl>(FNTarget)); 17780 } 17781 17782 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 17783 // Avoid dereferencing a null pointer here. 17784 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 17785 17786 if (!Current.insert(Canonical).second) 17787 return; 17788 17789 // We know that beyond here, we aren't chaining into a cycle. 17790 if (!Target || !Target->isDelegatingConstructor() || 17791 Target->isInvalidDecl() || Valid.count(TCanonical)) { 17792 Valid.insert(Current.begin(), Current.end()); 17793 Current.clear(); 17794 // We've hit a cycle. 17795 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 17796 Current.count(TCanonical)) { 17797 // If we haven't diagnosed this cycle yet, do so now. 17798 if (!Invalid.count(TCanonical)) { 17799 S.Diag((*Ctor->init_begin())->getSourceLocation(), 17800 diag::warn_delegating_ctor_cycle) 17801 << Ctor; 17802 17803 // Don't add a note for a function delegating directly to itself. 17804 if (TCanonical != Canonical) 17805 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 17806 17807 CXXConstructorDecl *C = Target; 17808 while (C->getCanonicalDecl() != Canonical) { 17809 const FunctionDecl *FNTarget = nullptr; 17810 (void)C->getTargetConstructor()->hasBody(FNTarget); 17811 assert(FNTarget && "Ctor cycle through bodiless function"); 17812 17813 C = const_cast<CXXConstructorDecl*>( 17814 cast<CXXConstructorDecl>(FNTarget)); 17815 S.Diag(C->getLocation(), diag::note_which_delegates_to); 17816 } 17817 } 17818 17819 Invalid.insert(Current.begin(), Current.end()); 17820 Current.clear(); 17821 } else { 17822 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 17823 } 17824 } 17825 17826 17827 void Sema::CheckDelegatingCtorCycles() { 17828 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 17829 17830 for (DelegatingCtorDeclsType::iterator 17831 I = DelegatingCtorDecls.begin(ExternalSource), 17832 E = DelegatingCtorDecls.end(); 17833 I != E; ++I) 17834 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 17835 17836 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI) 17837 (*CI)->setInvalidDecl(); 17838 } 17839 17840 namespace { 17841 /// AST visitor that finds references to the 'this' expression. 17842 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 17843 Sema &S; 17844 17845 public: 17846 explicit FindCXXThisExpr(Sema &S) : S(S) { } 17847 17848 bool VisitCXXThisExpr(CXXThisExpr *E) { 17849 S.Diag(E->getLocation(), diag::err_this_static_member_func) 17850 << E->isImplicit(); 17851 return false; 17852 } 17853 }; 17854 } 17855 17856 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 17857 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 17858 if (!TSInfo) 17859 return false; 17860 17861 TypeLoc TL = TSInfo->getTypeLoc(); 17862 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 17863 if (!ProtoTL) 17864 return false; 17865 17866 // C++11 [expr.prim.general]p3: 17867 // [The expression this] shall not appear before the optional 17868 // cv-qualifier-seq and it shall not appear within the declaration of a 17869 // static member function (although its type and value category are defined 17870 // within a static member function as they are within a non-static member 17871 // function). [ Note: this is because declaration matching does not occur 17872 // until the complete declarator is known. - end note ] 17873 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 17874 FindCXXThisExpr Finder(*this); 17875 17876 // If the return type came after the cv-qualifier-seq, check it now. 17877 if (Proto->hasTrailingReturn() && 17878 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 17879 return true; 17880 17881 // Check the exception specification. 17882 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 17883 return true; 17884 17885 // Check the trailing requires clause 17886 if (Expr *E = Method->getTrailingRequiresClause()) 17887 if (!Finder.TraverseStmt(E)) 17888 return true; 17889 17890 return checkThisInStaticMemberFunctionAttributes(Method); 17891 } 17892 17893 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 17894 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 17895 if (!TSInfo) 17896 return false; 17897 17898 TypeLoc TL = TSInfo->getTypeLoc(); 17899 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 17900 if (!ProtoTL) 17901 return false; 17902 17903 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 17904 FindCXXThisExpr Finder(*this); 17905 17906 switch (Proto->getExceptionSpecType()) { 17907 case EST_Unparsed: 17908 case EST_Uninstantiated: 17909 case EST_Unevaluated: 17910 case EST_BasicNoexcept: 17911 case EST_NoThrow: 17912 case EST_DynamicNone: 17913 case EST_MSAny: 17914 case EST_None: 17915 break; 17916 17917 case EST_DependentNoexcept: 17918 case EST_NoexceptFalse: 17919 case EST_NoexceptTrue: 17920 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 17921 return true; 17922 LLVM_FALLTHROUGH; 17923 17924 case EST_Dynamic: 17925 for (const auto &E : Proto->exceptions()) { 17926 if (!Finder.TraverseType(E)) 17927 return true; 17928 } 17929 break; 17930 } 17931 17932 return false; 17933 } 17934 17935 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 17936 FindCXXThisExpr Finder(*this); 17937 17938 // Check attributes. 17939 for (const auto *A : Method->attrs()) { 17940 // FIXME: This should be emitted by tblgen. 17941 Expr *Arg = nullptr; 17942 ArrayRef<Expr *> Args; 17943 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 17944 Arg = G->getArg(); 17945 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 17946 Arg = G->getArg(); 17947 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 17948 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 17949 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 17950 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 17951 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 17952 Arg = ETLF->getSuccessValue(); 17953 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 17954 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 17955 Arg = STLF->getSuccessValue(); 17956 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 17957 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 17958 Arg = LR->getArg(); 17959 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 17960 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 17961 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 17962 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 17963 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 17964 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 17965 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 17966 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 17967 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 17968 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 17969 17970 if (Arg && !Finder.TraverseStmt(Arg)) 17971 return true; 17972 17973 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 17974 if (!Finder.TraverseStmt(Args[I])) 17975 return true; 17976 } 17977 } 17978 17979 return false; 17980 } 17981 17982 void Sema::checkExceptionSpecification( 17983 bool IsTopLevel, ExceptionSpecificationType EST, 17984 ArrayRef<ParsedType> DynamicExceptions, 17985 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 17986 SmallVectorImpl<QualType> &Exceptions, 17987 FunctionProtoType::ExceptionSpecInfo &ESI) { 17988 Exceptions.clear(); 17989 ESI.Type = EST; 17990 if (EST == EST_Dynamic) { 17991 Exceptions.reserve(DynamicExceptions.size()); 17992 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 17993 // FIXME: Preserve type source info. 17994 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 17995 17996 if (IsTopLevel) { 17997 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 17998 collectUnexpandedParameterPacks(ET, Unexpanded); 17999 if (!Unexpanded.empty()) { 18000 DiagnoseUnexpandedParameterPacks( 18001 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 18002 Unexpanded); 18003 continue; 18004 } 18005 } 18006 18007 // Check that the type is valid for an exception spec, and 18008 // drop it if not. 18009 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 18010 Exceptions.push_back(ET); 18011 } 18012 ESI.Exceptions = Exceptions; 18013 return; 18014 } 18015 18016 if (isComputedNoexcept(EST)) { 18017 assert((NoexceptExpr->isTypeDependent() || 18018 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 18019 Context.BoolTy) && 18020 "Parser should have made sure that the expression is boolean"); 18021 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 18022 ESI.Type = EST_BasicNoexcept; 18023 return; 18024 } 18025 18026 ESI.NoexceptExpr = NoexceptExpr; 18027 return; 18028 } 18029 } 18030 18031 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 18032 ExceptionSpecificationType EST, 18033 SourceRange SpecificationRange, 18034 ArrayRef<ParsedType> DynamicExceptions, 18035 ArrayRef<SourceRange> DynamicExceptionRanges, 18036 Expr *NoexceptExpr) { 18037 if (!MethodD) 18038 return; 18039 18040 // Dig out the method we're referring to. 18041 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 18042 MethodD = FunTmpl->getTemplatedDecl(); 18043 18044 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 18045 if (!Method) 18046 return; 18047 18048 // Check the exception specification. 18049 llvm::SmallVector<QualType, 4> Exceptions; 18050 FunctionProtoType::ExceptionSpecInfo ESI; 18051 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 18052 DynamicExceptionRanges, NoexceptExpr, Exceptions, 18053 ESI); 18054 18055 // Update the exception specification on the function type. 18056 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 18057 18058 if (Method->isStatic()) 18059 checkThisInStaticMemberFunctionExceptionSpec(Method); 18060 18061 if (Method->isVirtual()) { 18062 // Check overrides, which we previously had to delay. 18063 for (const CXXMethodDecl *O : Method->overridden_methods()) 18064 CheckOverridingFunctionExceptionSpec(Method, O); 18065 } 18066 } 18067 18068 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 18069 /// 18070 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 18071 SourceLocation DeclStart, Declarator &D, 18072 Expr *BitWidth, 18073 InClassInitStyle InitStyle, 18074 AccessSpecifier AS, 18075 const ParsedAttr &MSPropertyAttr) { 18076 IdentifierInfo *II = D.getIdentifier(); 18077 if (!II) { 18078 Diag(DeclStart, diag::err_anonymous_property); 18079 return nullptr; 18080 } 18081 SourceLocation Loc = D.getIdentifierLoc(); 18082 18083 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 18084 QualType T = TInfo->getType(); 18085 if (getLangOpts().CPlusPlus) { 18086 CheckExtraCXXDefaultArguments(D); 18087 18088 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 18089 UPPC_DataMemberType)) { 18090 D.setInvalidType(); 18091 T = Context.IntTy; 18092 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 18093 } 18094 } 18095 18096 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 18097 18098 if (D.getDeclSpec().isInlineSpecified()) 18099 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 18100 << getLangOpts().CPlusPlus17; 18101 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 18102 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 18103 diag::err_invalid_thread) 18104 << DeclSpec::getSpecifierName(TSCS); 18105 18106 // Check to see if this name was declared as a member previously 18107 NamedDecl *PrevDecl = nullptr; 18108 LookupResult Previous(*this, II, Loc, LookupMemberName, 18109 ForVisibleRedeclaration); 18110 LookupName(Previous, S); 18111 switch (Previous.getResultKind()) { 18112 case LookupResult::Found: 18113 case LookupResult::FoundUnresolvedValue: 18114 PrevDecl = Previous.getAsSingle<NamedDecl>(); 18115 break; 18116 18117 case LookupResult::FoundOverloaded: 18118 PrevDecl = Previous.getRepresentativeDecl(); 18119 break; 18120 18121 case LookupResult::NotFound: 18122 case LookupResult::NotFoundInCurrentInstantiation: 18123 case LookupResult::Ambiguous: 18124 break; 18125 } 18126 18127 if (PrevDecl && PrevDecl->isTemplateParameter()) { 18128 // Maybe we will complain about the shadowed template parameter. 18129 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 18130 // Just pretend that we didn't see the previous declaration. 18131 PrevDecl = nullptr; 18132 } 18133 18134 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 18135 PrevDecl = nullptr; 18136 18137 SourceLocation TSSL = D.getBeginLoc(); 18138 MSPropertyDecl *NewPD = 18139 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL, 18140 MSPropertyAttr.getPropertyDataGetter(), 18141 MSPropertyAttr.getPropertyDataSetter()); 18142 ProcessDeclAttributes(TUScope, NewPD, D); 18143 NewPD->setAccess(AS); 18144 18145 if (NewPD->isInvalidDecl()) 18146 Record->setInvalidDecl(); 18147 18148 if (D.getDeclSpec().isModulePrivateSpecified()) 18149 NewPD->setModulePrivate(); 18150 18151 if (NewPD->isInvalidDecl() && PrevDecl) { 18152 // Don't introduce NewFD into scope; there's already something 18153 // with the same name in the same scope. 18154 } else if (II) { 18155 PushOnScopeChains(NewPD, S); 18156 } else 18157 Record->addDecl(NewPD); 18158 18159 return NewPD; 18160 } 18161 18162 void Sema::ActOnStartFunctionDeclarationDeclarator( 18163 Declarator &Declarator, unsigned TemplateParameterDepth) { 18164 auto &Info = InventedParameterInfos.emplace_back(); 18165 TemplateParameterList *ExplicitParams = nullptr; 18166 ArrayRef<TemplateParameterList *> ExplicitLists = 18167 Declarator.getTemplateParameterLists(); 18168 if (!ExplicitLists.empty()) { 18169 bool IsMemberSpecialization, IsInvalid; 18170 ExplicitParams = MatchTemplateParametersToScopeSpecifier( 18171 Declarator.getBeginLoc(), Declarator.getIdentifierLoc(), 18172 Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr, 18173 ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid, 18174 /*SuppressDiagnostic=*/true); 18175 } 18176 if (ExplicitParams) { 18177 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth(); 18178 for (NamedDecl *Param : *ExplicitParams) 18179 Info.TemplateParams.push_back(Param); 18180 Info.NumExplicitTemplateParams = ExplicitParams->size(); 18181 } else { 18182 Info.AutoTemplateParameterDepth = TemplateParameterDepth; 18183 Info.NumExplicitTemplateParams = 0; 18184 } 18185 } 18186 18187 void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) { 18188 auto &FSI = InventedParameterInfos.back(); 18189 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) { 18190 if (FSI.NumExplicitTemplateParams != 0) { 18191 TemplateParameterList *ExplicitParams = 18192 Declarator.getTemplateParameterLists().back(); 18193 Declarator.setInventedTemplateParameterList( 18194 TemplateParameterList::Create( 18195 Context, ExplicitParams->getTemplateLoc(), 18196 ExplicitParams->getLAngleLoc(), FSI.TemplateParams, 18197 ExplicitParams->getRAngleLoc(), 18198 ExplicitParams->getRequiresClause())); 18199 } else { 18200 Declarator.setInventedTemplateParameterList( 18201 TemplateParameterList::Create( 18202 Context, SourceLocation(), SourceLocation(), FSI.TemplateParams, 18203 SourceLocation(), /*RequiresClause=*/nullptr)); 18204 } 18205 } 18206 InventedParameterInfos.pop_back(); 18207 } 18208