1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements semantic analysis for C++ declarations. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/AST/ASTConsumer.h" 14 #include "clang/AST/ASTContext.h" 15 #include "clang/AST/ASTLambda.h" 16 #include "clang/AST/ASTMutationListener.h" 17 #include "clang/AST/CXXInheritance.h" 18 #include "clang/AST/CharUnits.h" 19 #include "clang/AST/ComparisonCategories.h" 20 #include "clang/AST/EvaluatedExprVisitor.h" 21 #include "clang/AST/ExprCXX.h" 22 #include "clang/AST/RecordLayout.h" 23 #include "clang/AST/RecursiveASTVisitor.h" 24 #include "clang/AST/StmtVisitor.h" 25 #include "clang/AST/TypeLoc.h" 26 #include "clang/AST/TypeOrdering.h" 27 #include "clang/Basic/AttributeCommonInfo.h" 28 #include "clang/Basic/PartialDiagnostic.h" 29 #include "clang/Basic/TargetInfo.h" 30 #include "clang/Lex/LiteralSupport.h" 31 #include "clang/Lex/Preprocessor.h" 32 #include "clang/Sema/CXXFieldCollector.h" 33 #include "clang/Sema/DeclSpec.h" 34 #include "clang/Sema/Initialization.h" 35 #include "clang/Sema/Lookup.h" 36 #include "clang/Sema/ParsedTemplate.h" 37 #include "clang/Sema/Scope.h" 38 #include "clang/Sema/ScopeInfo.h" 39 #include "clang/Sema/SemaInternal.h" 40 #include "clang/Sema/Template.h" 41 #include "llvm/ADT/ScopeExit.h" 42 #include "llvm/ADT/SmallString.h" 43 #include "llvm/ADT/STLExtras.h" 44 #include "llvm/ADT/StringExtras.h" 45 #include <map> 46 #include <set> 47 48 using namespace clang; 49 50 //===----------------------------------------------------------------------===// 51 // CheckDefaultArgumentVisitor 52 //===----------------------------------------------------------------------===// 53 54 namespace { 55 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 56 /// the default argument of a parameter to determine whether it 57 /// contains any ill-formed subexpressions. For example, this will 58 /// diagnose the use of local variables or parameters within the 59 /// default argument expression. 60 class CheckDefaultArgumentVisitor 61 : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> { 62 Sema &S; 63 const Expr *DefaultArg; 64 65 public: 66 CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg) 67 : S(S), DefaultArg(DefaultArg) {} 68 69 bool VisitExpr(const Expr *Node); 70 bool VisitDeclRefExpr(const DeclRefExpr *DRE); 71 bool VisitCXXThisExpr(const CXXThisExpr *ThisE); 72 bool VisitLambdaExpr(const LambdaExpr *Lambda); 73 bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE); 74 }; 75 76 /// VisitExpr - Visit all of the children of this expression. 77 bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) { 78 bool IsInvalid = false; 79 for (const Stmt *SubStmt : Node->children()) 80 IsInvalid |= Visit(SubStmt); 81 return IsInvalid; 82 } 83 84 /// VisitDeclRefExpr - Visit a reference to a declaration, to 85 /// determine whether this declaration can be used in the default 86 /// argument expression. 87 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) { 88 const NamedDecl *Decl = DRE->getDecl(); 89 if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) { 90 // C++ [dcl.fct.default]p9: 91 // [...] parameters of a function shall not be used in default 92 // argument expressions, even if they are not evaluated. [...] 93 // 94 // C++17 [dcl.fct.default]p9 (by CWG 2082): 95 // [...] A parameter shall not appear as a potentially-evaluated 96 // expression in a default argument. [...] 97 // 98 if (DRE->isNonOdrUse() != NOUR_Unevaluated) 99 return S.Diag(DRE->getBeginLoc(), 100 diag::err_param_default_argument_references_param) 101 << Param->getDeclName() << DefaultArg->getSourceRange(); 102 } else if (const auto *VDecl = dyn_cast<VarDecl>(Decl)) { 103 // C++ [dcl.fct.default]p7: 104 // Local variables shall not be used in default argument 105 // expressions. 106 // 107 // C++17 [dcl.fct.default]p7 (by CWG 2082): 108 // A local variable shall not appear as a potentially-evaluated 109 // expression in a default argument. 110 // 111 // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346): 112 // Note: A local variable cannot be odr-used (6.3) in a default argument. 113 // 114 if (VDecl->isLocalVarDecl() && !DRE->isNonOdrUse()) 115 return S.Diag(DRE->getBeginLoc(), 116 diag::err_param_default_argument_references_local) 117 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 118 } 119 120 return false; 121 } 122 123 /// VisitCXXThisExpr - Visit a C++ "this" expression. 124 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) { 125 // C++ [dcl.fct.default]p8: 126 // The keyword this shall not be used in a default argument of a 127 // member function. 128 return S.Diag(ThisE->getBeginLoc(), 129 diag::err_param_default_argument_references_this) 130 << ThisE->getSourceRange(); 131 } 132 133 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr( 134 const PseudoObjectExpr *POE) { 135 bool Invalid = false; 136 for (const Expr *E : POE->semantics()) { 137 // Look through bindings. 138 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) { 139 E = OVE->getSourceExpr(); 140 assert(E && "pseudo-object binding without source expression?"); 141 } 142 143 Invalid |= Visit(E); 144 } 145 return Invalid; 146 } 147 148 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) { 149 // C++11 [expr.lambda.prim]p13: 150 // A lambda-expression appearing in a default argument shall not 151 // implicitly or explicitly capture any entity. 152 if (Lambda->capture_begin() == Lambda->capture_end()) 153 return false; 154 155 return S.Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg); 156 } 157 } // namespace 158 159 void 160 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc, 161 const CXXMethodDecl *Method) { 162 // If we have an MSAny spec already, don't bother. 163 if (!Method || ComputedEST == EST_MSAny) 164 return; 165 166 const FunctionProtoType *Proto 167 = Method->getType()->getAs<FunctionProtoType>(); 168 Proto = Self->ResolveExceptionSpec(CallLoc, Proto); 169 if (!Proto) 170 return; 171 172 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 173 174 // If we have a throw-all spec at this point, ignore the function. 175 if (ComputedEST == EST_None) 176 return; 177 178 if (EST == EST_None && Method->hasAttr<NoThrowAttr>()) 179 EST = EST_BasicNoexcept; 180 181 switch (EST) { 182 case EST_Unparsed: 183 case EST_Uninstantiated: 184 case EST_Unevaluated: 185 llvm_unreachable("should not see unresolved exception specs here"); 186 187 // If this function can throw any exceptions, make a note of that. 188 case EST_MSAny: 189 case EST_None: 190 // FIXME: Whichever we see last of MSAny and None determines our result. 191 // We should make a consistent, order-independent choice here. 192 ClearExceptions(); 193 ComputedEST = EST; 194 return; 195 case EST_NoexceptFalse: 196 ClearExceptions(); 197 ComputedEST = EST_None; 198 return; 199 // FIXME: If the call to this decl is using any of its default arguments, we 200 // need to search them for potentially-throwing calls. 201 // If this function has a basic noexcept, it doesn't affect the outcome. 202 case EST_BasicNoexcept: 203 case EST_NoexceptTrue: 204 case EST_NoThrow: 205 return; 206 // If we're still at noexcept(true) and there's a throw() callee, 207 // change to that specification. 208 case EST_DynamicNone: 209 if (ComputedEST == EST_BasicNoexcept) 210 ComputedEST = EST_DynamicNone; 211 return; 212 case EST_DependentNoexcept: 213 llvm_unreachable( 214 "should not generate implicit declarations for dependent cases"); 215 case EST_Dynamic: 216 break; 217 } 218 assert(EST == EST_Dynamic && "EST case not considered earlier."); 219 assert(ComputedEST != EST_None && 220 "Shouldn't collect exceptions when throw-all is guaranteed."); 221 ComputedEST = EST_Dynamic; 222 // Record the exceptions in this function's exception specification. 223 for (const auto &E : Proto->exceptions()) 224 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second) 225 Exceptions.push_back(E); 226 } 227 228 void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) { 229 if (!S || ComputedEST == EST_MSAny) 230 return; 231 232 // FIXME: 233 // 234 // C++0x [except.spec]p14: 235 // [An] implicit exception-specification specifies the type-id T if and 236 // only if T is allowed by the exception-specification of a function directly 237 // invoked by f's implicit definition; f shall allow all exceptions if any 238 // function it directly invokes allows all exceptions, and f shall allow no 239 // exceptions if every function it directly invokes allows no exceptions. 240 // 241 // Note in particular that if an implicit exception-specification is generated 242 // for a function containing a throw-expression, that specification can still 243 // be noexcept(true). 244 // 245 // Note also that 'directly invoked' is not defined in the standard, and there 246 // is no indication that we should only consider potentially-evaluated calls. 247 // 248 // Ultimately we should implement the intent of the standard: the exception 249 // specification should be the set of exceptions which can be thrown by the 250 // implicit definition. For now, we assume that any non-nothrow expression can 251 // throw any exception. 252 253 if (Self->canThrow(S)) 254 ComputedEST = EST_None; 255 } 256 257 ExprResult Sema::ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 258 SourceLocation EqualLoc) { 259 if (RequireCompleteType(Param->getLocation(), Param->getType(), 260 diag::err_typecheck_decl_incomplete_type)) 261 return true; 262 263 // C++ [dcl.fct.default]p5 264 // A default argument expression is implicitly converted (clause 265 // 4) to the parameter type. The default argument expression has 266 // the same semantic constraints as the initializer expression in 267 // a declaration of a variable of the parameter type, using the 268 // copy-initialization semantics (8.5). 269 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 270 Param); 271 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 272 EqualLoc); 273 InitializationSequence InitSeq(*this, Entity, Kind, Arg); 274 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); 275 if (Result.isInvalid()) 276 return true; 277 Arg = Result.getAs<Expr>(); 278 279 CheckCompletedExpr(Arg, EqualLoc); 280 Arg = MaybeCreateExprWithCleanups(Arg); 281 282 return Arg; 283 } 284 285 void Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 286 SourceLocation EqualLoc) { 287 // Add the default argument to the parameter 288 Param->setDefaultArg(Arg); 289 290 // We have already instantiated this parameter; provide each of the 291 // instantiations with the uninstantiated default argument. 292 UnparsedDefaultArgInstantiationsMap::iterator InstPos 293 = UnparsedDefaultArgInstantiations.find(Param); 294 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 295 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 296 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 297 298 // We're done tracking this parameter's instantiations. 299 UnparsedDefaultArgInstantiations.erase(InstPos); 300 } 301 } 302 303 /// ActOnParamDefaultArgument - Check whether the default argument 304 /// provided for a function parameter is well-formed. If so, attach it 305 /// to the parameter declaration. 306 void 307 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 308 Expr *DefaultArg) { 309 if (!param || !DefaultArg) 310 return; 311 312 ParmVarDecl *Param = cast<ParmVarDecl>(param); 313 UnparsedDefaultArgLocs.erase(Param); 314 315 auto Fail = [&] { 316 Param->setInvalidDecl(); 317 Param->setDefaultArg(new (Context) OpaqueValueExpr( 318 EqualLoc, Param->getType().getNonReferenceType(), VK_PRValue)); 319 }; 320 321 // Default arguments are only permitted in C++ 322 if (!getLangOpts().CPlusPlus) { 323 Diag(EqualLoc, diag::err_param_default_argument) 324 << DefaultArg->getSourceRange(); 325 return Fail(); 326 } 327 328 // Check for unexpanded parameter packs. 329 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 330 return Fail(); 331 } 332 333 // C++11 [dcl.fct.default]p3 334 // A default argument expression [...] shall not be specified for a 335 // parameter pack. 336 if (Param->isParameterPack()) { 337 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack) 338 << DefaultArg->getSourceRange(); 339 // Recover by discarding the default argument. 340 Param->setDefaultArg(nullptr); 341 return; 342 } 343 344 ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc); 345 if (Result.isInvalid()) 346 return Fail(); 347 348 DefaultArg = Result.getAs<Expr>(); 349 350 // Check that the default argument is well-formed 351 CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg); 352 if (DefaultArgChecker.Visit(DefaultArg)) 353 return Fail(); 354 355 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 356 } 357 358 /// ActOnParamUnparsedDefaultArgument - We've seen a default 359 /// argument for a function parameter, but we can't parse it yet 360 /// because we're inside a class definition. Note that this default 361 /// argument will be parsed later. 362 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 363 SourceLocation EqualLoc, 364 SourceLocation ArgLoc) { 365 if (!param) 366 return; 367 368 ParmVarDecl *Param = cast<ParmVarDecl>(param); 369 Param->setUnparsedDefaultArg(); 370 UnparsedDefaultArgLocs[Param] = ArgLoc; 371 } 372 373 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 374 /// the default argument for the parameter param failed. 375 void Sema::ActOnParamDefaultArgumentError(Decl *param, 376 SourceLocation EqualLoc) { 377 if (!param) 378 return; 379 380 ParmVarDecl *Param = cast<ParmVarDecl>(param); 381 Param->setInvalidDecl(); 382 UnparsedDefaultArgLocs.erase(Param); 383 Param->setDefaultArg(new (Context) OpaqueValueExpr( 384 EqualLoc, Param->getType().getNonReferenceType(), VK_PRValue)); 385 } 386 387 /// CheckExtraCXXDefaultArguments - Check for any extra default 388 /// arguments in the declarator, which is not a function declaration 389 /// or definition and therefore is not permitted to have default 390 /// arguments. This routine should be invoked for every declarator 391 /// that is not a function declaration or definition. 392 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 393 // C++ [dcl.fct.default]p3 394 // A default argument expression shall be specified only in the 395 // parameter-declaration-clause of a function declaration or in a 396 // template-parameter (14.1). It shall not be specified for a 397 // parameter pack. If it is specified in a 398 // parameter-declaration-clause, it shall not occur within a 399 // declarator or abstract-declarator of a parameter-declaration. 400 bool MightBeFunction = D.isFunctionDeclarationContext(); 401 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 402 DeclaratorChunk &chunk = D.getTypeObject(i); 403 if (chunk.Kind == DeclaratorChunk::Function) { 404 if (MightBeFunction) { 405 // This is a function declaration. It can have default arguments, but 406 // keep looking in case its return type is a function type with default 407 // arguments. 408 MightBeFunction = false; 409 continue; 410 } 411 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e; 412 ++argIdx) { 413 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param); 414 if (Param->hasUnparsedDefaultArg()) { 415 std::unique_ptr<CachedTokens> Toks = 416 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens); 417 SourceRange SR; 418 if (Toks->size() > 1) 419 SR = SourceRange((*Toks)[1].getLocation(), 420 Toks->back().getLocation()); 421 else 422 SR = UnparsedDefaultArgLocs[Param]; 423 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 424 << SR; 425 } else if (Param->getDefaultArg()) { 426 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 427 << Param->getDefaultArg()->getSourceRange(); 428 Param->setDefaultArg(nullptr); 429 } 430 } 431 } else if (chunk.Kind != DeclaratorChunk::Paren) { 432 MightBeFunction = false; 433 } 434 } 435 } 436 437 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { 438 return std::any_of(FD->param_begin(), FD->param_end(), [](ParmVarDecl *P) { 439 return P->hasDefaultArg() && !P->hasInheritedDefaultArg(); 440 }); 441 } 442 443 /// MergeCXXFunctionDecl - Merge two declarations of the same C++ 444 /// function, once we already know that they have the same 445 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an 446 /// error, false otherwise. 447 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 448 Scope *S) { 449 bool Invalid = false; 450 451 // The declaration context corresponding to the scope is the semantic 452 // parent, unless this is a local function declaration, in which case 453 // it is that surrounding function. 454 DeclContext *ScopeDC = New->isLocalExternDecl() 455 ? New->getLexicalDeclContext() 456 : New->getDeclContext(); 457 458 // Find the previous declaration for the purpose of default arguments. 459 FunctionDecl *PrevForDefaultArgs = Old; 460 for (/**/; PrevForDefaultArgs; 461 // Don't bother looking back past the latest decl if this is a local 462 // extern declaration; nothing else could work. 463 PrevForDefaultArgs = New->isLocalExternDecl() 464 ? nullptr 465 : PrevForDefaultArgs->getPreviousDecl()) { 466 // Ignore hidden declarations. 467 if (!LookupResult::isVisible(*this, PrevForDefaultArgs)) 468 continue; 469 470 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) && 471 !New->isCXXClassMember()) { 472 // Ignore default arguments of old decl if they are not in 473 // the same scope and this is not an out-of-line definition of 474 // a member function. 475 continue; 476 } 477 478 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) { 479 // If only one of these is a local function declaration, then they are 480 // declared in different scopes, even though isDeclInScope may think 481 // they're in the same scope. (If both are local, the scope check is 482 // sufficient, and if neither is local, then they are in the same scope.) 483 continue; 484 } 485 486 // We found the right previous declaration. 487 break; 488 } 489 490 // C++ [dcl.fct.default]p4: 491 // For non-template functions, default arguments can be added in 492 // later declarations of a function in the same 493 // scope. Declarations in different scopes have completely 494 // distinct sets of default arguments. That is, declarations in 495 // inner scopes do not acquire default arguments from 496 // declarations in outer scopes, and vice versa. In a given 497 // function declaration, all parameters subsequent to a 498 // parameter with a default argument shall have default 499 // arguments supplied in this or previous declarations. A 500 // default argument shall not be redefined by a later 501 // declaration (not even to the same value). 502 // 503 // C++ [dcl.fct.default]p6: 504 // Except for member functions of class templates, the default arguments 505 // in a member function definition that appears outside of the class 506 // definition are added to the set of default arguments provided by the 507 // member function declaration in the class definition. 508 for (unsigned p = 0, NumParams = PrevForDefaultArgs 509 ? PrevForDefaultArgs->getNumParams() 510 : 0; 511 p < NumParams; ++p) { 512 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p); 513 ParmVarDecl *NewParam = New->getParamDecl(p); 514 515 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false; 516 bool NewParamHasDfl = NewParam->hasDefaultArg(); 517 518 if (OldParamHasDfl && NewParamHasDfl) { 519 unsigned DiagDefaultParamID = 520 diag::err_param_default_argument_redefinition; 521 522 // MSVC accepts that default parameters be redefined for member functions 523 // of template class. The new default parameter's value is ignored. 524 Invalid = true; 525 if (getLangOpts().MicrosoftExt) { 526 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New); 527 if (MD && MD->getParent()->getDescribedClassTemplate()) { 528 // Merge the old default argument into the new parameter. 529 NewParam->setHasInheritedDefaultArg(); 530 if (OldParam->hasUninstantiatedDefaultArg()) 531 NewParam->setUninstantiatedDefaultArg( 532 OldParam->getUninstantiatedDefaultArg()); 533 else 534 NewParam->setDefaultArg(OldParam->getInit()); 535 DiagDefaultParamID = diag::ext_param_default_argument_redefinition; 536 Invalid = false; 537 } 538 } 539 540 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 541 // hint here. Alternatively, we could walk the type-source information 542 // for NewParam to find the last source location in the type... but it 543 // isn't worth the effort right now. This is the kind of test case that 544 // is hard to get right: 545 // int f(int); 546 // void g(int (*fp)(int) = f); 547 // void g(int (*fp)(int) = &f); 548 Diag(NewParam->getLocation(), DiagDefaultParamID) 549 << NewParam->getDefaultArgRange(); 550 551 // Look for the function declaration where the default argument was 552 // actually written, which may be a declaration prior to Old. 553 for (auto Older = PrevForDefaultArgs; 554 OldParam->hasInheritedDefaultArg(); /**/) { 555 Older = Older->getPreviousDecl(); 556 OldParam = Older->getParamDecl(p); 557 } 558 559 Diag(OldParam->getLocation(), diag::note_previous_definition) 560 << OldParam->getDefaultArgRange(); 561 } else if (OldParamHasDfl) { 562 // Merge the old default argument into the new parameter unless the new 563 // function is a friend declaration in a template class. In the latter 564 // case the default arguments will be inherited when the friend 565 // declaration will be instantiated. 566 if (New->getFriendObjectKind() == Decl::FOK_None || 567 !New->getLexicalDeclContext()->isDependentContext()) { 568 // It's important to use getInit() here; getDefaultArg() 569 // strips off any top-level ExprWithCleanups. 570 NewParam->setHasInheritedDefaultArg(); 571 if (OldParam->hasUnparsedDefaultArg()) 572 NewParam->setUnparsedDefaultArg(); 573 else if (OldParam->hasUninstantiatedDefaultArg()) 574 NewParam->setUninstantiatedDefaultArg( 575 OldParam->getUninstantiatedDefaultArg()); 576 else 577 NewParam->setDefaultArg(OldParam->getInit()); 578 } 579 } else if (NewParamHasDfl) { 580 if (New->getDescribedFunctionTemplate()) { 581 // Paragraph 4, quoted above, only applies to non-template functions. 582 Diag(NewParam->getLocation(), 583 diag::err_param_default_argument_template_redecl) 584 << NewParam->getDefaultArgRange(); 585 Diag(PrevForDefaultArgs->getLocation(), 586 diag::note_template_prev_declaration) 587 << false; 588 } else if (New->getTemplateSpecializationKind() 589 != TSK_ImplicitInstantiation && 590 New->getTemplateSpecializationKind() != TSK_Undeclared) { 591 // C++ [temp.expr.spec]p21: 592 // Default function arguments shall not be specified in a declaration 593 // or a definition for one of the following explicit specializations: 594 // - the explicit specialization of a function template; 595 // - the explicit specialization of a member function template; 596 // - the explicit specialization of a member function of a class 597 // template where the class template specialization to which the 598 // member function specialization belongs is implicitly 599 // instantiated. 600 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 601 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 602 << New->getDeclName() 603 << NewParam->getDefaultArgRange(); 604 } else if (New->getDeclContext()->isDependentContext()) { 605 // C++ [dcl.fct.default]p6 (DR217): 606 // Default arguments for a member function of a class template shall 607 // be specified on the initial declaration of the member function 608 // within the class template. 609 // 610 // Reading the tea leaves a bit in DR217 and its reference to DR205 611 // leads me to the conclusion that one cannot add default function 612 // arguments for an out-of-line definition of a member function of a 613 // dependent type. 614 int WhichKind = 2; 615 if (CXXRecordDecl *Record 616 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 617 if (Record->getDescribedClassTemplate()) 618 WhichKind = 0; 619 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 620 WhichKind = 1; 621 else 622 WhichKind = 2; 623 } 624 625 Diag(NewParam->getLocation(), 626 diag::err_param_default_argument_member_template_redecl) 627 << WhichKind 628 << NewParam->getDefaultArgRange(); 629 } 630 } 631 } 632 633 // DR1344: If a default argument is added outside a class definition and that 634 // default argument makes the function a special member function, the program 635 // is ill-formed. This can only happen for constructors. 636 if (isa<CXXConstructorDecl>(New) && 637 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 638 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 639 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 640 if (NewSM != OldSM) { 641 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 642 assert(NewParam->hasDefaultArg()); 643 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 644 << NewParam->getDefaultArgRange() << NewSM; 645 Diag(Old->getLocation(), diag::note_previous_declaration); 646 } 647 } 648 649 const FunctionDecl *Def; 650 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 651 // template has a constexpr specifier then all its declarations shall 652 // contain the constexpr specifier. 653 if (New->getConstexprKind() != Old->getConstexprKind()) { 654 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 655 << New << static_cast<int>(New->getConstexprKind()) 656 << static_cast<int>(Old->getConstexprKind()); 657 Diag(Old->getLocation(), diag::note_previous_declaration); 658 Invalid = true; 659 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() && 660 Old->isDefined(Def) && 661 // If a friend function is inlined but does not have 'inline' 662 // specifier, it is a definition. Do not report attribute conflict 663 // in this case, redefinition will be diagnosed later. 664 (New->isInlineSpecified() || 665 New->getFriendObjectKind() == Decl::FOK_None)) { 666 // C++11 [dcl.fcn.spec]p4: 667 // If the definition of a function appears in a translation unit before its 668 // first declaration as inline, the program is ill-formed. 669 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 670 Diag(Def->getLocation(), diag::note_previous_definition); 671 Invalid = true; 672 } 673 674 // C++17 [temp.deduct.guide]p3: 675 // Two deduction guide declarations in the same translation unit 676 // for the same class template shall not have equivalent 677 // parameter-declaration-clauses. 678 if (isa<CXXDeductionGuideDecl>(New) && 679 !New->isFunctionTemplateSpecialization() && isVisible(Old)) { 680 Diag(New->getLocation(), diag::err_deduction_guide_redeclared); 681 Diag(Old->getLocation(), diag::note_previous_declaration); 682 } 683 684 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 685 // argument expression, that declaration shall be a definition and shall be 686 // the only declaration of the function or function template in the 687 // translation unit. 688 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 689 functionDeclHasDefaultArgument(Old)) { 690 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 691 Diag(Old->getLocation(), diag::note_previous_declaration); 692 Invalid = true; 693 } 694 695 // C++11 [temp.friend]p4 (DR329): 696 // When a function is defined in a friend function declaration in a class 697 // template, the function is instantiated when the function is odr-used. 698 // The same restrictions on multiple declarations and definitions that 699 // apply to non-template function declarations and definitions also apply 700 // to these implicit definitions. 701 const FunctionDecl *OldDefinition = nullptr; 702 if (New->isThisDeclarationInstantiatedFromAFriendDefinition() && 703 Old->isDefined(OldDefinition, true)) 704 CheckForFunctionRedefinition(New, OldDefinition); 705 706 return Invalid; 707 } 708 709 NamedDecl * 710 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D, 711 MultiTemplateParamsArg TemplateParamLists) { 712 assert(D.isDecompositionDeclarator()); 713 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 714 715 // The syntax only allows a decomposition declarator as a simple-declaration, 716 // a for-range-declaration, or a condition in Clang, but we parse it in more 717 // cases than that. 718 if (!D.mayHaveDecompositionDeclarator()) { 719 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 720 << Decomp.getSourceRange(); 721 return nullptr; 722 } 723 724 if (!TemplateParamLists.empty()) { 725 // FIXME: There's no rule against this, but there are also no rules that 726 // would actually make it usable, so we reject it for now. 727 Diag(TemplateParamLists.front()->getTemplateLoc(), 728 diag::err_decomp_decl_template); 729 return nullptr; 730 } 731 732 Diag(Decomp.getLSquareLoc(), 733 !getLangOpts().CPlusPlus17 734 ? diag::ext_decomp_decl 735 : D.getContext() == DeclaratorContext::Condition 736 ? diag::ext_decomp_decl_cond 737 : diag::warn_cxx14_compat_decomp_decl) 738 << Decomp.getSourceRange(); 739 740 // The semantic context is always just the current context. 741 DeclContext *const DC = CurContext; 742 743 // C++17 [dcl.dcl]/8: 744 // The decl-specifier-seq shall contain only the type-specifier auto 745 // and cv-qualifiers. 746 // C++2a [dcl.dcl]/8: 747 // If decl-specifier-seq contains any decl-specifier other than static, 748 // thread_local, auto, or cv-qualifiers, the program is ill-formed. 749 auto &DS = D.getDeclSpec(); 750 { 751 SmallVector<StringRef, 8> BadSpecifiers; 752 SmallVector<SourceLocation, 8> BadSpecifierLocs; 753 SmallVector<StringRef, 8> CPlusPlus20Specifiers; 754 SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs; 755 if (auto SCS = DS.getStorageClassSpec()) { 756 if (SCS == DeclSpec::SCS_static) { 757 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS)); 758 CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 759 } else { 760 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS)); 761 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 762 } 763 } 764 if (auto TSCS = DS.getThreadStorageClassSpec()) { 765 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS)); 766 CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc()); 767 } 768 if (DS.hasConstexprSpecifier()) { 769 BadSpecifiers.push_back( 770 DeclSpec::getSpecifierName(DS.getConstexprSpecifier())); 771 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc()); 772 } 773 if (DS.isInlineSpecified()) { 774 BadSpecifiers.push_back("inline"); 775 BadSpecifierLocs.push_back(DS.getInlineSpecLoc()); 776 } 777 if (!BadSpecifiers.empty()) { 778 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec); 779 Err << (int)BadSpecifiers.size() 780 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " "); 781 // Don't add FixItHints to remove the specifiers; we do still respect 782 // them when building the underlying variable. 783 for (auto Loc : BadSpecifierLocs) 784 Err << SourceRange(Loc, Loc); 785 } else if (!CPlusPlus20Specifiers.empty()) { 786 auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(), 787 getLangOpts().CPlusPlus20 788 ? diag::warn_cxx17_compat_decomp_decl_spec 789 : diag::ext_decomp_decl_spec); 790 Warn << (int)CPlusPlus20Specifiers.size() 791 << llvm::join(CPlusPlus20Specifiers.begin(), 792 CPlusPlus20Specifiers.end(), " "); 793 for (auto Loc : CPlusPlus20SpecifierLocs) 794 Warn << SourceRange(Loc, Loc); 795 } 796 // We can't recover from it being declared as a typedef. 797 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 798 return nullptr; 799 } 800 801 // C++2a [dcl.struct.bind]p1: 802 // A cv that includes volatile is deprecated 803 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) && 804 getLangOpts().CPlusPlus20) 805 Diag(DS.getVolatileSpecLoc(), 806 diag::warn_deprecated_volatile_structured_binding); 807 808 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 809 QualType R = TInfo->getType(); 810 811 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 812 UPPC_DeclarationType)) 813 D.setInvalidType(); 814 815 // The syntax only allows a single ref-qualifier prior to the decomposition 816 // declarator. No other declarator chunks are permitted. Also check the type 817 // specifier here. 818 if (DS.getTypeSpecType() != DeclSpec::TST_auto || 819 D.hasGroupingParens() || D.getNumTypeObjects() > 1 || 820 (D.getNumTypeObjects() == 1 && 821 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) { 822 Diag(Decomp.getLSquareLoc(), 823 (D.hasGroupingParens() || 824 (D.getNumTypeObjects() && 825 D.getTypeObject(0).Kind == DeclaratorChunk::Paren)) 826 ? diag::err_decomp_decl_parens 827 : diag::err_decomp_decl_type) 828 << R; 829 830 // In most cases, there's no actual problem with an explicitly-specified 831 // type, but a function type won't work here, and ActOnVariableDeclarator 832 // shouldn't be called for such a type. 833 if (R->isFunctionType()) 834 D.setInvalidType(); 835 } 836 837 // Build the BindingDecls. 838 SmallVector<BindingDecl*, 8> Bindings; 839 840 // Build the BindingDecls. 841 for (auto &B : D.getDecompositionDeclarator().bindings()) { 842 // Check for name conflicts. 843 DeclarationNameInfo NameInfo(B.Name, B.NameLoc); 844 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 845 ForVisibleRedeclaration); 846 LookupName(Previous, S, 847 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit()); 848 849 // It's not permitted to shadow a template parameter name. 850 if (Previous.isSingleResult() && 851 Previous.getFoundDecl()->isTemplateParameter()) { 852 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 853 Previous.getFoundDecl()); 854 Previous.clear(); 855 } 856 857 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name); 858 859 // Find the shadowed declaration before filtering for scope. 860 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 861 ? getShadowedDeclaration(BD, Previous) 862 : nullptr; 863 864 bool ConsiderLinkage = DC->isFunctionOrMethod() && 865 DS.getStorageClassSpec() == DeclSpec::SCS_extern; 866 FilterLookupForScope(Previous, DC, S, ConsiderLinkage, 867 /*AllowInlineNamespace*/false); 868 869 if (!Previous.empty()) { 870 auto *Old = Previous.getRepresentativeDecl(); 871 Diag(B.NameLoc, diag::err_redefinition) << B.Name; 872 Diag(Old->getLocation(), diag::note_previous_definition); 873 } else if (ShadowedDecl && !D.isRedeclaration()) { 874 CheckShadow(BD, ShadowedDecl, Previous); 875 } 876 PushOnScopeChains(BD, S, true); 877 Bindings.push_back(BD); 878 ParsingInitForAutoVars.insert(BD); 879 } 880 881 // There are no prior lookup results for the variable itself, because it 882 // is unnamed. 883 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr, 884 Decomp.getLSquareLoc()); 885 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 886 ForVisibleRedeclaration); 887 888 // Build the variable that holds the non-decomposed object. 889 bool AddToScope = true; 890 NamedDecl *New = 891 ActOnVariableDeclarator(S, D, DC, TInfo, Previous, 892 MultiTemplateParamsArg(), AddToScope, Bindings); 893 if (AddToScope) { 894 S->AddDecl(New); 895 CurContext->addHiddenDecl(New); 896 } 897 898 if (isInOpenMPDeclareTargetContext()) 899 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 900 901 return New; 902 } 903 904 static bool checkSimpleDecomposition( 905 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src, 906 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType, 907 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) { 908 if ((int64_t)Bindings.size() != NumElems) { 909 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 910 << DecompType << (unsigned)Bindings.size() 911 << (unsigned)NumElems.getLimitedValue(UINT_MAX) 912 << toString(NumElems, 10) << (NumElems < Bindings.size()); 913 return true; 914 } 915 916 unsigned I = 0; 917 for (auto *B : Bindings) { 918 SourceLocation Loc = B->getLocation(); 919 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 920 if (E.isInvalid()) 921 return true; 922 E = GetInit(Loc, E.get(), I++); 923 if (E.isInvalid()) 924 return true; 925 B->setBinding(ElemType, E.get()); 926 } 927 928 return false; 929 } 930 931 static bool checkArrayLikeDecomposition(Sema &S, 932 ArrayRef<BindingDecl *> Bindings, 933 ValueDecl *Src, QualType DecompType, 934 const llvm::APSInt &NumElems, 935 QualType ElemType) { 936 return checkSimpleDecomposition( 937 S, Bindings, Src, DecompType, NumElems, ElemType, 938 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 939 ExprResult E = S.ActOnIntegerConstant(Loc, I); 940 if (E.isInvalid()) 941 return ExprError(); 942 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc); 943 }); 944 } 945 946 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 947 ValueDecl *Src, QualType DecompType, 948 const ConstantArrayType *CAT) { 949 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType, 950 llvm::APSInt(CAT->getSize()), 951 CAT->getElementType()); 952 } 953 954 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 955 ValueDecl *Src, QualType DecompType, 956 const VectorType *VT) { 957 return checkArrayLikeDecomposition( 958 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()), 959 S.Context.getQualifiedType(VT->getElementType(), 960 DecompType.getQualifiers())); 961 } 962 963 static bool checkComplexDecomposition(Sema &S, 964 ArrayRef<BindingDecl *> Bindings, 965 ValueDecl *Src, QualType DecompType, 966 const ComplexType *CT) { 967 return checkSimpleDecomposition( 968 S, Bindings, Src, DecompType, llvm::APSInt::get(2), 969 S.Context.getQualifiedType(CT->getElementType(), 970 DecompType.getQualifiers()), 971 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 972 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base); 973 }); 974 } 975 976 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy, 977 TemplateArgumentListInfo &Args, 978 const TemplateParameterList *Params) { 979 SmallString<128> SS; 980 llvm::raw_svector_ostream OS(SS); 981 bool First = true; 982 unsigned I = 0; 983 for (auto &Arg : Args.arguments()) { 984 if (!First) 985 OS << ", "; 986 Arg.getArgument().print( 987 PrintingPolicy, OS, 988 TemplateParameterList::shouldIncludeTypeForArgument(Params, I)); 989 First = false; 990 I++; 991 } 992 return std::string(OS.str()); 993 } 994 995 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup, 996 SourceLocation Loc, StringRef Trait, 997 TemplateArgumentListInfo &Args, 998 unsigned DiagID) { 999 auto DiagnoseMissing = [&] { 1000 if (DiagID) 1001 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(), 1002 Args, /*Params*/ nullptr); 1003 return true; 1004 }; 1005 1006 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine. 1007 NamespaceDecl *Std = S.getStdNamespace(); 1008 if (!Std) 1009 return DiagnoseMissing(); 1010 1011 // Look up the trait itself, within namespace std. We can diagnose various 1012 // problems with this lookup even if we've been asked to not diagnose a 1013 // missing specialization, because this can only fail if the user has been 1014 // declaring their own names in namespace std or we don't support the 1015 // standard library implementation in use. 1016 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait), 1017 Loc, Sema::LookupOrdinaryName); 1018 if (!S.LookupQualifiedName(Result, Std)) 1019 return DiagnoseMissing(); 1020 if (Result.isAmbiguous()) 1021 return true; 1022 1023 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>(); 1024 if (!TraitTD) { 1025 Result.suppressDiagnostics(); 1026 NamedDecl *Found = *Result.begin(); 1027 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait; 1028 S.Diag(Found->getLocation(), diag::note_declared_at); 1029 return true; 1030 } 1031 1032 // Build the template-id. 1033 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args); 1034 if (TraitTy.isNull()) 1035 return true; 1036 if (!S.isCompleteType(Loc, TraitTy)) { 1037 if (DiagID) 1038 S.RequireCompleteType( 1039 Loc, TraitTy, DiagID, 1040 printTemplateArgs(S.Context.getPrintingPolicy(), Args, 1041 TraitTD->getTemplateParameters())); 1042 return true; 1043 } 1044 1045 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl(); 1046 assert(RD && "specialization of class template is not a class?"); 1047 1048 // Look up the member of the trait type. 1049 S.LookupQualifiedName(TraitMemberLookup, RD); 1050 return TraitMemberLookup.isAmbiguous(); 1051 } 1052 1053 static TemplateArgumentLoc 1054 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, 1055 uint64_t I) { 1056 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T); 1057 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc); 1058 } 1059 1060 static TemplateArgumentLoc 1061 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) { 1062 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc); 1063 } 1064 1065 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; } 1066 1067 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, 1068 llvm::APSInt &Size) { 1069 EnterExpressionEvaluationContext ContextRAII( 1070 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 1071 1072 DeclarationName Value = S.PP.getIdentifierInfo("value"); 1073 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName); 1074 1075 // Form template argument list for tuple_size<T>. 1076 TemplateArgumentListInfo Args(Loc, Loc); 1077 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1078 1079 // If there's no tuple_size specialization or the lookup of 'value' is empty, 1080 // it's not tuple-like. 1081 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) || 1082 R.empty()) 1083 return IsTupleLike::NotTupleLike; 1084 1085 // If we get this far, we've committed to the tuple interpretation, but 1086 // we can still fail if there actually isn't a usable ::value. 1087 1088 struct ICEDiagnoser : Sema::VerifyICEDiagnoser { 1089 LookupResult &R; 1090 TemplateArgumentListInfo &Args; 1091 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args) 1092 : R(R), Args(Args) {} 1093 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S, 1094 SourceLocation Loc) override { 1095 return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant) 1096 << printTemplateArgs(S.Context.getPrintingPolicy(), Args, 1097 /*Params*/ nullptr); 1098 } 1099 } Diagnoser(R, Args); 1100 1101 ExprResult E = 1102 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false); 1103 if (E.isInvalid()) 1104 return IsTupleLike::Error; 1105 1106 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser); 1107 if (E.isInvalid()) 1108 return IsTupleLike::Error; 1109 1110 return IsTupleLike::TupleLike; 1111 } 1112 1113 /// \return std::tuple_element<I, T>::type. 1114 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, 1115 unsigned I, QualType T) { 1116 // Form template argument list for tuple_element<I, T>. 1117 TemplateArgumentListInfo Args(Loc, Loc); 1118 Args.addArgument( 1119 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1120 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1121 1122 DeclarationName TypeDN = S.PP.getIdentifierInfo("type"); 1123 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName); 1124 if (lookupStdTypeTraitMember( 1125 S, R, Loc, "tuple_element", Args, 1126 diag::err_decomp_decl_std_tuple_element_not_specialized)) 1127 return QualType(); 1128 1129 auto *TD = R.getAsSingle<TypeDecl>(); 1130 if (!TD) { 1131 R.suppressDiagnostics(); 1132 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized) 1133 << printTemplateArgs(S.Context.getPrintingPolicy(), Args, 1134 /*Params*/ nullptr); 1135 if (!R.empty()) 1136 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at); 1137 return QualType(); 1138 } 1139 1140 return S.Context.getTypeDeclType(TD); 1141 } 1142 1143 namespace { 1144 struct InitializingBinding { 1145 Sema &S; 1146 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) { 1147 Sema::CodeSynthesisContext Ctx; 1148 Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding; 1149 Ctx.PointOfInstantiation = BD->getLocation(); 1150 Ctx.Entity = BD; 1151 S.pushCodeSynthesisContext(Ctx); 1152 } 1153 ~InitializingBinding() { 1154 S.popCodeSynthesisContext(); 1155 } 1156 }; 1157 } 1158 1159 static bool checkTupleLikeDecomposition(Sema &S, 1160 ArrayRef<BindingDecl *> Bindings, 1161 VarDecl *Src, QualType DecompType, 1162 const llvm::APSInt &TupleSize) { 1163 if ((int64_t)Bindings.size() != TupleSize) { 1164 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1165 << DecompType << (unsigned)Bindings.size() 1166 << (unsigned)TupleSize.getLimitedValue(UINT_MAX) 1167 << toString(TupleSize, 10) << (TupleSize < Bindings.size()); 1168 return true; 1169 } 1170 1171 if (Bindings.empty()) 1172 return false; 1173 1174 DeclarationName GetDN = S.PP.getIdentifierInfo("get"); 1175 1176 // [dcl.decomp]p3: 1177 // The unqualified-id get is looked up in the scope of E by class member 1178 // access lookup ... 1179 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName); 1180 bool UseMemberGet = false; 1181 if (S.isCompleteType(Src->getLocation(), DecompType)) { 1182 if (auto *RD = DecompType->getAsCXXRecordDecl()) 1183 S.LookupQualifiedName(MemberGet, RD); 1184 if (MemberGet.isAmbiguous()) 1185 return true; 1186 // ... and if that finds at least one declaration that is a function 1187 // template whose first template parameter is a non-type parameter ... 1188 for (NamedDecl *D : MemberGet) { 1189 if (FunctionTemplateDecl *FTD = 1190 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) { 1191 TemplateParameterList *TPL = FTD->getTemplateParameters(); 1192 if (TPL->size() != 0 && 1193 isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) { 1194 // ... the initializer is e.get<i>(). 1195 UseMemberGet = true; 1196 break; 1197 } 1198 } 1199 } 1200 } 1201 1202 unsigned I = 0; 1203 for (auto *B : Bindings) { 1204 InitializingBinding InitContext(S, B); 1205 SourceLocation Loc = B->getLocation(); 1206 1207 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1208 if (E.isInvalid()) 1209 return true; 1210 1211 // e is an lvalue if the type of the entity is an lvalue reference and 1212 // an xvalue otherwise 1213 if (!Src->getType()->isLValueReferenceType()) 1214 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp, 1215 E.get(), nullptr, VK_XValue, 1216 FPOptionsOverride()); 1217 1218 TemplateArgumentListInfo Args(Loc, Loc); 1219 Args.addArgument( 1220 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1221 1222 if (UseMemberGet) { 1223 // if [lookup of member get] finds at least one declaration, the 1224 // initializer is e.get<i-1>(). 1225 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false, 1226 CXXScopeSpec(), SourceLocation(), nullptr, 1227 MemberGet, &Args, nullptr); 1228 if (E.isInvalid()) 1229 return true; 1230 1231 E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc); 1232 } else { 1233 // Otherwise, the initializer is get<i-1>(e), where get is looked up 1234 // in the associated namespaces. 1235 Expr *Get = UnresolvedLookupExpr::Create( 1236 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(), 1237 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args, 1238 UnresolvedSetIterator(), UnresolvedSetIterator()); 1239 1240 Expr *Arg = E.get(); 1241 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc); 1242 } 1243 if (E.isInvalid()) 1244 return true; 1245 Expr *Init = E.get(); 1246 1247 // Given the type T designated by std::tuple_element<i - 1, E>::type, 1248 QualType T = getTupleLikeElementType(S, Loc, I, DecompType); 1249 if (T.isNull()) 1250 return true; 1251 1252 // each vi is a variable of type "reference to T" initialized with the 1253 // initializer, where the reference is an lvalue reference if the 1254 // initializer is an lvalue and an rvalue reference otherwise 1255 QualType RefType = 1256 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName()); 1257 if (RefType.isNull()) 1258 return true; 1259 auto *RefVD = VarDecl::Create( 1260 S.Context, Src->getDeclContext(), Loc, Loc, 1261 B->getDeclName().getAsIdentifierInfo(), RefType, 1262 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass()); 1263 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext()); 1264 RefVD->setTSCSpec(Src->getTSCSpec()); 1265 RefVD->setImplicit(); 1266 if (Src->isInlineSpecified()) 1267 RefVD->setInlineSpecified(); 1268 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD); 1269 1270 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD); 1271 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc); 1272 InitializationSequence Seq(S, Entity, Kind, Init); 1273 E = Seq.Perform(S, Entity, Kind, Init); 1274 if (E.isInvalid()) 1275 return true; 1276 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false); 1277 if (E.isInvalid()) 1278 return true; 1279 RefVD->setInit(E.get()); 1280 S.CheckCompleteVariableDeclaration(RefVD); 1281 1282 E = S.BuildDeclarationNameExpr(CXXScopeSpec(), 1283 DeclarationNameInfo(B->getDeclName(), Loc), 1284 RefVD); 1285 if (E.isInvalid()) 1286 return true; 1287 1288 B->setBinding(T, E.get()); 1289 I++; 1290 } 1291 1292 return false; 1293 } 1294 1295 /// Find the base class to decompose in a built-in decomposition of a class type. 1296 /// This base class search is, unfortunately, not quite like any other that we 1297 /// perform anywhere else in C++. 1298 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc, 1299 const CXXRecordDecl *RD, 1300 CXXCastPath &BasePath) { 1301 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier, 1302 CXXBasePath &Path) { 1303 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields(); 1304 }; 1305 1306 const CXXRecordDecl *ClassWithFields = nullptr; 1307 AccessSpecifier AS = AS_public; 1308 if (RD->hasDirectFields()) 1309 // [dcl.decomp]p4: 1310 // Otherwise, all of E's non-static data members shall be public direct 1311 // members of E ... 1312 ClassWithFields = RD; 1313 else { 1314 // ... or of ... 1315 CXXBasePaths Paths; 1316 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD)); 1317 if (!RD->lookupInBases(BaseHasFields, Paths)) { 1318 // If no classes have fields, just decompose RD itself. (This will work 1319 // if and only if zero bindings were provided.) 1320 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public); 1321 } 1322 1323 CXXBasePath *BestPath = nullptr; 1324 for (auto &P : Paths) { 1325 if (!BestPath) 1326 BestPath = &P; 1327 else if (!S.Context.hasSameType(P.back().Base->getType(), 1328 BestPath->back().Base->getType())) { 1329 // ... the same ... 1330 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1331 << false << RD << BestPath->back().Base->getType() 1332 << P.back().Base->getType(); 1333 return DeclAccessPair(); 1334 } else if (P.Access < BestPath->Access) { 1335 BestPath = &P; 1336 } 1337 } 1338 1339 // ... unambiguous ... 1340 QualType BaseType = BestPath->back().Base->getType(); 1341 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) { 1342 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base) 1343 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths); 1344 return DeclAccessPair(); 1345 } 1346 1347 // ... [accessible, implied by other rules] base class of E. 1348 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD), 1349 *BestPath, diag::err_decomp_decl_inaccessible_base); 1350 AS = BestPath->Access; 1351 1352 ClassWithFields = BaseType->getAsCXXRecordDecl(); 1353 S.BuildBasePathArray(Paths, BasePath); 1354 } 1355 1356 // The above search did not check whether the selected class itself has base 1357 // classes with fields, so check that now. 1358 CXXBasePaths Paths; 1359 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) { 1360 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1361 << (ClassWithFields == RD) << RD << ClassWithFields 1362 << Paths.front().back().Base->getType(); 1363 return DeclAccessPair(); 1364 } 1365 1366 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS); 1367 } 1368 1369 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 1370 ValueDecl *Src, QualType DecompType, 1371 const CXXRecordDecl *OrigRD) { 1372 if (S.RequireCompleteType(Src->getLocation(), DecompType, 1373 diag::err_incomplete_type)) 1374 return true; 1375 1376 CXXCastPath BasePath; 1377 DeclAccessPair BasePair = 1378 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath); 1379 const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl()); 1380 if (!RD) 1381 return true; 1382 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD), 1383 DecompType.getQualifiers()); 1384 1385 auto DiagnoseBadNumberOfBindings = [&]() -> bool { 1386 unsigned NumFields = 1387 std::count_if(RD->field_begin(), RD->field_end(), 1388 [](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::CompoundStmtClass: { 2054 // C++1y allows compound-statements. 2055 if (!Cxx1yLoc.isValid()) 2056 Cxx1yLoc = S->getBeginLoc(); 2057 2058 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 2059 for (auto *BodyIt : CompStmt->body()) { 2060 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 2061 Cxx1yLoc, Cxx2aLoc, Kind)) 2062 return false; 2063 } 2064 return true; 2065 } 2066 2067 case Stmt::AttributedStmtClass: 2068 if (!Cxx1yLoc.isValid()) 2069 Cxx1yLoc = S->getBeginLoc(); 2070 return true; 2071 2072 case Stmt::IfStmtClass: { 2073 // C++1y allows if-statements. 2074 if (!Cxx1yLoc.isValid()) 2075 Cxx1yLoc = S->getBeginLoc(); 2076 2077 IfStmt *If = cast<IfStmt>(S); 2078 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 2079 Cxx1yLoc, Cxx2aLoc, Kind)) 2080 return false; 2081 if (If->getElse() && 2082 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 2083 Cxx1yLoc, Cxx2aLoc, Kind)) 2084 return false; 2085 return true; 2086 } 2087 2088 case Stmt::WhileStmtClass: 2089 case Stmt::DoStmtClass: 2090 case Stmt::ForStmtClass: 2091 case Stmt::CXXForRangeStmtClass: 2092 case Stmt::ContinueStmtClass: 2093 // C++1y allows all of these. We don't allow them as extensions in C++11, 2094 // because they don't make sense without variable mutation. 2095 if (!SemaRef.getLangOpts().CPlusPlus14) 2096 break; 2097 if (!Cxx1yLoc.isValid()) 2098 Cxx1yLoc = S->getBeginLoc(); 2099 for (Stmt *SubStmt : S->children()) 2100 if (SubStmt && 2101 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2102 Cxx1yLoc, Cxx2aLoc, Kind)) 2103 return false; 2104 return true; 2105 2106 case Stmt::SwitchStmtClass: 2107 case Stmt::CaseStmtClass: 2108 case Stmt::DefaultStmtClass: 2109 case Stmt::BreakStmtClass: 2110 // C++1y allows switch-statements, and since they don't need variable 2111 // mutation, we can reasonably allow them in C++11 as an extension. 2112 if (!Cxx1yLoc.isValid()) 2113 Cxx1yLoc = S->getBeginLoc(); 2114 for (Stmt *SubStmt : S->children()) 2115 if (SubStmt && 2116 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2117 Cxx1yLoc, Cxx2aLoc, Kind)) 2118 return false; 2119 return true; 2120 2121 case Stmt::GCCAsmStmtClass: 2122 case Stmt::MSAsmStmtClass: 2123 // C++2a allows inline assembly statements. 2124 case Stmt::CXXTryStmtClass: 2125 if (Cxx2aLoc.isInvalid()) 2126 Cxx2aLoc = S->getBeginLoc(); 2127 for (Stmt *SubStmt : S->children()) { 2128 if (SubStmt && 2129 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2130 Cxx1yLoc, Cxx2aLoc, Kind)) 2131 return false; 2132 } 2133 return true; 2134 2135 case Stmt::CXXCatchStmtClass: 2136 // Do not bother checking the language mode (already covered by the 2137 // try block check). 2138 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, 2139 cast<CXXCatchStmt>(S)->getHandlerBlock(), 2140 ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind)) 2141 return false; 2142 return true; 2143 2144 default: 2145 if (!isa<Expr>(S)) 2146 break; 2147 2148 // C++1y allows expression-statements. 2149 if (!Cxx1yLoc.isValid()) 2150 Cxx1yLoc = S->getBeginLoc(); 2151 return true; 2152 } 2153 2154 if (Kind == Sema::CheckConstexprKind::Diagnose) { 2155 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 2156 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 2157 } 2158 return false; 2159 } 2160 2161 /// Check the body for the given constexpr function declaration only contains 2162 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 2163 /// 2164 /// \return true if the body is OK, false if we have found or diagnosed a 2165 /// problem. 2166 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, 2167 Stmt *Body, 2168 Sema::CheckConstexprKind Kind) { 2169 SmallVector<SourceLocation, 4> ReturnStmts; 2170 2171 if (isa<CXXTryStmt>(Body)) { 2172 // C++11 [dcl.constexpr]p3: 2173 // The definition of a constexpr function shall satisfy the following 2174 // constraints: [...] 2175 // - its function-body shall be = delete, = default, or a 2176 // compound-statement 2177 // 2178 // C++11 [dcl.constexpr]p4: 2179 // In the definition of a constexpr constructor, [...] 2180 // - its function-body shall not be a function-try-block; 2181 // 2182 // This restriction is lifted in C++2a, as long as inner statements also 2183 // apply the general constexpr rules. 2184 switch (Kind) { 2185 case Sema::CheckConstexprKind::CheckValid: 2186 if (!SemaRef.getLangOpts().CPlusPlus20) 2187 return false; 2188 break; 2189 2190 case Sema::CheckConstexprKind::Diagnose: 2191 SemaRef.Diag(Body->getBeginLoc(), 2192 !SemaRef.getLangOpts().CPlusPlus20 2193 ? diag::ext_constexpr_function_try_block_cxx20 2194 : diag::warn_cxx17_compat_constexpr_function_try_block) 2195 << isa<CXXConstructorDecl>(Dcl); 2196 break; 2197 } 2198 } 2199 2200 // - its function-body shall be [...] a compound-statement that contains only 2201 // [... list of cases ...] 2202 // 2203 // Note that walking the children here is enough to properly check for 2204 // CompoundStmt and CXXTryStmt body. 2205 SourceLocation Cxx1yLoc, Cxx2aLoc; 2206 for (Stmt *SubStmt : Body->children()) { 2207 if (SubStmt && 2208 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2209 Cxx1yLoc, Cxx2aLoc, Kind)) 2210 return false; 2211 } 2212 2213 if (Kind == Sema::CheckConstexprKind::CheckValid) { 2214 // If this is only valid as an extension, report that we don't satisfy the 2215 // constraints of the current language. 2216 if ((Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) || 2217 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17)) 2218 return false; 2219 } else if (Cxx2aLoc.isValid()) { 2220 SemaRef.Diag(Cxx2aLoc, 2221 SemaRef.getLangOpts().CPlusPlus20 2222 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt 2223 : diag::ext_constexpr_body_invalid_stmt_cxx20) 2224 << isa<CXXConstructorDecl>(Dcl); 2225 } else if (Cxx1yLoc.isValid()) { 2226 SemaRef.Diag(Cxx1yLoc, 2227 SemaRef.getLangOpts().CPlusPlus14 2228 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 2229 : diag::ext_constexpr_body_invalid_stmt) 2230 << isa<CXXConstructorDecl>(Dcl); 2231 } 2232 2233 if (const CXXConstructorDecl *Constructor 2234 = dyn_cast<CXXConstructorDecl>(Dcl)) { 2235 const CXXRecordDecl *RD = Constructor->getParent(); 2236 // DR1359: 2237 // - every non-variant non-static data member and base class sub-object 2238 // shall be initialized; 2239 // DR1460: 2240 // - if the class is a union having variant members, exactly one of them 2241 // shall be initialized; 2242 if (RD->isUnion()) { 2243 if (Constructor->getNumCtorInitializers() == 0 && 2244 RD->hasVariantMembers()) { 2245 if (Kind == Sema::CheckConstexprKind::Diagnose) { 2246 SemaRef.Diag( 2247 Dcl->getLocation(), 2248 SemaRef.getLangOpts().CPlusPlus20 2249 ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init 2250 : diag::ext_constexpr_union_ctor_no_init); 2251 } else if (!SemaRef.getLangOpts().CPlusPlus20) { 2252 return false; 2253 } 2254 } 2255 } else if (!Constructor->isDependentContext() && 2256 !Constructor->isDelegatingConstructor()) { 2257 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 2258 2259 // Skip detailed checking if we have enough initializers, and we would 2260 // allow at most one initializer per member. 2261 bool AnyAnonStructUnionMembers = false; 2262 unsigned Fields = 0; 2263 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 2264 E = RD->field_end(); I != E; ++I, ++Fields) { 2265 if (I->isAnonymousStructOrUnion()) { 2266 AnyAnonStructUnionMembers = true; 2267 break; 2268 } 2269 } 2270 // DR1460: 2271 // - if the class is a union-like class, but is not a union, for each of 2272 // its anonymous union members having variant members, exactly one of 2273 // them shall be initialized; 2274 if (AnyAnonStructUnionMembers || 2275 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 2276 // Check initialization of non-static data members. Base classes are 2277 // always initialized so do not need to be checked. Dependent bases 2278 // might not have initializers in the member initializer list. 2279 llvm::SmallSet<Decl*, 16> Inits; 2280 for (const auto *I: Constructor->inits()) { 2281 if (FieldDecl *FD = I->getMember()) 2282 Inits.insert(FD); 2283 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 2284 Inits.insert(ID->chain_begin(), ID->chain_end()); 2285 } 2286 2287 bool Diagnosed = false; 2288 for (auto *I : RD->fields()) 2289 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, 2290 Kind)) 2291 return false; 2292 } 2293 } 2294 } else { 2295 if (ReturnStmts.empty()) { 2296 // C++1y doesn't require constexpr functions to contain a 'return' 2297 // statement. We still do, unless the return type might be void, because 2298 // otherwise if there's no return statement, the function cannot 2299 // be used in a core constant expression. 2300 bool OK = SemaRef.getLangOpts().CPlusPlus14 && 2301 (Dcl->getReturnType()->isVoidType() || 2302 Dcl->getReturnType()->isDependentType()); 2303 switch (Kind) { 2304 case Sema::CheckConstexprKind::Diagnose: 2305 SemaRef.Diag(Dcl->getLocation(), 2306 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 2307 : diag::err_constexpr_body_no_return) 2308 << Dcl->isConsteval(); 2309 if (!OK) 2310 return false; 2311 break; 2312 2313 case Sema::CheckConstexprKind::CheckValid: 2314 // The formal requirements don't include this rule in C++14, even 2315 // though the "must be able to produce a constant expression" rules 2316 // still imply it in some cases. 2317 if (!SemaRef.getLangOpts().CPlusPlus14) 2318 return false; 2319 break; 2320 } 2321 } else if (ReturnStmts.size() > 1) { 2322 switch (Kind) { 2323 case Sema::CheckConstexprKind::Diagnose: 2324 SemaRef.Diag( 2325 ReturnStmts.back(), 2326 SemaRef.getLangOpts().CPlusPlus14 2327 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 2328 : diag::ext_constexpr_body_multiple_return); 2329 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 2330 SemaRef.Diag(ReturnStmts[I], 2331 diag::note_constexpr_body_previous_return); 2332 break; 2333 2334 case Sema::CheckConstexprKind::CheckValid: 2335 if (!SemaRef.getLangOpts().CPlusPlus14) 2336 return false; 2337 break; 2338 } 2339 } 2340 } 2341 2342 // C++11 [dcl.constexpr]p5: 2343 // if no function argument values exist such that the function invocation 2344 // substitution would produce a constant expression, the program is 2345 // ill-formed; no diagnostic required. 2346 // C++11 [dcl.constexpr]p3: 2347 // - every constructor call and implicit conversion used in initializing the 2348 // return value shall be one of those allowed in a constant expression. 2349 // C++11 [dcl.constexpr]p4: 2350 // - every constructor involved in initializing non-static data members and 2351 // base class sub-objects shall be a constexpr constructor. 2352 // 2353 // Note that this rule is distinct from the "requirements for a constexpr 2354 // function", so is not checked in CheckValid mode. 2355 SmallVector<PartialDiagnosticAt, 8> Diags; 2356 if (Kind == Sema::CheckConstexprKind::Diagnose && 2357 !Expr::isPotentialConstantExpr(Dcl, Diags)) { 2358 SemaRef.Diag(Dcl->getLocation(), 2359 diag::ext_constexpr_function_never_constant_expr) 2360 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 2361 for (size_t I = 0, N = Diags.size(); I != N; ++I) 2362 SemaRef.Diag(Diags[I].first, Diags[I].second); 2363 // Don't return false here: we allow this for compatibility in 2364 // system headers. 2365 } 2366 2367 return true; 2368 } 2369 2370 /// Get the class that is directly named by the current context. This is the 2371 /// class for which an unqualified-id in this scope could name a constructor 2372 /// or destructor. 2373 /// 2374 /// If the scope specifier denotes a class, this will be that class. 2375 /// If the scope specifier is empty, this will be the class whose 2376 /// member-specification we are currently within. Otherwise, there 2377 /// is no such class. 2378 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) { 2379 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2380 2381 if (SS && SS->isInvalid()) 2382 return nullptr; 2383 2384 if (SS && SS->isNotEmpty()) { 2385 DeclContext *DC = computeDeclContext(*SS, true); 2386 return dyn_cast_or_null<CXXRecordDecl>(DC); 2387 } 2388 2389 return dyn_cast_or_null<CXXRecordDecl>(CurContext); 2390 } 2391 2392 /// isCurrentClassName - Determine whether the identifier II is the 2393 /// name of the class type currently being defined. In the case of 2394 /// nested classes, this will only return true if II is the name of 2395 /// the innermost class. 2396 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S, 2397 const CXXScopeSpec *SS) { 2398 CXXRecordDecl *CurDecl = getCurrentClass(S, SS); 2399 return CurDecl && &II == CurDecl->getIdentifier(); 2400 } 2401 2402 /// Determine whether the identifier II is a typo for the name of 2403 /// the class type currently being defined. If so, update it to the identifier 2404 /// that should have been used. 2405 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 2406 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2407 2408 if (!getLangOpts().SpellChecking) 2409 return false; 2410 2411 CXXRecordDecl *CurDecl; 2412 if (SS && SS->isSet() && !SS->isInvalid()) { 2413 DeclContext *DC = computeDeclContext(*SS, true); 2414 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 2415 } else 2416 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 2417 2418 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 2419 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 2420 < II->getLength()) { 2421 II = CurDecl->getIdentifier(); 2422 return true; 2423 } 2424 2425 return false; 2426 } 2427 2428 /// Determine whether the given class is a base class of the given 2429 /// class, including looking at dependent bases. 2430 static bool findCircularInheritance(const CXXRecordDecl *Class, 2431 const CXXRecordDecl *Current) { 2432 SmallVector<const CXXRecordDecl*, 8> Queue; 2433 2434 Class = Class->getCanonicalDecl(); 2435 while (true) { 2436 for (const auto &I : Current->bases()) { 2437 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 2438 if (!Base) 2439 continue; 2440 2441 Base = Base->getDefinition(); 2442 if (!Base) 2443 continue; 2444 2445 if (Base->getCanonicalDecl() == Class) 2446 return true; 2447 2448 Queue.push_back(Base); 2449 } 2450 2451 if (Queue.empty()) 2452 return false; 2453 2454 Current = Queue.pop_back_val(); 2455 } 2456 2457 return false; 2458 } 2459 2460 /// Check the validity of a C++ base class specifier. 2461 /// 2462 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 2463 /// and returns NULL otherwise. 2464 CXXBaseSpecifier * 2465 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 2466 SourceRange SpecifierRange, 2467 bool Virtual, AccessSpecifier Access, 2468 TypeSourceInfo *TInfo, 2469 SourceLocation EllipsisLoc) { 2470 QualType BaseType = TInfo->getType(); 2471 if (BaseType->containsErrors()) { 2472 // Already emitted a diagnostic when parsing the error type. 2473 return nullptr; 2474 } 2475 // C++ [class.union]p1: 2476 // A union shall not have base classes. 2477 if (Class->isUnion()) { 2478 Diag(Class->getLocation(), diag::err_base_clause_on_union) 2479 << SpecifierRange; 2480 return nullptr; 2481 } 2482 2483 if (EllipsisLoc.isValid() && 2484 !TInfo->getType()->containsUnexpandedParameterPack()) { 2485 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2486 << TInfo->getTypeLoc().getSourceRange(); 2487 EllipsisLoc = SourceLocation(); 2488 } 2489 2490 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 2491 2492 if (BaseType->isDependentType()) { 2493 // Make sure that we don't have circular inheritance among our dependent 2494 // bases. For non-dependent bases, the check for completeness below handles 2495 // this. 2496 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 2497 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 2498 ((BaseDecl = BaseDecl->getDefinition()) && 2499 findCircularInheritance(Class, BaseDecl))) { 2500 Diag(BaseLoc, diag::err_circular_inheritance) 2501 << BaseType << Context.getTypeDeclType(Class); 2502 2503 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 2504 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 2505 << BaseType; 2506 2507 return nullptr; 2508 } 2509 } 2510 2511 // Make sure that we don't make an ill-formed AST where the type of the 2512 // Class is non-dependent and its attached base class specifier is an 2513 // dependent type, which violates invariants in many clang code paths (e.g. 2514 // constexpr evaluator). If this case happens (in errory-recovery mode), we 2515 // explicitly mark the Class decl invalid. The diagnostic was already 2516 // emitted. 2517 if (!Class->getTypeForDecl()->isDependentType()) 2518 Class->setInvalidDecl(); 2519 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2520 Class->getTagKind() == TTK_Class, 2521 Access, TInfo, EllipsisLoc); 2522 } 2523 2524 // Base specifiers must be record types. 2525 if (!BaseType->isRecordType()) { 2526 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 2527 return nullptr; 2528 } 2529 2530 // C++ [class.union]p1: 2531 // A union shall not be used as a base class. 2532 if (BaseType->isUnionType()) { 2533 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 2534 return nullptr; 2535 } 2536 2537 // For the MS ABI, propagate DLL attributes to base class templates. 2538 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 2539 if (Attr *ClassAttr = getDLLAttr(Class)) { 2540 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 2541 BaseType->getAsCXXRecordDecl())) { 2542 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate, 2543 BaseLoc); 2544 } 2545 } 2546 } 2547 2548 // C++ [class.derived]p2: 2549 // The class-name in a base-specifier shall not be an incompletely 2550 // defined class. 2551 if (RequireCompleteType(BaseLoc, BaseType, 2552 diag::err_incomplete_base_class, SpecifierRange)) { 2553 Class->setInvalidDecl(); 2554 return nullptr; 2555 } 2556 2557 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 2558 RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl(); 2559 assert(BaseDecl && "Record type has no declaration"); 2560 BaseDecl = BaseDecl->getDefinition(); 2561 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 2562 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 2563 assert(CXXBaseDecl && "Base type is not a C++ type"); 2564 2565 // Microsoft docs say: 2566 // "If a base-class has a code_seg attribute, derived classes must have the 2567 // same attribute." 2568 const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>(); 2569 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>(); 2570 if ((DerivedCSA || BaseCSA) && 2571 (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) { 2572 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base); 2573 Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here) 2574 << CXXBaseDecl; 2575 return nullptr; 2576 } 2577 2578 // A class which contains a flexible array member is not suitable for use as a 2579 // base class: 2580 // - If the layout determines that a base comes before another base, 2581 // the flexible array member would index into the subsequent base. 2582 // - If the layout determines that base comes before the derived class, 2583 // the flexible array member would index into the derived class. 2584 if (CXXBaseDecl->hasFlexibleArrayMember()) { 2585 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 2586 << CXXBaseDecl->getDeclName(); 2587 return nullptr; 2588 } 2589 2590 // C++ [class]p3: 2591 // If a class is marked final and it appears as a base-type-specifier in 2592 // base-clause, the program is ill-formed. 2593 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 2594 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 2595 << CXXBaseDecl->getDeclName() 2596 << FA->isSpelledAsSealed(); 2597 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 2598 << CXXBaseDecl->getDeclName() << FA->getRange(); 2599 return nullptr; 2600 } 2601 2602 if (BaseDecl->isInvalidDecl()) 2603 Class->setInvalidDecl(); 2604 2605 // Create the base specifier. 2606 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2607 Class->getTagKind() == TTK_Class, 2608 Access, TInfo, EllipsisLoc); 2609 } 2610 2611 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 2612 /// one entry in the base class list of a class specifier, for 2613 /// example: 2614 /// class foo : public bar, virtual private baz { 2615 /// 'public bar' and 'virtual private baz' are each base-specifiers. 2616 BaseResult 2617 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 2618 ParsedAttributes &Attributes, 2619 bool Virtual, AccessSpecifier Access, 2620 ParsedType basetype, SourceLocation BaseLoc, 2621 SourceLocation EllipsisLoc) { 2622 if (!classdecl) 2623 return true; 2624 2625 AdjustDeclIfTemplate(classdecl); 2626 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 2627 if (!Class) 2628 return true; 2629 2630 // We haven't yet attached the base specifiers. 2631 Class->setIsParsingBaseSpecifiers(); 2632 2633 // We do not support any C++11 attributes on base-specifiers yet. 2634 // Diagnose any attributes we see. 2635 for (const ParsedAttr &AL : Attributes) { 2636 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute) 2637 continue; 2638 Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute 2639 ? (unsigned)diag::warn_unknown_attribute_ignored 2640 : (unsigned)diag::err_base_specifier_attribute) 2641 << AL << AL.getRange(); 2642 } 2643 2644 TypeSourceInfo *TInfo = nullptr; 2645 GetTypeFromParser(basetype, &TInfo); 2646 2647 if (EllipsisLoc.isInvalid() && 2648 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 2649 UPPC_BaseType)) 2650 return true; 2651 2652 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 2653 Virtual, Access, TInfo, 2654 EllipsisLoc)) 2655 return BaseSpec; 2656 else 2657 Class->setInvalidDecl(); 2658 2659 return true; 2660 } 2661 2662 /// Use small set to collect indirect bases. As this is only used 2663 /// locally, there's no need to abstract the small size parameter. 2664 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet; 2665 2666 /// Recursively add the bases of Type. Don't add Type itself. 2667 static void 2668 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, 2669 const QualType &Type) 2670 { 2671 // Even though the incoming type is a base, it might not be 2672 // a class -- it could be a template parm, for instance. 2673 if (auto Rec = Type->getAs<RecordType>()) { 2674 auto Decl = Rec->getAsCXXRecordDecl(); 2675 2676 // Iterate over its bases. 2677 for (const auto &BaseSpec : Decl->bases()) { 2678 QualType Base = Context.getCanonicalType(BaseSpec.getType()) 2679 .getUnqualifiedType(); 2680 if (Set.insert(Base).second) 2681 // If we've not already seen it, recurse. 2682 NoteIndirectBases(Context, Set, Base); 2683 } 2684 } 2685 } 2686 2687 /// Performs the actual work of attaching the given base class 2688 /// specifiers to a C++ class. 2689 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, 2690 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2691 if (Bases.empty()) 2692 return false; 2693 2694 // Used to keep track of which base types we have already seen, so 2695 // that we can properly diagnose redundant direct base types. Note 2696 // that the key is always the unqualified canonical type of the base 2697 // class. 2698 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 2699 2700 // Used to track indirect bases so we can see if a direct base is 2701 // ambiguous. 2702 IndirectBaseSet IndirectBaseTypes; 2703 2704 // Copy non-redundant base specifiers into permanent storage. 2705 unsigned NumGoodBases = 0; 2706 bool Invalid = false; 2707 for (unsigned idx = 0; idx < Bases.size(); ++idx) { 2708 QualType NewBaseType 2709 = Context.getCanonicalType(Bases[idx]->getType()); 2710 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 2711 2712 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 2713 if (KnownBase) { 2714 // C++ [class.mi]p3: 2715 // A class shall not be specified as a direct base class of a 2716 // derived class more than once. 2717 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class) 2718 << KnownBase->getType() << Bases[idx]->getSourceRange(); 2719 2720 // Delete the duplicate base class specifier; we're going to 2721 // overwrite its pointer later. 2722 Context.Deallocate(Bases[idx]); 2723 2724 Invalid = true; 2725 } else { 2726 // Okay, add this new base class. 2727 KnownBase = Bases[idx]; 2728 Bases[NumGoodBases++] = Bases[idx]; 2729 2730 // Note this base's direct & indirect bases, if there could be ambiguity. 2731 if (Bases.size() > 1) 2732 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType); 2733 2734 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 2735 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 2736 if (Class->isInterface() && 2737 (!RD->isInterfaceLike() || 2738 KnownBase->getAccessSpecifier() != AS_public)) { 2739 // The Microsoft extension __interface does not permit bases that 2740 // are not themselves public interfaces. 2741 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface) 2742 << getRecordDiagFromTagKind(RD->getTagKind()) << RD 2743 << RD->getSourceRange(); 2744 Invalid = true; 2745 } 2746 if (RD->hasAttr<WeakAttr>()) 2747 Class->addAttr(WeakAttr::CreateImplicit(Context)); 2748 } 2749 } 2750 } 2751 2752 // Attach the remaining base class specifiers to the derived class. 2753 Class->setBases(Bases.data(), NumGoodBases); 2754 2755 // Check that the only base classes that are duplicate are virtual. 2756 for (unsigned idx = 0; idx < NumGoodBases; ++idx) { 2757 // Check whether this direct base is inaccessible due to ambiguity. 2758 QualType BaseType = Bases[idx]->getType(); 2759 2760 // Skip all dependent types in templates being used as base specifiers. 2761 // Checks below assume that the base specifier is a CXXRecord. 2762 if (BaseType->isDependentType()) 2763 continue; 2764 2765 CanQualType CanonicalBase = Context.getCanonicalType(BaseType) 2766 .getUnqualifiedType(); 2767 2768 if (IndirectBaseTypes.count(CanonicalBase)) { 2769 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2770 /*DetectVirtual=*/true); 2771 bool found 2772 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); 2773 assert(found); 2774 (void)found; 2775 2776 if (Paths.isAmbiguous(CanonicalBase)) 2777 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class) 2778 << BaseType << getAmbiguousPathsDisplayString(Paths) 2779 << Bases[idx]->getSourceRange(); 2780 else 2781 assert(Bases[idx]->isVirtual()); 2782 } 2783 2784 // Delete the base class specifier, since its data has been copied 2785 // into the CXXRecordDecl. 2786 Context.Deallocate(Bases[idx]); 2787 } 2788 2789 return Invalid; 2790 } 2791 2792 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 2793 /// class, after checking whether there are any duplicate base 2794 /// classes. 2795 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, 2796 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2797 if (!ClassDecl || Bases.empty()) 2798 return; 2799 2800 AdjustDeclIfTemplate(ClassDecl); 2801 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases); 2802 } 2803 2804 /// Determine whether the type \p Derived is a C++ class that is 2805 /// derived from the type \p Base. 2806 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) { 2807 if (!getLangOpts().CPlusPlus) 2808 return false; 2809 2810 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2811 if (!DerivedRD) 2812 return false; 2813 2814 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2815 if (!BaseRD) 2816 return false; 2817 2818 // If either the base or the derived type is invalid, don't try to 2819 // check whether one is derived from the other. 2820 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 2821 return false; 2822 2823 // FIXME: In a modules build, do we need the entire path to be visible for us 2824 // to be able to use the inheritance relationship? 2825 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2826 return false; 2827 2828 return DerivedRD->isDerivedFrom(BaseRD); 2829 } 2830 2831 /// Determine whether the type \p Derived is a C++ class that is 2832 /// derived from the type \p Base. 2833 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, 2834 CXXBasePaths &Paths) { 2835 if (!getLangOpts().CPlusPlus) 2836 return false; 2837 2838 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2839 if (!DerivedRD) 2840 return false; 2841 2842 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2843 if (!BaseRD) 2844 return false; 2845 2846 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2847 return false; 2848 2849 return DerivedRD->isDerivedFrom(BaseRD, Paths); 2850 } 2851 2852 static void BuildBasePathArray(const CXXBasePath &Path, 2853 CXXCastPath &BasePathArray) { 2854 // We first go backward and check if we have a virtual base. 2855 // FIXME: It would be better if CXXBasePath had the base specifier for 2856 // the nearest virtual base. 2857 unsigned Start = 0; 2858 for (unsigned I = Path.size(); I != 0; --I) { 2859 if (Path[I - 1].Base->isVirtual()) { 2860 Start = I - 1; 2861 break; 2862 } 2863 } 2864 2865 // Now add all bases. 2866 for (unsigned I = Start, E = Path.size(); I != E; ++I) 2867 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 2868 } 2869 2870 2871 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 2872 CXXCastPath &BasePathArray) { 2873 assert(BasePathArray.empty() && "Base path array must be empty!"); 2874 assert(Paths.isRecordingPaths() && "Must record paths!"); 2875 return ::BuildBasePathArray(Paths.front(), BasePathArray); 2876 } 2877 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 2878 /// conversion (where Derived and Base are class types) is 2879 /// well-formed, meaning that the conversion is unambiguous (and 2880 /// that all of the base classes are accessible). Returns true 2881 /// and emits a diagnostic if the code is ill-formed, returns false 2882 /// otherwise. Loc is the location where this routine should point to 2883 /// if there is an error, and Range is the source range to highlight 2884 /// if there is an error. 2885 /// 2886 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the 2887 /// diagnostic for the respective type of error will be suppressed, but the 2888 /// check for ill-formed code will still be performed. 2889 bool 2890 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2891 unsigned InaccessibleBaseID, 2892 unsigned AmbiguousBaseConvID, 2893 SourceLocation Loc, SourceRange Range, 2894 DeclarationName Name, 2895 CXXCastPath *BasePath, 2896 bool IgnoreAccess) { 2897 // First, determine whether the path from Derived to Base is 2898 // ambiguous. This is slightly more expensive than checking whether 2899 // the Derived to Base conversion exists, because here we need to 2900 // explore multiple paths to determine if there is an ambiguity. 2901 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2902 /*DetectVirtual=*/false); 2903 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2904 if (!DerivationOkay) 2905 return true; 2906 2907 const CXXBasePath *Path = nullptr; 2908 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) 2909 Path = &Paths.front(); 2910 2911 // For MSVC compatibility, check if Derived directly inherits from Base. Clang 2912 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the 2913 // user to access such bases. 2914 if (!Path && getLangOpts().MSVCCompat) { 2915 for (const CXXBasePath &PossiblePath : Paths) { 2916 if (PossiblePath.size() == 1) { 2917 Path = &PossiblePath; 2918 if (AmbiguousBaseConvID) 2919 Diag(Loc, diag::ext_ms_ambiguous_direct_base) 2920 << Base << Derived << Range; 2921 break; 2922 } 2923 } 2924 } 2925 2926 if (Path) { 2927 if (!IgnoreAccess) { 2928 // Check that the base class can be accessed. 2929 switch ( 2930 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) { 2931 case AR_inaccessible: 2932 return true; 2933 case AR_accessible: 2934 case AR_dependent: 2935 case AR_delayed: 2936 break; 2937 } 2938 } 2939 2940 // Build a base path if necessary. 2941 if (BasePath) 2942 ::BuildBasePathArray(*Path, *BasePath); 2943 return false; 2944 } 2945 2946 if (AmbiguousBaseConvID) { 2947 // We know that the derived-to-base conversion is ambiguous, and 2948 // we're going to produce a diagnostic. Perform the derived-to-base 2949 // search just one more time to compute all of the possible paths so 2950 // that we can print them out. This is more expensive than any of 2951 // the previous derived-to-base checks we've done, but at this point 2952 // performance isn't as much of an issue. 2953 Paths.clear(); 2954 Paths.setRecordingPaths(true); 2955 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2956 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 2957 (void)StillOkay; 2958 2959 // Build up a textual representation of the ambiguous paths, e.g., 2960 // D -> B -> A, that will be used to illustrate the ambiguous 2961 // conversions in the diagnostic. We only print one of the paths 2962 // to each base class subobject. 2963 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2964 2965 Diag(Loc, AmbiguousBaseConvID) 2966 << Derived << Base << PathDisplayStr << Range << Name; 2967 } 2968 return true; 2969 } 2970 2971 bool 2972 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2973 SourceLocation Loc, SourceRange Range, 2974 CXXCastPath *BasePath, 2975 bool IgnoreAccess) { 2976 return CheckDerivedToBaseConversion( 2977 Derived, Base, diag::err_upcast_to_inaccessible_base, 2978 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(), 2979 BasePath, IgnoreAccess); 2980 } 2981 2982 2983 /// Builds a string representing ambiguous paths from a 2984 /// specific derived class to different subobjects of the same base 2985 /// class. 2986 /// 2987 /// This function builds a string that can be used in error messages 2988 /// to show the different paths that one can take through the 2989 /// inheritance hierarchy to go from the derived class to different 2990 /// subobjects of a base class. The result looks something like this: 2991 /// @code 2992 /// struct D -> struct B -> struct A 2993 /// struct D -> struct C -> struct A 2994 /// @endcode 2995 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 2996 std::string PathDisplayStr; 2997 std::set<unsigned> DisplayedPaths; 2998 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2999 Path != Paths.end(); ++Path) { 3000 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 3001 // We haven't displayed a path to this particular base 3002 // class subobject yet. 3003 PathDisplayStr += "\n "; 3004 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 3005 for (CXXBasePath::const_iterator Element = Path->begin(); 3006 Element != Path->end(); ++Element) 3007 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 3008 } 3009 } 3010 3011 return PathDisplayStr; 3012 } 3013 3014 //===----------------------------------------------------------------------===// 3015 // C++ class member Handling 3016 //===----------------------------------------------------------------------===// 3017 3018 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 3019 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, 3020 SourceLocation ColonLoc, 3021 const ParsedAttributesView &Attrs) { 3022 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 3023 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 3024 ASLoc, ColonLoc); 3025 CurContext->addHiddenDecl(ASDecl); 3026 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 3027 } 3028 3029 /// CheckOverrideControl - Check C++11 override control semantics. 3030 void Sema::CheckOverrideControl(NamedDecl *D) { 3031 if (D->isInvalidDecl()) 3032 return; 3033 3034 // We only care about "override" and "final" declarations. 3035 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 3036 return; 3037 3038 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 3039 3040 // We can't check dependent instance methods. 3041 if (MD && MD->isInstance() && 3042 (MD->getParent()->hasAnyDependentBases() || 3043 MD->getType()->isDependentType())) 3044 return; 3045 3046 if (MD && !MD->isVirtual()) { 3047 // If we have a non-virtual method, check if if hides a virtual method. 3048 // (In that case, it's most likely the method has the wrong type.) 3049 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 3050 FindHiddenVirtualMethods(MD, OverloadedMethods); 3051 3052 if (!OverloadedMethods.empty()) { 3053 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 3054 Diag(OA->getLocation(), 3055 diag::override_keyword_hides_virtual_member_function) 3056 << "override" << (OverloadedMethods.size() > 1); 3057 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 3058 Diag(FA->getLocation(), 3059 diag::override_keyword_hides_virtual_member_function) 3060 << (FA->isSpelledAsSealed() ? "sealed" : "final") 3061 << (OverloadedMethods.size() > 1); 3062 } 3063 NoteHiddenVirtualMethods(MD, OverloadedMethods); 3064 MD->setInvalidDecl(); 3065 return; 3066 } 3067 // Fall through into the general case diagnostic. 3068 // FIXME: We might want to attempt typo correction here. 3069 } 3070 3071 if (!MD || !MD->isVirtual()) { 3072 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 3073 Diag(OA->getLocation(), 3074 diag::override_keyword_only_allowed_on_virtual_member_functions) 3075 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 3076 D->dropAttr<OverrideAttr>(); 3077 } 3078 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 3079 Diag(FA->getLocation(), 3080 diag::override_keyword_only_allowed_on_virtual_member_functions) 3081 << (FA->isSpelledAsSealed() ? "sealed" : "final") 3082 << FixItHint::CreateRemoval(FA->getLocation()); 3083 D->dropAttr<FinalAttr>(); 3084 } 3085 return; 3086 } 3087 3088 // C++11 [class.virtual]p5: 3089 // If a function is marked with the virt-specifier override and 3090 // does not override a member function of a base class, the program is 3091 // ill-formed. 3092 bool HasOverriddenMethods = MD->size_overridden_methods() != 0; 3093 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 3094 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 3095 << MD->getDeclName(); 3096 } 3097 3098 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) { 3099 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) 3100 return; 3101 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 3102 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>()) 3103 return; 3104 3105 SourceLocation Loc = MD->getLocation(); 3106 SourceLocation SpellingLoc = Loc; 3107 if (getSourceManager().isMacroArgExpansion(Loc)) 3108 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin(); 3109 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); 3110 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) 3111 return; 3112 3113 if (MD->size_overridden_methods() > 0) { 3114 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) { 3115 unsigned DiagID = 3116 Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation()) 3117 ? DiagInconsistent 3118 : DiagSuggest; 3119 Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 3120 const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); 3121 Diag(OMD->getLocation(), diag::note_overridden_virtual_function); 3122 }; 3123 if (isa<CXXDestructorDecl>(MD)) 3124 EmitDiag( 3125 diag::warn_inconsistent_destructor_marked_not_override_overriding, 3126 diag::warn_suggest_destructor_marked_not_override_overriding); 3127 else 3128 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding, 3129 diag::warn_suggest_function_marked_not_override_overriding); 3130 } 3131 } 3132 3133 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 3134 /// function overrides a virtual member function marked 'final', according to 3135 /// C++11 [class.virtual]p4. 3136 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 3137 const CXXMethodDecl *Old) { 3138 FinalAttr *FA = Old->getAttr<FinalAttr>(); 3139 if (!FA) 3140 return false; 3141 3142 Diag(New->getLocation(), diag::err_final_function_overridden) 3143 << New->getDeclName() 3144 << FA->isSpelledAsSealed(); 3145 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 3146 return true; 3147 } 3148 3149 static bool InitializationHasSideEffects(const FieldDecl &FD) { 3150 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 3151 // FIXME: Destruction of ObjC lifetime types has side-effects. 3152 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 3153 return !RD->isCompleteDefinition() || 3154 !RD->hasTrivialDefaultConstructor() || 3155 !RD->hasTrivialDestructor(); 3156 return false; 3157 } 3158 3159 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) { 3160 ParsedAttributesView::const_iterator Itr = 3161 llvm::find_if(list, [](const ParsedAttr &AL) { 3162 return AL.isDeclspecPropertyAttribute(); 3163 }); 3164 if (Itr != list.end()) 3165 return &*Itr; 3166 return nullptr; 3167 } 3168 3169 // Check if there is a field shadowing. 3170 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc, 3171 DeclarationName FieldName, 3172 const CXXRecordDecl *RD, 3173 bool DeclIsField) { 3174 if (Diags.isIgnored(diag::warn_shadow_field, Loc)) 3175 return; 3176 3177 // To record a shadowed field in a base 3178 std::map<CXXRecordDecl*, NamedDecl*> Bases; 3179 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier, 3180 CXXBasePath &Path) { 3181 const auto Base = Specifier->getType()->getAsCXXRecordDecl(); 3182 // Record an ambiguous path directly 3183 if (Bases.find(Base) != Bases.end()) 3184 return true; 3185 for (const auto Field : Base->lookup(FieldName)) { 3186 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) && 3187 Field->getAccess() != AS_private) { 3188 assert(Field->getAccess() != AS_none); 3189 assert(Bases.find(Base) == Bases.end()); 3190 Bases[Base] = Field; 3191 return true; 3192 } 3193 } 3194 return false; 3195 }; 3196 3197 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3198 /*DetectVirtual=*/true); 3199 if (!RD->lookupInBases(FieldShadowed, Paths)) 3200 return; 3201 3202 for (const auto &P : Paths) { 3203 auto Base = P.back().Base->getType()->getAsCXXRecordDecl(); 3204 auto It = Bases.find(Base); 3205 // Skip duplicated bases 3206 if (It == Bases.end()) 3207 continue; 3208 auto BaseField = It->second; 3209 assert(BaseField->getAccess() != AS_private); 3210 if (AS_none != 3211 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) { 3212 Diag(Loc, diag::warn_shadow_field) 3213 << FieldName << RD << Base << DeclIsField; 3214 Diag(BaseField->getLocation(), diag::note_shadow_field); 3215 Bases.erase(It); 3216 } 3217 } 3218 } 3219 3220 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 3221 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 3222 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 3223 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 3224 /// present (but parsing it has been deferred). 3225 NamedDecl * 3226 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 3227 MultiTemplateParamsArg TemplateParameterLists, 3228 Expr *BW, const VirtSpecifiers &VS, 3229 InClassInitStyle InitStyle) { 3230 const DeclSpec &DS = D.getDeclSpec(); 3231 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 3232 DeclarationName Name = NameInfo.getName(); 3233 SourceLocation Loc = NameInfo.getLoc(); 3234 3235 // For anonymous bitfields, the location should point to the type. 3236 if (Loc.isInvalid()) 3237 Loc = D.getBeginLoc(); 3238 3239 Expr *BitWidth = static_cast<Expr*>(BW); 3240 3241 assert(isa<CXXRecordDecl>(CurContext)); 3242 assert(!DS.isFriendSpecified()); 3243 3244 bool isFunc = D.isDeclarationOfFunction(); 3245 const ParsedAttr *MSPropertyAttr = 3246 getMSPropertyAttr(D.getDeclSpec().getAttributes()); 3247 3248 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 3249 // The Microsoft extension __interface only permits public member functions 3250 // and prohibits constructors, destructors, operators, non-public member 3251 // functions, static methods and data members. 3252 unsigned InvalidDecl; 3253 bool ShowDeclName = true; 3254 if (!isFunc && 3255 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr)) 3256 InvalidDecl = 0; 3257 else if (!isFunc) 3258 InvalidDecl = 1; 3259 else if (AS != AS_public) 3260 InvalidDecl = 2; 3261 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 3262 InvalidDecl = 3; 3263 else switch (Name.getNameKind()) { 3264 case DeclarationName::CXXConstructorName: 3265 InvalidDecl = 4; 3266 ShowDeclName = false; 3267 break; 3268 3269 case DeclarationName::CXXDestructorName: 3270 InvalidDecl = 5; 3271 ShowDeclName = false; 3272 break; 3273 3274 case DeclarationName::CXXOperatorName: 3275 case DeclarationName::CXXConversionFunctionName: 3276 InvalidDecl = 6; 3277 break; 3278 3279 default: 3280 InvalidDecl = 0; 3281 break; 3282 } 3283 3284 if (InvalidDecl) { 3285 if (ShowDeclName) 3286 Diag(Loc, diag::err_invalid_member_in_interface) 3287 << (InvalidDecl-1) << Name; 3288 else 3289 Diag(Loc, diag::err_invalid_member_in_interface) 3290 << (InvalidDecl-1) << ""; 3291 return nullptr; 3292 } 3293 } 3294 3295 // C++ 9.2p6: A member shall not be declared to have automatic storage 3296 // duration (auto, register) or with the extern storage-class-specifier. 3297 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 3298 // data members and cannot be applied to names declared const or static, 3299 // and cannot be applied to reference members. 3300 switch (DS.getStorageClassSpec()) { 3301 case DeclSpec::SCS_unspecified: 3302 case DeclSpec::SCS_typedef: 3303 case DeclSpec::SCS_static: 3304 break; 3305 case DeclSpec::SCS_mutable: 3306 if (isFunc) { 3307 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 3308 3309 // FIXME: It would be nicer if the keyword was ignored only for this 3310 // declarator. Otherwise we could get follow-up errors. 3311 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3312 } 3313 break; 3314 default: 3315 Diag(DS.getStorageClassSpecLoc(), 3316 diag::err_storageclass_invalid_for_member); 3317 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3318 break; 3319 } 3320 3321 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 3322 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 3323 !isFunc); 3324 3325 if (DS.hasConstexprSpecifier() && isInstField) { 3326 SemaDiagnosticBuilder B = 3327 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 3328 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 3329 if (InitStyle == ICIS_NoInit) { 3330 B << 0 << 0; 3331 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 3332 B << FixItHint::CreateRemoval(ConstexprLoc); 3333 else { 3334 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 3335 D.getMutableDeclSpec().ClearConstexprSpec(); 3336 const char *PrevSpec; 3337 unsigned DiagID; 3338 bool Failed = D.getMutableDeclSpec().SetTypeQual( 3339 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 3340 (void)Failed; 3341 assert(!Failed && "Making a constexpr member const shouldn't fail"); 3342 } 3343 } else { 3344 B << 1; 3345 const char *PrevSpec; 3346 unsigned DiagID; 3347 if (D.getMutableDeclSpec().SetStorageClassSpec( 3348 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 3349 Context.getPrintingPolicy())) { 3350 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 3351 "This is the only DeclSpec that should fail to be applied"); 3352 B << 1; 3353 } else { 3354 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 3355 isInstField = false; 3356 } 3357 } 3358 } 3359 3360 NamedDecl *Member; 3361 if (isInstField) { 3362 CXXScopeSpec &SS = D.getCXXScopeSpec(); 3363 3364 // Data members must have identifiers for names. 3365 if (!Name.isIdentifier()) { 3366 Diag(Loc, diag::err_bad_variable_name) 3367 << Name; 3368 return nullptr; 3369 } 3370 3371 IdentifierInfo *II = Name.getAsIdentifierInfo(); 3372 3373 // Member field could not be with "template" keyword. 3374 // So TemplateParameterLists should be empty in this case. 3375 if (TemplateParameterLists.size()) { 3376 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 3377 if (TemplateParams->size()) { 3378 // There is no such thing as a member field template. 3379 Diag(D.getIdentifierLoc(), diag::err_template_member) 3380 << II 3381 << SourceRange(TemplateParams->getTemplateLoc(), 3382 TemplateParams->getRAngleLoc()); 3383 } else { 3384 // There is an extraneous 'template<>' for this member. 3385 Diag(TemplateParams->getTemplateLoc(), 3386 diag::err_template_member_noparams) 3387 << II 3388 << SourceRange(TemplateParams->getTemplateLoc(), 3389 TemplateParams->getRAngleLoc()); 3390 } 3391 return nullptr; 3392 } 3393 3394 if (SS.isSet() && !SS.isInvalid()) { 3395 // The user provided a superfluous scope specifier inside a class 3396 // definition: 3397 // 3398 // class X { 3399 // int X::member; 3400 // }; 3401 if (DeclContext *DC = computeDeclContext(SS, false)) 3402 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(), 3403 D.getName().getKind() == 3404 UnqualifiedIdKind::IK_TemplateId); 3405 else 3406 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 3407 << Name << SS.getRange(); 3408 3409 SS.clear(); 3410 } 3411 3412 if (MSPropertyAttr) { 3413 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3414 BitWidth, InitStyle, AS, *MSPropertyAttr); 3415 if (!Member) 3416 return nullptr; 3417 isInstField = false; 3418 } else { 3419 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3420 BitWidth, InitStyle, AS); 3421 if (!Member) 3422 return nullptr; 3423 } 3424 3425 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext)); 3426 } else { 3427 Member = HandleDeclarator(S, D, TemplateParameterLists); 3428 if (!Member) 3429 return nullptr; 3430 3431 // Non-instance-fields can't have a bitfield. 3432 if (BitWidth) { 3433 if (Member->isInvalidDecl()) { 3434 // don't emit another diagnostic. 3435 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) { 3436 // C++ 9.6p3: A bit-field shall not be a static member. 3437 // "static member 'A' cannot be a bit-field" 3438 Diag(Loc, diag::err_static_not_bitfield) 3439 << Name << BitWidth->getSourceRange(); 3440 } else if (isa<TypedefDecl>(Member)) { 3441 // "typedef member 'x' cannot be a bit-field" 3442 Diag(Loc, diag::err_typedef_not_bitfield) 3443 << Name << BitWidth->getSourceRange(); 3444 } else { 3445 // A function typedef ("typedef int f(); f a;"). 3446 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 3447 Diag(Loc, diag::err_not_integral_type_bitfield) 3448 << Name << cast<ValueDecl>(Member)->getType() 3449 << BitWidth->getSourceRange(); 3450 } 3451 3452 BitWidth = nullptr; 3453 Member->setInvalidDecl(); 3454 } 3455 3456 NamedDecl *NonTemplateMember = Member; 3457 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 3458 NonTemplateMember = FunTmpl->getTemplatedDecl(); 3459 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 3460 NonTemplateMember = VarTmpl->getTemplatedDecl(); 3461 3462 Member->setAccess(AS); 3463 3464 // If we have declared a member function template or static data member 3465 // template, set the access of the templated declaration as well. 3466 if (NonTemplateMember != Member) 3467 NonTemplateMember->setAccess(AS); 3468 3469 // C++ [temp.deduct.guide]p3: 3470 // A deduction guide [...] for a member class template [shall be 3471 // declared] with the same access [as the template]. 3472 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) { 3473 auto *TD = DG->getDeducedTemplate(); 3474 // Access specifiers are only meaningful if both the template and the 3475 // deduction guide are from the same scope. 3476 if (AS != TD->getAccess() && 3477 TD->getDeclContext()->getRedeclContext()->Equals( 3478 DG->getDeclContext()->getRedeclContext())) { 3479 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access); 3480 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access) 3481 << TD->getAccess(); 3482 const AccessSpecDecl *LastAccessSpec = nullptr; 3483 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) { 3484 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D)) 3485 LastAccessSpec = AccessSpec; 3486 } 3487 assert(LastAccessSpec && "differing access with no access specifier"); 3488 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access) 3489 << AS; 3490 } 3491 } 3492 } 3493 3494 if (VS.isOverrideSpecified()) 3495 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(), 3496 AttributeCommonInfo::AS_Keyword)); 3497 if (VS.isFinalSpecified()) 3498 Member->addAttr(FinalAttr::Create( 3499 Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword, 3500 static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed()))); 3501 3502 if (VS.getLastLocation().isValid()) { 3503 // Update the end location of a method that has a virt-specifiers. 3504 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 3505 MD->setRangeEnd(VS.getLastLocation()); 3506 } 3507 3508 CheckOverrideControl(Member); 3509 3510 assert((Name || isInstField) && "No identifier for non-field ?"); 3511 3512 if (isInstField) { 3513 FieldDecl *FD = cast<FieldDecl>(Member); 3514 FieldCollector->Add(FD); 3515 3516 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 3517 // Remember all explicit private FieldDecls that have a name, no side 3518 // effects and are not part of a dependent type declaration. 3519 if (!FD->isImplicit() && FD->getDeclName() && 3520 FD->getAccess() == AS_private && 3521 !FD->hasAttr<UnusedAttr>() && 3522 !FD->getParent()->isDependentContext() && 3523 !InitializationHasSideEffects(*FD)) 3524 UnusedPrivateFields.insert(FD); 3525 } 3526 } 3527 3528 return Member; 3529 } 3530 3531 namespace { 3532 class UninitializedFieldVisitor 3533 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 3534 Sema &S; 3535 // List of Decls to generate a warning on. Also remove Decls that become 3536 // initialized. 3537 llvm::SmallPtrSetImpl<ValueDecl*> &Decls; 3538 // List of base classes of the record. Classes are removed after their 3539 // initializers. 3540 llvm::SmallPtrSetImpl<QualType> &BaseClasses; 3541 // Vector of decls to be removed from the Decl set prior to visiting the 3542 // nodes. These Decls may have been initialized in the prior initializer. 3543 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; 3544 // If non-null, add a note to the warning pointing back to the constructor. 3545 const CXXConstructorDecl *Constructor; 3546 // Variables to hold state when processing an initializer list. When 3547 // InitList is true, special case initialization of FieldDecls matching 3548 // InitListFieldDecl. 3549 bool InitList; 3550 FieldDecl *InitListFieldDecl; 3551 llvm::SmallVector<unsigned, 4> InitFieldIndex; 3552 3553 public: 3554 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 3555 UninitializedFieldVisitor(Sema &S, 3556 llvm::SmallPtrSetImpl<ValueDecl*> &Decls, 3557 llvm::SmallPtrSetImpl<QualType> &BaseClasses) 3558 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), 3559 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} 3560 3561 // Returns true if the use of ME is not an uninitialized use. 3562 bool IsInitListMemberExprInitialized(MemberExpr *ME, 3563 bool CheckReferenceOnly) { 3564 llvm::SmallVector<FieldDecl*, 4> Fields; 3565 bool ReferenceField = false; 3566 while (ME) { 3567 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 3568 if (!FD) 3569 return false; 3570 Fields.push_back(FD); 3571 if (FD->getType()->isReferenceType()) 3572 ReferenceField = true; 3573 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); 3574 } 3575 3576 // Binding a reference to an uninitialized field is not an 3577 // uninitialized use. 3578 if (CheckReferenceOnly && !ReferenceField) 3579 return true; 3580 3581 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 3582 // Discard the first field since it is the field decl that is being 3583 // initialized. 3584 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) { 3585 UsedFieldIndex.push_back((*I)->getFieldIndex()); 3586 } 3587 3588 for (auto UsedIter = UsedFieldIndex.begin(), 3589 UsedEnd = UsedFieldIndex.end(), 3590 OrigIter = InitFieldIndex.begin(), 3591 OrigEnd = InitFieldIndex.end(); 3592 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 3593 if (*UsedIter < *OrigIter) 3594 return true; 3595 if (*UsedIter > *OrigIter) 3596 break; 3597 } 3598 3599 return false; 3600 } 3601 3602 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, 3603 bool AddressOf) { 3604 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 3605 return; 3606 3607 // FieldME is the inner-most MemberExpr that is not an anonymous struct 3608 // or union. 3609 MemberExpr *FieldME = ME; 3610 3611 bool AllPODFields = FieldME->getType().isPODType(S.Context); 3612 3613 Expr *Base = ME; 3614 while (MemberExpr *SubME = 3615 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { 3616 3617 if (isa<VarDecl>(SubME->getMemberDecl())) 3618 return; 3619 3620 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) 3621 if (!FD->isAnonymousStructOrUnion()) 3622 FieldME = SubME; 3623 3624 if (!FieldME->getType().isPODType(S.Context)) 3625 AllPODFields = false; 3626 3627 Base = SubME->getBase(); 3628 } 3629 3630 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) { 3631 Visit(Base); 3632 return; 3633 } 3634 3635 if (AddressOf && AllPODFields) 3636 return; 3637 3638 ValueDecl* FoundVD = FieldME->getMemberDecl(); 3639 3640 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { 3641 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { 3642 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); 3643 } 3644 3645 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { 3646 QualType T = BaseCast->getType(); 3647 if (T->isPointerType() && 3648 BaseClasses.count(T->getPointeeType())) { 3649 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) 3650 << T->getPointeeType() << FoundVD; 3651 } 3652 } 3653 } 3654 3655 if (!Decls.count(FoundVD)) 3656 return; 3657 3658 const bool IsReference = FoundVD->getType()->isReferenceType(); 3659 3660 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { 3661 // Special checking for initializer lists. 3662 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { 3663 return; 3664 } 3665 } else { 3666 // Prevent double warnings on use of unbounded references. 3667 if (CheckReferenceOnly && !IsReference) 3668 return; 3669 } 3670 3671 unsigned diag = IsReference 3672 ? diag::warn_reference_field_is_uninit 3673 : diag::warn_field_is_uninit; 3674 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 3675 if (Constructor) 3676 S.Diag(Constructor->getLocation(), 3677 diag::note_uninit_in_this_constructor) 3678 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 3679 3680 } 3681 3682 void HandleValue(Expr *E, bool AddressOf) { 3683 E = E->IgnoreParens(); 3684 3685 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3686 HandleMemberExpr(ME, false /*CheckReferenceOnly*/, 3687 AddressOf /*AddressOf*/); 3688 return; 3689 } 3690 3691 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 3692 Visit(CO->getCond()); 3693 HandleValue(CO->getTrueExpr(), AddressOf); 3694 HandleValue(CO->getFalseExpr(), AddressOf); 3695 return; 3696 } 3697 3698 if (BinaryConditionalOperator *BCO = 3699 dyn_cast<BinaryConditionalOperator>(E)) { 3700 Visit(BCO->getCond()); 3701 HandleValue(BCO->getFalseExpr(), AddressOf); 3702 return; 3703 } 3704 3705 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 3706 HandleValue(OVE->getSourceExpr(), AddressOf); 3707 return; 3708 } 3709 3710 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 3711 switch (BO->getOpcode()) { 3712 default: 3713 break; 3714 case(BO_PtrMemD): 3715 case(BO_PtrMemI): 3716 HandleValue(BO->getLHS(), AddressOf); 3717 Visit(BO->getRHS()); 3718 return; 3719 case(BO_Comma): 3720 Visit(BO->getLHS()); 3721 HandleValue(BO->getRHS(), AddressOf); 3722 return; 3723 } 3724 } 3725 3726 Visit(E); 3727 } 3728 3729 void CheckInitListExpr(InitListExpr *ILE) { 3730 InitFieldIndex.push_back(0); 3731 for (auto Child : ILE->children()) { 3732 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { 3733 CheckInitListExpr(SubList); 3734 } else { 3735 Visit(Child); 3736 } 3737 ++InitFieldIndex.back(); 3738 } 3739 InitFieldIndex.pop_back(); 3740 } 3741 3742 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, 3743 FieldDecl *Field, const Type *BaseClass) { 3744 // Remove Decls that may have been initialized in the previous 3745 // initializer. 3746 for (ValueDecl* VD : DeclsToRemove) 3747 Decls.erase(VD); 3748 DeclsToRemove.clear(); 3749 3750 Constructor = FieldConstructor; 3751 InitListExpr *ILE = dyn_cast<InitListExpr>(E); 3752 3753 if (ILE && Field) { 3754 InitList = true; 3755 InitListFieldDecl = Field; 3756 InitFieldIndex.clear(); 3757 CheckInitListExpr(ILE); 3758 } else { 3759 InitList = false; 3760 Visit(E); 3761 } 3762 3763 if (Field) 3764 Decls.erase(Field); 3765 if (BaseClass) 3766 BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); 3767 } 3768 3769 void VisitMemberExpr(MemberExpr *ME) { 3770 // All uses of unbounded reference fields will warn. 3771 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); 3772 } 3773 3774 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 3775 if (E->getCastKind() == CK_LValueToRValue) { 3776 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3777 return; 3778 } 3779 3780 Inherited::VisitImplicitCastExpr(E); 3781 } 3782 3783 void VisitCXXConstructExpr(CXXConstructExpr *E) { 3784 if (E->getConstructor()->isCopyConstructor()) { 3785 Expr *ArgExpr = E->getArg(0); 3786 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 3787 if (ILE->getNumInits() == 1) 3788 ArgExpr = ILE->getInit(0); 3789 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 3790 if (ICE->getCastKind() == CK_NoOp) 3791 ArgExpr = ICE->getSubExpr(); 3792 HandleValue(ArgExpr, false /*AddressOf*/); 3793 return; 3794 } 3795 Inherited::VisitCXXConstructExpr(E); 3796 } 3797 3798 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 3799 Expr *Callee = E->getCallee(); 3800 if (isa<MemberExpr>(Callee)) { 3801 HandleValue(Callee, false /*AddressOf*/); 3802 for (auto Arg : E->arguments()) 3803 Visit(Arg); 3804 return; 3805 } 3806 3807 Inherited::VisitCXXMemberCallExpr(E); 3808 } 3809 3810 void VisitCallExpr(CallExpr *E) { 3811 // Treat std::move as a use. 3812 if (E->isCallToStdMove()) { 3813 HandleValue(E->getArg(0), /*AddressOf=*/false); 3814 return; 3815 } 3816 3817 Inherited::VisitCallExpr(E); 3818 } 3819 3820 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 3821 Expr *Callee = E->getCallee(); 3822 3823 if (isa<UnresolvedLookupExpr>(Callee)) 3824 return Inherited::VisitCXXOperatorCallExpr(E); 3825 3826 Visit(Callee); 3827 for (auto Arg : E->arguments()) 3828 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); 3829 } 3830 3831 void VisitBinaryOperator(BinaryOperator *E) { 3832 // If a field assignment is detected, remove the field from the 3833 // uninitiailized field set. 3834 if (E->getOpcode() == BO_Assign) 3835 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 3836 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 3837 if (!FD->getType()->isReferenceType()) 3838 DeclsToRemove.push_back(FD); 3839 3840 if (E->isCompoundAssignmentOp()) { 3841 HandleValue(E->getLHS(), false /*AddressOf*/); 3842 Visit(E->getRHS()); 3843 return; 3844 } 3845 3846 Inherited::VisitBinaryOperator(E); 3847 } 3848 3849 void VisitUnaryOperator(UnaryOperator *E) { 3850 if (E->isIncrementDecrementOp()) { 3851 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3852 return; 3853 } 3854 if (E->getOpcode() == UO_AddrOf) { 3855 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { 3856 HandleValue(ME->getBase(), true /*AddressOf*/); 3857 return; 3858 } 3859 } 3860 3861 Inherited::VisitUnaryOperator(E); 3862 } 3863 }; 3864 3865 // Diagnose value-uses of fields to initialize themselves, e.g. 3866 // foo(foo) 3867 // where foo is not also a parameter to the constructor. 3868 // Also diagnose across field uninitialized use such as 3869 // x(y), y(x) 3870 // TODO: implement -Wuninitialized and fold this into that framework. 3871 static void DiagnoseUninitializedFields( 3872 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 3873 3874 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 3875 Constructor->getLocation())) { 3876 return; 3877 } 3878 3879 if (Constructor->isInvalidDecl()) 3880 return; 3881 3882 const CXXRecordDecl *RD = Constructor->getParent(); 3883 3884 if (RD->isDependentContext()) 3885 return; 3886 3887 // Holds fields that are uninitialized. 3888 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 3889 3890 // At the beginning, all fields are uninitialized. 3891 for (auto *I : RD->decls()) { 3892 if (auto *FD = dyn_cast<FieldDecl>(I)) { 3893 UninitializedFields.insert(FD); 3894 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 3895 UninitializedFields.insert(IFD->getAnonField()); 3896 } 3897 } 3898 3899 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; 3900 for (auto I : RD->bases()) 3901 UninitializedBaseClasses.insert(I.getType().getCanonicalType()); 3902 3903 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3904 return; 3905 3906 UninitializedFieldVisitor UninitializedChecker(SemaRef, 3907 UninitializedFields, 3908 UninitializedBaseClasses); 3909 3910 for (const auto *FieldInit : Constructor->inits()) { 3911 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3912 break; 3913 3914 Expr *InitExpr = FieldInit->getInit(); 3915 if (!InitExpr) 3916 continue; 3917 3918 if (CXXDefaultInitExpr *Default = 3919 dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 3920 InitExpr = Default->getExpr(); 3921 if (!InitExpr) 3922 continue; 3923 // In class initializers will point to the constructor. 3924 UninitializedChecker.CheckInitializer(InitExpr, Constructor, 3925 FieldInit->getAnyMember(), 3926 FieldInit->getBaseClass()); 3927 } else { 3928 UninitializedChecker.CheckInitializer(InitExpr, nullptr, 3929 FieldInit->getAnyMember(), 3930 FieldInit->getBaseClass()); 3931 } 3932 } 3933 } 3934 } // namespace 3935 3936 /// Enter a new C++ default initializer scope. After calling this, the 3937 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 3938 /// parsing or instantiating the initializer failed. 3939 void Sema::ActOnStartCXXInClassMemberInitializer() { 3940 // Create a synthetic function scope to represent the call to the constructor 3941 // that notionally surrounds a use of this initializer. 3942 PushFunctionScope(); 3943 } 3944 3945 void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) { 3946 if (!D.isFunctionDeclarator()) 3947 return; 3948 auto &FTI = D.getFunctionTypeInfo(); 3949 if (!FTI.Params) 3950 return; 3951 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params, 3952 FTI.NumParams)) { 3953 auto *ParamDecl = cast<NamedDecl>(Param.Param); 3954 if (ParamDecl->getDeclName()) 3955 PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false); 3956 } 3957 } 3958 3959 ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) { 3960 return ActOnRequiresClause(ConstraintExpr); 3961 } 3962 3963 ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) { 3964 if (ConstraintExpr.isInvalid()) 3965 return ExprError(); 3966 3967 ConstraintExpr = CorrectDelayedTyposInExpr(ConstraintExpr); 3968 if (ConstraintExpr.isInvalid()) 3969 return ExprError(); 3970 3971 if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(), 3972 UPPC_RequiresClause)) 3973 return ExprError(); 3974 3975 return ConstraintExpr; 3976 } 3977 3978 /// This is invoked after parsing an in-class initializer for a 3979 /// non-static C++ class member, and after instantiating an in-class initializer 3980 /// in a class template. Such actions are deferred until the class is complete. 3981 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 3982 SourceLocation InitLoc, 3983 Expr *InitExpr) { 3984 // Pop the notional constructor scope we created earlier. 3985 PopFunctionScopeInfo(nullptr, D); 3986 3987 FieldDecl *FD = dyn_cast<FieldDecl>(D); 3988 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && 3989 "must set init style when field is created"); 3990 3991 if (!InitExpr) { 3992 D->setInvalidDecl(); 3993 if (FD) 3994 FD->removeInClassInitializer(); 3995 return; 3996 } 3997 3998 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 3999 FD->setInvalidDecl(); 4000 FD->removeInClassInitializer(); 4001 return; 4002 } 4003 4004 ExprResult Init = InitExpr; 4005 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 4006 InitializedEntity Entity = 4007 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD); 4008 InitializationKind Kind = 4009 FD->getInClassInitStyle() == ICIS_ListInit 4010 ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(), 4011 InitExpr->getBeginLoc(), 4012 InitExpr->getEndLoc()) 4013 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc); 4014 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 4015 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 4016 if (Init.isInvalid()) { 4017 FD->setInvalidDecl(); 4018 return; 4019 } 4020 } 4021 4022 // C++11 [class.base.init]p7: 4023 // The initialization of each base and member constitutes a 4024 // full-expression. 4025 Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false); 4026 if (Init.isInvalid()) { 4027 FD->setInvalidDecl(); 4028 return; 4029 } 4030 4031 InitExpr = Init.get(); 4032 4033 FD->setInClassInitializer(InitExpr); 4034 } 4035 4036 /// Find the direct and/or virtual base specifiers that 4037 /// correspond to the given base type, for use in base initialization 4038 /// within a constructor. 4039 static bool FindBaseInitializer(Sema &SemaRef, 4040 CXXRecordDecl *ClassDecl, 4041 QualType BaseType, 4042 const CXXBaseSpecifier *&DirectBaseSpec, 4043 const CXXBaseSpecifier *&VirtualBaseSpec) { 4044 // First, check for a direct base class. 4045 DirectBaseSpec = nullptr; 4046 for (const auto &Base : ClassDecl->bases()) { 4047 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 4048 // We found a direct base of this type. That's what we're 4049 // initializing. 4050 DirectBaseSpec = &Base; 4051 break; 4052 } 4053 } 4054 4055 // Check for a virtual base class. 4056 // FIXME: We might be able to short-circuit this if we know in advance that 4057 // there are no virtual bases. 4058 VirtualBaseSpec = nullptr; 4059 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 4060 // We haven't found a base yet; search the class hierarchy for a 4061 // virtual base class. 4062 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 4063 /*DetectVirtual=*/false); 4064 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(), 4065 SemaRef.Context.getTypeDeclType(ClassDecl), 4066 BaseType, Paths)) { 4067 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 4068 Path != Paths.end(); ++Path) { 4069 if (Path->back().Base->isVirtual()) { 4070 VirtualBaseSpec = Path->back().Base; 4071 break; 4072 } 4073 } 4074 } 4075 } 4076 4077 return DirectBaseSpec || VirtualBaseSpec; 4078 } 4079 4080 /// Handle a C++ member initializer using braced-init-list syntax. 4081 MemInitResult 4082 Sema::ActOnMemInitializer(Decl *ConstructorD, 4083 Scope *S, 4084 CXXScopeSpec &SS, 4085 IdentifierInfo *MemberOrBase, 4086 ParsedType TemplateTypeTy, 4087 const DeclSpec &DS, 4088 SourceLocation IdLoc, 4089 Expr *InitList, 4090 SourceLocation EllipsisLoc) { 4091 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 4092 DS, IdLoc, InitList, 4093 EllipsisLoc); 4094 } 4095 4096 /// Handle a C++ member initializer using parentheses syntax. 4097 MemInitResult 4098 Sema::ActOnMemInitializer(Decl *ConstructorD, 4099 Scope *S, 4100 CXXScopeSpec &SS, 4101 IdentifierInfo *MemberOrBase, 4102 ParsedType TemplateTypeTy, 4103 const DeclSpec &DS, 4104 SourceLocation IdLoc, 4105 SourceLocation LParenLoc, 4106 ArrayRef<Expr *> Args, 4107 SourceLocation RParenLoc, 4108 SourceLocation EllipsisLoc) { 4109 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc); 4110 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 4111 DS, IdLoc, List, EllipsisLoc); 4112 } 4113 4114 namespace { 4115 4116 // Callback to only accept typo corrections that can be a valid C++ member 4117 // intializer: either a non-static field member or a base class. 4118 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback { 4119 public: 4120 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 4121 : ClassDecl(ClassDecl) {} 4122 4123 bool ValidateCandidate(const TypoCorrection &candidate) override { 4124 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 4125 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 4126 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 4127 return isa<TypeDecl>(ND); 4128 } 4129 return false; 4130 } 4131 4132 std::unique_ptr<CorrectionCandidateCallback> clone() override { 4133 return std::make_unique<MemInitializerValidatorCCC>(*this); 4134 } 4135 4136 private: 4137 CXXRecordDecl *ClassDecl; 4138 }; 4139 4140 } 4141 4142 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, 4143 CXXScopeSpec &SS, 4144 ParsedType TemplateTypeTy, 4145 IdentifierInfo *MemberOrBase) { 4146 if (SS.getScopeRep() || TemplateTypeTy) 4147 return nullptr; 4148 for (auto *D : ClassDecl->lookup(MemberOrBase)) 4149 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) 4150 return cast<ValueDecl>(D); 4151 return nullptr; 4152 } 4153 4154 /// Handle a C++ member initializer. 4155 MemInitResult 4156 Sema::BuildMemInitializer(Decl *ConstructorD, 4157 Scope *S, 4158 CXXScopeSpec &SS, 4159 IdentifierInfo *MemberOrBase, 4160 ParsedType TemplateTypeTy, 4161 const DeclSpec &DS, 4162 SourceLocation IdLoc, 4163 Expr *Init, 4164 SourceLocation EllipsisLoc) { 4165 ExprResult Res = CorrectDelayedTyposInExpr(Init, /*InitDecl=*/nullptr, 4166 /*RecoverUncorrectedTypos=*/true); 4167 if (!Res.isUsable()) 4168 return true; 4169 Init = Res.get(); 4170 4171 if (!ConstructorD) 4172 return true; 4173 4174 AdjustDeclIfTemplate(ConstructorD); 4175 4176 CXXConstructorDecl *Constructor 4177 = dyn_cast<CXXConstructorDecl>(ConstructorD); 4178 if (!Constructor) { 4179 // The user wrote a constructor initializer on a function that is 4180 // not a C++ constructor. Ignore the error for now, because we may 4181 // have more member initializers coming; we'll diagnose it just 4182 // once in ActOnMemInitializers. 4183 return true; 4184 } 4185 4186 CXXRecordDecl *ClassDecl = Constructor->getParent(); 4187 4188 // C++ [class.base.init]p2: 4189 // Names in a mem-initializer-id are looked up in the scope of the 4190 // constructor's class and, if not found in that scope, are looked 4191 // up in the scope containing the constructor's definition. 4192 // [Note: if the constructor's class contains a member with the 4193 // same name as a direct or virtual base class of the class, a 4194 // mem-initializer-id naming the member or base class and composed 4195 // of a single identifier refers to the class member. A 4196 // mem-initializer-id for the hidden base class may be specified 4197 // using a qualified name. ] 4198 4199 // Look for a member, first. 4200 if (ValueDecl *Member = tryLookupCtorInitMemberDecl( 4201 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) { 4202 if (EllipsisLoc.isValid()) 4203 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 4204 << MemberOrBase 4205 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 4206 4207 return BuildMemberInitializer(Member, Init, IdLoc); 4208 } 4209 // It didn't name a member, so see if it names a class. 4210 QualType BaseType; 4211 TypeSourceInfo *TInfo = nullptr; 4212 4213 if (TemplateTypeTy) { 4214 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 4215 if (BaseType.isNull()) 4216 return true; 4217 } else if (DS.getTypeSpecType() == TST_decltype) { 4218 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 4219 } else if (DS.getTypeSpecType() == TST_decltype_auto) { 4220 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); 4221 return true; 4222 } else { 4223 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 4224 LookupParsedName(R, S, &SS); 4225 4226 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 4227 if (!TyD) { 4228 if (R.isAmbiguous()) return true; 4229 4230 // We don't want access-control diagnostics here. 4231 R.suppressDiagnostics(); 4232 4233 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 4234 bool NotUnknownSpecialization = false; 4235 DeclContext *DC = computeDeclContext(SS, false); 4236 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 4237 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 4238 4239 if (!NotUnknownSpecialization) { 4240 // When the scope specifier can refer to a member of an unknown 4241 // specialization, we take it as a type name. 4242 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 4243 SS.getWithLocInContext(Context), 4244 *MemberOrBase, IdLoc); 4245 if (BaseType.isNull()) 4246 return true; 4247 4248 TInfo = Context.CreateTypeSourceInfo(BaseType); 4249 DependentNameTypeLoc TL = 4250 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>(); 4251 if (!TL.isNull()) { 4252 TL.setNameLoc(IdLoc); 4253 TL.setElaboratedKeywordLoc(SourceLocation()); 4254 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4255 } 4256 4257 R.clear(); 4258 R.setLookupName(MemberOrBase); 4259 } 4260 } 4261 4262 // If no results were found, try to correct typos. 4263 TypoCorrection Corr; 4264 MemInitializerValidatorCCC CCC(ClassDecl); 4265 if (R.empty() && BaseType.isNull() && 4266 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 4267 CCC, CTK_ErrorRecovery, ClassDecl))) { 4268 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 4269 // We have found a non-static data member with a similar 4270 // name to what was typed; complain and initialize that 4271 // member. 4272 diagnoseTypo(Corr, 4273 PDiag(diag::err_mem_init_not_member_or_class_suggest) 4274 << MemberOrBase << true); 4275 return BuildMemberInitializer(Member, Init, IdLoc); 4276 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 4277 const CXXBaseSpecifier *DirectBaseSpec; 4278 const CXXBaseSpecifier *VirtualBaseSpec; 4279 if (FindBaseInitializer(*this, ClassDecl, 4280 Context.getTypeDeclType(Type), 4281 DirectBaseSpec, VirtualBaseSpec)) { 4282 // We have found a direct or virtual base class with a 4283 // similar name to what was typed; complain and initialize 4284 // that base class. 4285 diagnoseTypo(Corr, 4286 PDiag(diag::err_mem_init_not_member_or_class_suggest) 4287 << MemberOrBase << false, 4288 PDiag() /*Suppress note, we provide our own.*/); 4289 4290 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 4291 : VirtualBaseSpec; 4292 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here) 4293 << BaseSpec->getType() << BaseSpec->getSourceRange(); 4294 4295 TyD = Type; 4296 } 4297 } 4298 } 4299 4300 if (!TyD && BaseType.isNull()) { 4301 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 4302 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 4303 return true; 4304 } 4305 } 4306 4307 if (BaseType.isNull()) { 4308 BaseType = Context.getTypeDeclType(TyD); 4309 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); 4310 if (SS.isSet()) { 4311 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 4312 BaseType); 4313 TInfo = Context.CreateTypeSourceInfo(BaseType); 4314 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>(); 4315 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc); 4316 TL.setElaboratedKeywordLoc(SourceLocation()); 4317 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4318 } 4319 } 4320 } 4321 4322 if (!TInfo) 4323 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 4324 4325 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 4326 } 4327 4328 MemInitResult 4329 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 4330 SourceLocation IdLoc) { 4331 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 4332 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 4333 assert((DirectMember || IndirectMember) && 4334 "Member must be a FieldDecl or IndirectFieldDecl"); 4335 4336 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4337 return true; 4338 4339 if (Member->isInvalidDecl()) 4340 return true; 4341 4342 MultiExprArg Args; 4343 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4344 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4345 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 4346 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 4347 } else { 4348 // Template instantiation doesn't reconstruct ParenListExprs for us. 4349 Args = Init; 4350 } 4351 4352 SourceRange InitRange = Init->getSourceRange(); 4353 4354 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 4355 // Can't check initialization for a member of dependent type or when 4356 // any of the arguments are type-dependent expressions. 4357 DiscardCleanupsInEvaluationContext(); 4358 } else { 4359 bool InitList = false; 4360 if (isa<InitListExpr>(Init)) { 4361 InitList = true; 4362 Args = Init; 4363 } 4364 4365 // Initialize the member. 4366 InitializedEntity MemberEntity = 4367 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 4368 : InitializedEntity::InitializeMember(IndirectMember, 4369 nullptr); 4370 InitializationKind Kind = 4371 InitList ? InitializationKind::CreateDirectList( 4372 IdLoc, Init->getBeginLoc(), Init->getEndLoc()) 4373 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 4374 InitRange.getEnd()); 4375 4376 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 4377 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 4378 nullptr); 4379 if (!MemberInit.isInvalid()) { 4380 // C++11 [class.base.init]p7: 4381 // The initialization of each base and member constitutes a 4382 // full-expression. 4383 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(), 4384 /*DiscardedValue*/ false); 4385 } 4386 4387 if (MemberInit.isInvalid()) { 4388 // Args were sensible expressions but we couldn't initialize the member 4389 // from them. Preserve them in a RecoveryExpr instead. 4390 Init = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args, 4391 Member->getType()) 4392 .get(); 4393 if (!Init) 4394 return true; 4395 } else { 4396 Init = MemberInit.get(); 4397 } 4398 } 4399 4400 if (DirectMember) { 4401 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 4402 InitRange.getBegin(), Init, 4403 InitRange.getEnd()); 4404 } else { 4405 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 4406 InitRange.getBegin(), Init, 4407 InitRange.getEnd()); 4408 } 4409 } 4410 4411 MemInitResult 4412 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 4413 CXXRecordDecl *ClassDecl) { 4414 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4415 if (!LangOpts.CPlusPlus11) 4416 return Diag(NameLoc, diag::err_delegating_ctor) 4417 << TInfo->getTypeLoc().getLocalSourceRange(); 4418 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 4419 4420 bool InitList = true; 4421 MultiExprArg Args = Init; 4422 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4423 InitList = false; 4424 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4425 } 4426 4427 SourceRange InitRange = Init->getSourceRange(); 4428 // Initialize the object. 4429 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 4430 QualType(ClassDecl->getTypeForDecl(), 0)); 4431 InitializationKind Kind = 4432 InitList ? InitializationKind::CreateDirectList( 4433 NameLoc, Init->getBeginLoc(), Init->getEndLoc()) 4434 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 4435 InitRange.getEnd()); 4436 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 4437 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 4438 Args, nullptr); 4439 if (!DelegationInit.isInvalid()) { 4440 assert((DelegationInit.get()->containsErrors() || 4441 cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) && 4442 "Delegating constructor with no target?"); 4443 4444 // C++11 [class.base.init]p7: 4445 // The initialization of each base and member constitutes a 4446 // full-expression. 4447 DelegationInit = ActOnFinishFullExpr( 4448 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false); 4449 } 4450 4451 if (DelegationInit.isInvalid()) { 4452 DelegationInit = 4453 CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args, 4454 QualType(ClassDecl->getTypeForDecl(), 0)); 4455 if (DelegationInit.isInvalid()) 4456 return true; 4457 } else { 4458 // If we are in a dependent context, template instantiation will 4459 // perform this type-checking again. Just save the arguments that we 4460 // received in a ParenListExpr. 4461 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4462 // of the information that we have about the base 4463 // initializer. However, deconstructing the ASTs is a dicey process, 4464 // and this approach is far more likely to get the corner cases right. 4465 if (CurContext->isDependentContext()) 4466 DelegationInit = Init; 4467 } 4468 4469 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 4470 DelegationInit.getAs<Expr>(), 4471 InitRange.getEnd()); 4472 } 4473 4474 MemInitResult 4475 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 4476 Expr *Init, CXXRecordDecl *ClassDecl, 4477 SourceLocation EllipsisLoc) { 4478 SourceLocation BaseLoc 4479 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4480 4481 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 4482 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 4483 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4484 4485 // C++ [class.base.init]p2: 4486 // [...] Unless the mem-initializer-id names a nonstatic data 4487 // member of the constructor's class or a direct or virtual base 4488 // of that class, the mem-initializer is ill-formed. A 4489 // mem-initializer-list can initialize a base class using any 4490 // name that denotes that base class type. 4491 4492 // We can store the initializers in "as-written" form and delay analysis until 4493 // instantiation if the constructor is dependent. But not for dependent 4494 // (broken) code in a non-template! SetCtorInitializers does not expect this. 4495 bool Dependent = CurContext->isDependentContext() && 4496 (BaseType->isDependentType() || Init->isTypeDependent()); 4497 4498 SourceRange InitRange = Init->getSourceRange(); 4499 if (EllipsisLoc.isValid()) { 4500 // This is a pack expansion. 4501 if (!BaseType->containsUnexpandedParameterPack()) { 4502 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 4503 << SourceRange(BaseLoc, InitRange.getEnd()); 4504 4505 EllipsisLoc = SourceLocation(); 4506 } 4507 } else { 4508 // Check for any unexpanded parameter packs. 4509 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 4510 return true; 4511 4512 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4513 return true; 4514 } 4515 4516 // Check for direct and virtual base classes. 4517 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 4518 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 4519 if (!Dependent) { 4520 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 4521 BaseType)) 4522 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 4523 4524 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 4525 VirtualBaseSpec); 4526 4527 // C++ [base.class.init]p2: 4528 // Unless the mem-initializer-id names a nonstatic data member of the 4529 // constructor's class or a direct or virtual base of that class, the 4530 // mem-initializer is ill-formed. 4531 if (!DirectBaseSpec && !VirtualBaseSpec) { 4532 // If the class has any dependent bases, then it's possible that 4533 // one of those types will resolve to the same type as 4534 // BaseType. Therefore, just treat this as a dependent base 4535 // class initialization. FIXME: Should we try to check the 4536 // initialization anyway? It seems odd. 4537 if (ClassDecl->hasAnyDependentBases()) 4538 Dependent = true; 4539 else 4540 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 4541 << BaseType << Context.getTypeDeclType(ClassDecl) 4542 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4543 } 4544 } 4545 4546 if (Dependent) { 4547 DiscardCleanupsInEvaluationContext(); 4548 4549 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4550 /*IsVirtual=*/false, 4551 InitRange.getBegin(), Init, 4552 InitRange.getEnd(), EllipsisLoc); 4553 } 4554 4555 // C++ [base.class.init]p2: 4556 // If a mem-initializer-id is ambiguous because it designates both 4557 // a direct non-virtual base class and an inherited virtual base 4558 // class, the mem-initializer is ill-formed. 4559 if (DirectBaseSpec && VirtualBaseSpec) 4560 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 4561 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4562 4563 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 4564 if (!BaseSpec) 4565 BaseSpec = VirtualBaseSpec; 4566 4567 // Initialize the base. 4568 bool InitList = true; 4569 MultiExprArg Args = Init; 4570 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4571 InitList = false; 4572 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4573 } 4574 4575 InitializedEntity BaseEntity = 4576 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 4577 InitializationKind Kind = 4578 InitList ? InitializationKind::CreateDirectList(BaseLoc) 4579 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 4580 InitRange.getEnd()); 4581 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 4582 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 4583 if (!BaseInit.isInvalid()) { 4584 // C++11 [class.base.init]p7: 4585 // The initialization of each base and member constitutes a 4586 // full-expression. 4587 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(), 4588 /*DiscardedValue*/ false); 4589 } 4590 4591 if (BaseInit.isInvalid()) { 4592 BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), 4593 Args, BaseType); 4594 if (BaseInit.isInvalid()) 4595 return true; 4596 } else { 4597 // If we are in a dependent context, template instantiation will 4598 // perform this type-checking again. Just save the arguments that we 4599 // received in a ParenListExpr. 4600 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4601 // of the information that we have about the base 4602 // initializer. However, deconstructing the ASTs is a dicey process, 4603 // and this approach is far more likely to get the corner cases right. 4604 if (CurContext->isDependentContext()) 4605 BaseInit = Init; 4606 } 4607 4608 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4609 BaseSpec->isVirtual(), 4610 InitRange.getBegin(), 4611 BaseInit.getAs<Expr>(), 4612 InitRange.getEnd(), EllipsisLoc); 4613 } 4614 4615 // Create a static_cast\<T&&>(expr). 4616 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 4617 if (T.isNull()) T = E->getType(); 4618 QualType TargetType = SemaRef.BuildReferenceType( 4619 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 4620 SourceLocation ExprLoc = E->getBeginLoc(); 4621 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 4622 TargetType, ExprLoc); 4623 4624 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 4625 SourceRange(ExprLoc, ExprLoc), 4626 E->getSourceRange()).get(); 4627 } 4628 4629 /// ImplicitInitializerKind - How an implicit base or member initializer should 4630 /// initialize its base or member. 4631 enum ImplicitInitializerKind { 4632 IIK_Default, 4633 IIK_Copy, 4634 IIK_Move, 4635 IIK_Inherit 4636 }; 4637 4638 static bool 4639 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4640 ImplicitInitializerKind ImplicitInitKind, 4641 CXXBaseSpecifier *BaseSpec, 4642 bool IsInheritedVirtualBase, 4643 CXXCtorInitializer *&CXXBaseInit) { 4644 InitializedEntity InitEntity 4645 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 4646 IsInheritedVirtualBase); 4647 4648 ExprResult BaseInit; 4649 4650 switch (ImplicitInitKind) { 4651 case IIK_Inherit: 4652 case IIK_Default: { 4653 InitializationKind InitKind 4654 = InitializationKind::CreateDefault(Constructor->getLocation()); 4655 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4656 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4657 break; 4658 } 4659 4660 case IIK_Move: 4661 case IIK_Copy: { 4662 bool Moving = ImplicitInitKind == IIK_Move; 4663 ParmVarDecl *Param = Constructor->getParamDecl(0); 4664 QualType ParamType = Param->getType().getNonReferenceType(); 4665 4666 Expr *CopyCtorArg = 4667 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4668 SourceLocation(), Param, false, 4669 Constructor->getLocation(), ParamType, 4670 VK_LValue, nullptr); 4671 4672 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 4673 4674 // Cast to the base class to avoid ambiguities. 4675 QualType ArgTy = 4676 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 4677 ParamType.getQualifiers()); 4678 4679 if (Moving) { 4680 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 4681 } 4682 4683 CXXCastPath BasePath; 4684 BasePath.push_back(BaseSpec); 4685 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 4686 CK_UncheckedDerivedToBase, 4687 Moving ? VK_XValue : VK_LValue, 4688 &BasePath).get(); 4689 4690 InitializationKind InitKind 4691 = InitializationKind::CreateDirect(Constructor->getLocation(), 4692 SourceLocation(), SourceLocation()); 4693 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 4694 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 4695 break; 4696 } 4697 } 4698 4699 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 4700 if (BaseInit.isInvalid()) 4701 return true; 4702 4703 CXXBaseInit = 4704 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4705 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 4706 SourceLocation()), 4707 BaseSpec->isVirtual(), 4708 SourceLocation(), 4709 BaseInit.getAs<Expr>(), 4710 SourceLocation(), 4711 SourceLocation()); 4712 4713 return false; 4714 } 4715 4716 static bool RefersToRValueRef(Expr *MemRef) { 4717 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 4718 return Referenced->getType()->isRValueReferenceType(); 4719 } 4720 4721 static bool 4722 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4723 ImplicitInitializerKind ImplicitInitKind, 4724 FieldDecl *Field, IndirectFieldDecl *Indirect, 4725 CXXCtorInitializer *&CXXMemberInit) { 4726 if (Field->isInvalidDecl()) 4727 return true; 4728 4729 SourceLocation Loc = Constructor->getLocation(); 4730 4731 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 4732 bool Moving = ImplicitInitKind == IIK_Move; 4733 ParmVarDecl *Param = Constructor->getParamDecl(0); 4734 QualType ParamType = Param->getType().getNonReferenceType(); 4735 4736 // Suppress copying zero-width bitfields. 4737 if (Field->isZeroLengthBitField(SemaRef.Context)) 4738 return false; 4739 4740 Expr *MemberExprBase = 4741 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4742 SourceLocation(), Param, false, 4743 Loc, ParamType, VK_LValue, nullptr); 4744 4745 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 4746 4747 if (Moving) { 4748 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 4749 } 4750 4751 // Build a reference to this field within the parameter. 4752 CXXScopeSpec SS; 4753 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 4754 Sema::LookupMemberName); 4755 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 4756 : cast<ValueDecl>(Field), AS_public); 4757 MemberLookup.resolveKind(); 4758 ExprResult CtorArg 4759 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 4760 ParamType, Loc, 4761 /*IsArrow=*/false, 4762 SS, 4763 /*TemplateKWLoc=*/SourceLocation(), 4764 /*FirstQualifierInScope=*/nullptr, 4765 MemberLookup, 4766 /*TemplateArgs=*/nullptr, 4767 /*S*/nullptr); 4768 if (CtorArg.isInvalid()) 4769 return true; 4770 4771 // C++11 [class.copy]p15: 4772 // - if a member m has rvalue reference type T&&, it is direct-initialized 4773 // with static_cast<T&&>(x.m); 4774 if (RefersToRValueRef(CtorArg.get())) { 4775 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 4776 } 4777 4778 InitializedEntity Entity = 4779 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4780 /*Implicit*/ true) 4781 : InitializedEntity::InitializeMember(Field, nullptr, 4782 /*Implicit*/ true); 4783 4784 // Direct-initialize to use the copy constructor. 4785 InitializationKind InitKind = 4786 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 4787 4788 Expr *CtorArgE = CtorArg.getAs<Expr>(); 4789 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE); 4790 ExprResult MemberInit = 4791 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1)); 4792 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4793 if (MemberInit.isInvalid()) 4794 return true; 4795 4796 if (Indirect) 4797 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4798 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4799 else 4800 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4801 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4802 return false; 4803 } 4804 4805 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 4806 "Unhandled implicit init kind!"); 4807 4808 QualType FieldBaseElementType = 4809 SemaRef.Context.getBaseElementType(Field->getType()); 4810 4811 if (FieldBaseElementType->isRecordType()) { 4812 InitializedEntity InitEntity = 4813 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4814 /*Implicit*/ true) 4815 : InitializedEntity::InitializeMember(Field, nullptr, 4816 /*Implicit*/ true); 4817 InitializationKind InitKind = 4818 InitializationKind::CreateDefault(Loc); 4819 4820 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4821 ExprResult MemberInit = 4822 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4823 4824 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4825 if (MemberInit.isInvalid()) 4826 return true; 4827 4828 if (Indirect) 4829 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4830 Indirect, Loc, 4831 Loc, 4832 MemberInit.get(), 4833 Loc); 4834 else 4835 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4836 Field, Loc, Loc, 4837 MemberInit.get(), 4838 Loc); 4839 return false; 4840 } 4841 4842 if (!Field->getParent()->isUnion()) { 4843 if (FieldBaseElementType->isReferenceType()) { 4844 SemaRef.Diag(Constructor->getLocation(), 4845 diag::err_uninitialized_member_in_ctor) 4846 << (int)Constructor->isImplicit() 4847 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4848 << 0 << Field->getDeclName(); 4849 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4850 return true; 4851 } 4852 4853 if (FieldBaseElementType.isConstQualified()) { 4854 SemaRef.Diag(Constructor->getLocation(), 4855 diag::err_uninitialized_member_in_ctor) 4856 << (int)Constructor->isImplicit() 4857 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4858 << 1 << Field->getDeclName(); 4859 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4860 return true; 4861 } 4862 } 4863 4864 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) { 4865 // ARC and Weak: 4866 // Default-initialize Objective-C pointers to NULL. 4867 CXXMemberInit 4868 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 4869 Loc, Loc, 4870 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 4871 Loc); 4872 return false; 4873 } 4874 4875 // Nothing to initialize. 4876 CXXMemberInit = nullptr; 4877 return false; 4878 } 4879 4880 namespace { 4881 struct BaseAndFieldInfo { 4882 Sema &S; 4883 CXXConstructorDecl *Ctor; 4884 bool AnyErrorsInInits; 4885 ImplicitInitializerKind IIK; 4886 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 4887 SmallVector<CXXCtorInitializer*, 8> AllToInit; 4888 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 4889 4890 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 4891 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 4892 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 4893 if (Ctor->getInheritedConstructor()) 4894 IIK = IIK_Inherit; 4895 else if (Generated && Ctor->isCopyConstructor()) 4896 IIK = IIK_Copy; 4897 else if (Generated && Ctor->isMoveConstructor()) 4898 IIK = IIK_Move; 4899 else 4900 IIK = IIK_Default; 4901 } 4902 4903 bool isImplicitCopyOrMove() const { 4904 switch (IIK) { 4905 case IIK_Copy: 4906 case IIK_Move: 4907 return true; 4908 4909 case IIK_Default: 4910 case IIK_Inherit: 4911 return false; 4912 } 4913 4914 llvm_unreachable("Invalid ImplicitInitializerKind!"); 4915 } 4916 4917 bool addFieldInitializer(CXXCtorInitializer *Init) { 4918 AllToInit.push_back(Init); 4919 4920 // Check whether this initializer makes the field "used". 4921 if (Init->getInit()->HasSideEffects(S.Context)) 4922 S.UnusedPrivateFields.remove(Init->getAnyMember()); 4923 4924 return false; 4925 } 4926 4927 bool isInactiveUnionMember(FieldDecl *Field) { 4928 RecordDecl *Record = Field->getParent(); 4929 if (!Record->isUnion()) 4930 return false; 4931 4932 if (FieldDecl *Active = 4933 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 4934 return Active != Field->getCanonicalDecl(); 4935 4936 // In an implicit copy or move constructor, ignore any in-class initializer. 4937 if (isImplicitCopyOrMove()) 4938 return true; 4939 4940 // If there's no explicit initialization, the field is active only if it 4941 // has an in-class initializer... 4942 if (Field->hasInClassInitializer()) 4943 return false; 4944 // ... or it's an anonymous struct or union whose class has an in-class 4945 // initializer. 4946 if (!Field->isAnonymousStructOrUnion()) 4947 return true; 4948 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 4949 return !FieldRD->hasInClassInitializer(); 4950 } 4951 4952 /// Determine whether the given field is, or is within, a union member 4953 /// that is inactive (because there was an initializer given for a different 4954 /// member of the union, or because the union was not initialized at all). 4955 bool isWithinInactiveUnionMember(FieldDecl *Field, 4956 IndirectFieldDecl *Indirect) { 4957 if (!Indirect) 4958 return isInactiveUnionMember(Field); 4959 4960 for (auto *C : Indirect->chain()) { 4961 FieldDecl *Field = dyn_cast<FieldDecl>(C); 4962 if (Field && isInactiveUnionMember(Field)) 4963 return true; 4964 } 4965 return false; 4966 } 4967 }; 4968 } 4969 4970 /// Determine whether the given type is an incomplete or zero-lenfgth 4971 /// array type. 4972 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 4973 if (T->isIncompleteArrayType()) 4974 return true; 4975 4976 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 4977 if (!ArrayT->getSize()) 4978 return true; 4979 4980 T = ArrayT->getElementType(); 4981 } 4982 4983 return false; 4984 } 4985 4986 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 4987 FieldDecl *Field, 4988 IndirectFieldDecl *Indirect = nullptr) { 4989 if (Field->isInvalidDecl()) 4990 return false; 4991 4992 // Overwhelmingly common case: we have a direct initializer for this field. 4993 if (CXXCtorInitializer *Init = 4994 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 4995 return Info.addFieldInitializer(Init); 4996 4997 // C++11 [class.base.init]p8: 4998 // if the entity is a non-static data member that has a 4999 // brace-or-equal-initializer and either 5000 // -- the constructor's class is a union and no other variant member of that 5001 // union is designated by a mem-initializer-id or 5002 // -- the constructor's class is not a union, and, if the entity is a member 5003 // of an anonymous union, no other member of that union is designated by 5004 // a mem-initializer-id, 5005 // the entity is initialized as specified in [dcl.init]. 5006 // 5007 // We also apply the same rules to handle anonymous structs within anonymous 5008 // unions. 5009 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 5010 return false; 5011 5012 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 5013 ExprResult DIE = 5014 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); 5015 if (DIE.isInvalid()) 5016 return true; 5017 5018 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true); 5019 SemaRef.checkInitializerLifetime(Entity, DIE.get()); 5020 5021 CXXCtorInitializer *Init; 5022 if (Indirect) 5023 Init = new (SemaRef.Context) 5024 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), 5025 SourceLocation(), DIE.get(), SourceLocation()); 5026 else 5027 Init = new (SemaRef.Context) 5028 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), 5029 SourceLocation(), DIE.get(), SourceLocation()); 5030 return Info.addFieldInitializer(Init); 5031 } 5032 5033 // Don't initialize incomplete or zero-length arrays. 5034 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 5035 return false; 5036 5037 // Don't try to build an implicit initializer if there were semantic 5038 // errors in any of the initializers (and therefore we might be 5039 // missing some that the user actually wrote). 5040 if (Info.AnyErrorsInInits) 5041 return false; 5042 5043 CXXCtorInitializer *Init = nullptr; 5044 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 5045 Indirect, Init)) 5046 return true; 5047 5048 if (!Init) 5049 return false; 5050 5051 return Info.addFieldInitializer(Init); 5052 } 5053 5054 bool 5055 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 5056 CXXCtorInitializer *Initializer) { 5057 assert(Initializer->isDelegatingInitializer()); 5058 Constructor->setNumCtorInitializers(1); 5059 CXXCtorInitializer **initializer = 5060 new (Context) CXXCtorInitializer*[1]; 5061 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 5062 Constructor->setCtorInitializers(initializer); 5063 5064 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 5065 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 5066 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 5067 } 5068 5069 DelegatingCtorDecls.push_back(Constructor); 5070 5071 DiagnoseUninitializedFields(*this, Constructor); 5072 5073 return false; 5074 } 5075 5076 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 5077 ArrayRef<CXXCtorInitializer *> Initializers) { 5078 if (Constructor->isDependentContext()) { 5079 // Just store the initializers as written, they will be checked during 5080 // instantiation. 5081 if (!Initializers.empty()) { 5082 Constructor->setNumCtorInitializers(Initializers.size()); 5083 CXXCtorInitializer **baseOrMemberInitializers = 5084 new (Context) CXXCtorInitializer*[Initializers.size()]; 5085 memcpy(baseOrMemberInitializers, Initializers.data(), 5086 Initializers.size() * sizeof(CXXCtorInitializer*)); 5087 Constructor->setCtorInitializers(baseOrMemberInitializers); 5088 } 5089 5090 // Let template instantiation know whether we had errors. 5091 if (AnyErrors) 5092 Constructor->setInvalidDecl(); 5093 5094 return false; 5095 } 5096 5097 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 5098 5099 // We need to build the initializer AST according to order of construction 5100 // and not what user specified in the Initializers list. 5101 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 5102 if (!ClassDecl) 5103 return true; 5104 5105 bool HadError = false; 5106 5107 for (unsigned i = 0; i < Initializers.size(); i++) { 5108 CXXCtorInitializer *Member = Initializers[i]; 5109 5110 if (Member->isBaseInitializer()) 5111 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 5112 else { 5113 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 5114 5115 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 5116 for (auto *C : F->chain()) { 5117 FieldDecl *FD = dyn_cast<FieldDecl>(C); 5118 if (FD && FD->getParent()->isUnion()) 5119 Info.ActiveUnionMember.insert(std::make_pair( 5120 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 5121 } 5122 } else if (FieldDecl *FD = Member->getMember()) { 5123 if (FD->getParent()->isUnion()) 5124 Info.ActiveUnionMember.insert(std::make_pair( 5125 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 5126 } 5127 } 5128 } 5129 5130 // Keep track of the direct virtual bases. 5131 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 5132 for (auto &I : ClassDecl->bases()) { 5133 if (I.isVirtual()) 5134 DirectVBases.insert(&I); 5135 } 5136 5137 // Push virtual bases before others. 5138 for (auto &VBase : ClassDecl->vbases()) { 5139 if (CXXCtorInitializer *Value 5140 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 5141 // [class.base.init]p7, per DR257: 5142 // A mem-initializer where the mem-initializer-id names a virtual base 5143 // class is ignored during execution of a constructor of any class that 5144 // is not the most derived class. 5145 if (ClassDecl->isAbstract()) { 5146 // FIXME: Provide a fixit to remove the base specifier. This requires 5147 // tracking the location of the associated comma for a base specifier. 5148 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 5149 << VBase.getType() << ClassDecl; 5150 DiagnoseAbstractType(ClassDecl); 5151 } 5152 5153 Info.AllToInit.push_back(Value); 5154 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 5155 // [class.base.init]p8, per DR257: 5156 // If a given [...] base class is not named by a mem-initializer-id 5157 // [...] and the entity is not a virtual base class of an abstract 5158 // class, then [...] the entity is default-initialized. 5159 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 5160 CXXCtorInitializer *CXXBaseInit; 5161 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 5162 &VBase, IsInheritedVirtualBase, 5163 CXXBaseInit)) { 5164 HadError = true; 5165 continue; 5166 } 5167 5168 Info.AllToInit.push_back(CXXBaseInit); 5169 } 5170 } 5171 5172 // Non-virtual bases. 5173 for (auto &Base : ClassDecl->bases()) { 5174 // Virtuals are in the virtual base list and already constructed. 5175 if (Base.isVirtual()) 5176 continue; 5177 5178 if (CXXCtorInitializer *Value 5179 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 5180 Info.AllToInit.push_back(Value); 5181 } else if (!AnyErrors) { 5182 CXXCtorInitializer *CXXBaseInit; 5183 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 5184 &Base, /*IsInheritedVirtualBase=*/false, 5185 CXXBaseInit)) { 5186 HadError = true; 5187 continue; 5188 } 5189 5190 Info.AllToInit.push_back(CXXBaseInit); 5191 } 5192 } 5193 5194 // Fields. 5195 for (auto *Mem : ClassDecl->decls()) { 5196 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 5197 // C++ [class.bit]p2: 5198 // A declaration for a bit-field that omits the identifier declares an 5199 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 5200 // initialized. 5201 if (F->isUnnamedBitfield()) 5202 continue; 5203 5204 // If we're not generating the implicit copy/move constructor, then we'll 5205 // handle anonymous struct/union fields based on their individual 5206 // indirect fields. 5207 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 5208 continue; 5209 5210 if (CollectFieldInitializer(*this, Info, F)) 5211 HadError = true; 5212 continue; 5213 } 5214 5215 // Beyond this point, we only consider default initialization. 5216 if (Info.isImplicitCopyOrMove()) 5217 continue; 5218 5219 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 5220 if (F->getType()->isIncompleteArrayType()) { 5221 assert(ClassDecl->hasFlexibleArrayMember() && 5222 "Incomplete array type is not valid"); 5223 continue; 5224 } 5225 5226 // Initialize each field of an anonymous struct individually. 5227 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 5228 HadError = true; 5229 5230 continue; 5231 } 5232 } 5233 5234 unsigned NumInitializers = Info.AllToInit.size(); 5235 if (NumInitializers > 0) { 5236 Constructor->setNumCtorInitializers(NumInitializers); 5237 CXXCtorInitializer **baseOrMemberInitializers = 5238 new (Context) CXXCtorInitializer*[NumInitializers]; 5239 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 5240 NumInitializers * sizeof(CXXCtorInitializer*)); 5241 Constructor->setCtorInitializers(baseOrMemberInitializers); 5242 5243 // Constructors implicitly reference the base and member 5244 // destructors. 5245 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 5246 Constructor->getParent()); 5247 } 5248 5249 return HadError; 5250 } 5251 5252 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 5253 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 5254 const RecordDecl *RD = RT->getDecl(); 5255 if (RD->isAnonymousStructOrUnion()) { 5256 for (auto *Field : RD->fields()) 5257 PopulateKeysForFields(Field, IdealInits); 5258 return; 5259 } 5260 } 5261 IdealInits.push_back(Field->getCanonicalDecl()); 5262 } 5263 5264 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 5265 return Context.getCanonicalType(BaseType).getTypePtr(); 5266 } 5267 5268 static const void *GetKeyForMember(ASTContext &Context, 5269 CXXCtorInitializer *Member) { 5270 if (!Member->isAnyMemberInitializer()) 5271 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 5272 5273 return Member->getAnyMember()->getCanonicalDecl(); 5274 } 5275 5276 static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag, 5277 const CXXCtorInitializer *Previous, 5278 const CXXCtorInitializer *Current) { 5279 if (Previous->isAnyMemberInitializer()) 5280 Diag << 0 << Previous->getAnyMember(); 5281 else 5282 Diag << 1 << Previous->getTypeSourceInfo()->getType(); 5283 5284 if (Current->isAnyMemberInitializer()) 5285 Diag << 0 << Current->getAnyMember(); 5286 else 5287 Diag << 1 << Current->getTypeSourceInfo()->getType(); 5288 } 5289 5290 static void DiagnoseBaseOrMemInitializerOrder( 5291 Sema &SemaRef, const CXXConstructorDecl *Constructor, 5292 ArrayRef<CXXCtorInitializer *> Inits) { 5293 if (Constructor->getDeclContext()->isDependentContext()) 5294 return; 5295 5296 // Don't check initializers order unless the warning is enabled at the 5297 // location of at least one initializer. 5298 bool ShouldCheckOrder = false; 5299 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 5300 CXXCtorInitializer *Init = Inits[InitIndex]; 5301 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 5302 Init->getSourceLocation())) { 5303 ShouldCheckOrder = true; 5304 break; 5305 } 5306 } 5307 if (!ShouldCheckOrder) 5308 return; 5309 5310 // Build the list of bases and members in the order that they'll 5311 // actually be initialized. The explicit initializers should be in 5312 // this same order but may be missing things. 5313 SmallVector<const void*, 32> IdealInitKeys; 5314 5315 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 5316 5317 // 1. Virtual bases. 5318 for (const auto &VBase : ClassDecl->vbases()) 5319 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 5320 5321 // 2. Non-virtual bases. 5322 for (const auto &Base : ClassDecl->bases()) { 5323 if (Base.isVirtual()) 5324 continue; 5325 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 5326 } 5327 5328 // 3. Direct fields. 5329 for (auto *Field : ClassDecl->fields()) { 5330 if (Field->isUnnamedBitfield()) 5331 continue; 5332 5333 PopulateKeysForFields(Field, IdealInitKeys); 5334 } 5335 5336 unsigned NumIdealInits = IdealInitKeys.size(); 5337 unsigned IdealIndex = 0; 5338 5339 // Track initializers that are in an incorrect order for either a warning or 5340 // note if multiple ones occur. 5341 SmallVector<unsigned> WarnIndexes; 5342 // Correlates the index of an initializer in the init-list to the index of 5343 // the field/base in the class. 5344 SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder; 5345 5346 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 5347 const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]); 5348 5349 // Scan forward to try to find this initializer in the idealized 5350 // initializers list. 5351 for (; IdealIndex != NumIdealInits; ++IdealIndex) 5352 if (InitKey == IdealInitKeys[IdealIndex]) 5353 break; 5354 5355 // If we didn't find this initializer, it must be because we 5356 // scanned past it on a previous iteration. That can only 5357 // happen if we're out of order; emit a warning. 5358 if (IdealIndex == NumIdealInits && InitIndex) { 5359 WarnIndexes.push_back(InitIndex); 5360 5361 // Move back to the initializer's location in the ideal list. 5362 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 5363 if (InitKey == IdealInitKeys[IdealIndex]) 5364 break; 5365 5366 assert(IdealIndex < NumIdealInits && 5367 "initializer not found in initializer list"); 5368 } 5369 CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex); 5370 } 5371 5372 if (WarnIndexes.empty()) 5373 return; 5374 5375 // Sort based on the ideal order, first in the pair. 5376 llvm::sort(CorrelatedInitOrder, 5377 [](auto &LHS, auto &RHS) { return LHS.first < RHS.first; }); 5378 5379 // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to 5380 // emit the diagnostic before we can try adding notes. 5381 { 5382 Sema::SemaDiagnosticBuilder D = SemaRef.Diag( 5383 Inits[WarnIndexes.front() - 1]->getSourceLocation(), 5384 WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order 5385 : diag::warn_some_initializers_out_of_order); 5386 5387 for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) { 5388 if (CorrelatedInitOrder[I].second == I) 5389 continue; 5390 // Ideally we would be using InsertFromRange here, but clang doesn't 5391 // appear to handle InsertFromRange correctly when the source range is 5392 // modified by another fix-it. 5393 D << FixItHint::CreateReplacement( 5394 Inits[I]->getSourceRange(), 5395 Lexer::getSourceText( 5396 CharSourceRange::getTokenRange( 5397 Inits[CorrelatedInitOrder[I].second]->getSourceRange()), 5398 SemaRef.getSourceManager(), SemaRef.getLangOpts())); 5399 } 5400 5401 // If there is only 1 item out of order, the warning expects the name and 5402 // type of each being added to it. 5403 if (WarnIndexes.size() == 1) { 5404 AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1], 5405 Inits[WarnIndexes.front()]); 5406 return; 5407 } 5408 } 5409 // More than 1 item to warn, create notes letting the user know which ones 5410 // are bad. 5411 for (unsigned WarnIndex : WarnIndexes) { 5412 const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1]; 5413 auto D = SemaRef.Diag(PrevInit->getSourceLocation(), 5414 diag::note_initializer_out_of_order); 5415 AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]); 5416 D << PrevInit->getSourceRange(); 5417 } 5418 } 5419 5420 namespace { 5421 bool CheckRedundantInit(Sema &S, 5422 CXXCtorInitializer *Init, 5423 CXXCtorInitializer *&PrevInit) { 5424 if (!PrevInit) { 5425 PrevInit = Init; 5426 return false; 5427 } 5428 5429 if (FieldDecl *Field = Init->getAnyMember()) 5430 S.Diag(Init->getSourceLocation(), 5431 diag::err_multiple_mem_initialization) 5432 << Field->getDeclName() 5433 << Init->getSourceRange(); 5434 else { 5435 const Type *BaseClass = Init->getBaseClass(); 5436 assert(BaseClass && "neither field nor base"); 5437 S.Diag(Init->getSourceLocation(), 5438 diag::err_multiple_base_initialization) 5439 << QualType(BaseClass, 0) 5440 << Init->getSourceRange(); 5441 } 5442 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 5443 << 0 << PrevInit->getSourceRange(); 5444 5445 return true; 5446 } 5447 5448 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 5449 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 5450 5451 bool CheckRedundantUnionInit(Sema &S, 5452 CXXCtorInitializer *Init, 5453 RedundantUnionMap &Unions) { 5454 FieldDecl *Field = Init->getAnyMember(); 5455 RecordDecl *Parent = Field->getParent(); 5456 NamedDecl *Child = Field; 5457 5458 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 5459 if (Parent->isUnion()) { 5460 UnionEntry &En = Unions[Parent]; 5461 if (En.first && En.first != Child) { 5462 S.Diag(Init->getSourceLocation(), 5463 diag::err_multiple_mem_union_initialization) 5464 << Field->getDeclName() 5465 << Init->getSourceRange(); 5466 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 5467 << 0 << En.second->getSourceRange(); 5468 return true; 5469 } 5470 if (!En.first) { 5471 En.first = Child; 5472 En.second = Init; 5473 } 5474 if (!Parent->isAnonymousStructOrUnion()) 5475 return false; 5476 } 5477 5478 Child = Parent; 5479 Parent = cast<RecordDecl>(Parent->getDeclContext()); 5480 } 5481 5482 return false; 5483 } 5484 } // namespace 5485 5486 /// ActOnMemInitializers - Handle the member initializers for a constructor. 5487 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 5488 SourceLocation ColonLoc, 5489 ArrayRef<CXXCtorInitializer*> MemInits, 5490 bool AnyErrors) { 5491 if (!ConstructorDecl) 5492 return; 5493 5494 AdjustDeclIfTemplate(ConstructorDecl); 5495 5496 CXXConstructorDecl *Constructor 5497 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 5498 5499 if (!Constructor) { 5500 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 5501 return; 5502 } 5503 5504 // Mapping for the duplicate initializers check. 5505 // For member initializers, this is keyed with a FieldDecl*. 5506 // For base initializers, this is keyed with a Type*. 5507 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 5508 5509 // Mapping for the inconsistent anonymous-union initializers check. 5510 RedundantUnionMap MemberUnions; 5511 5512 bool HadError = false; 5513 for (unsigned i = 0; i < MemInits.size(); i++) { 5514 CXXCtorInitializer *Init = MemInits[i]; 5515 5516 // Set the source order index. 5517 Init->setSourceOrder(i); 5518 5519 if (Init->isAnyMemberInitializer()) { 5520 const void *Key = GetKeyForMember(Context, Init); 5521 if (CheckRedundantInit(*this, Init, Members[Key]) || 5522 CheckRedundantUnionInit(*this, Init, MemberUnions)) 5523 HadError = true; 5524 } else if (Init->isBaseInitializer()) { 5525 const void *Key = GetKeyForMember(Context, Init); 5526 if (CheckRedundantInit(*this, Init, Members[Key])) 5527 HadError = true; 5528 } else { 5529 assert(Init->isDelegatingInitializer()); 5530 // This must be the only initializer 5531 if (MemInits.size() != 1) { 5532 Diag(Init->getSourceLocation(), 5533 diag::err_delegating_initializer_alone) 5534 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 5535 // We will treat this as being the only initializer. 5536 } 5537 SetDelegatingInitializer(Constructor, MemInits[i]); 5538 // Return immediately as the initializer is set. 5539 return; 5540 } 5541 } 5542 5543 if (HadError) 5544 return; 5545 5546 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 5547 5548 SetCtorInitializers(Constructor, AnyErrors, MemInits); 5549 5550 DiagnoseUninitializedFields(*this, Constructor); 5551 } 5552 5553 void 5554 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 5555 CXXRecordDecl *ClassDecl) { 5556 // Ignore dependent contexts. Also ignore unions, since their members never 5557 // have destructors implicitly called. 5558 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 5559 return; 5560 5561 // FIXME: all the access-control diagnostics are positioned on the 5562 // field/base declaration. That's probably good; that said, the 5563 // user might reasonably want to know why the destructor is being 5564 // emitted, and we currently don't say. 5565 5566 // Non-static data members. 5567 for (auto *Field : ClassDecl->fields()) { 5568 if (Field->isInvalidDecl()) 5569 continue; 5570 5571 // Don't destroy incomplete or zero-length arrays. 5572 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 5573 continue; 5574 5575 QualType FieldType = Context.getBaseElementType(Field->getType()); 5576 5577 const RecordType* RT = FieldType->getAs<RecordType>(); 5578 if (!RT) 5579 continue; 5580 5581 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5582 if (FieldClassDecl->isInvalidDecl()) 5583 continue; 5584 if (FieldClassDecl->hasIrrelevantDestructor()) 5585 continue; 5586 // The destructor for an implicit anonymous union member is never invoked. 5587 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 5588 continue; 5589 5590 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 5591 assert(Dtor && "No dtor found for FieldClassDecl!"); 5592 CheckDestructorAccess(Field->getLocation(), Dtor, 5593 PDiag(diag::err_access_dtor_field) 5594 << Field->getDeclName() 5595 << FieldType); 5596 5597 MarkFunctionReferenced(Location, Dtor); 5598 DiagnoseUseOfDecl(Dtor, Location); 5599 } 5600 5601 // We only potentially invoke the destructors of potentially constructed 5602 // subobjects. 5603 bool VisitVirtualBases = !ClassDecl->isAbstract(); 5604 5605 // If the destructor exists and has already been marked used in the MS ABI, 5606 // then virtual base destructors have already been checked and marked used. 5607 // Skip checking them again to avoid duplicate diagnostics. 5608 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 5609 CXXDestructorDecl *Dtor = ClassDecl->getDestructor(); 5610 if (Dtor && Dtor->isUsed()) 5611 VisitVirtualBases = false; 5612 } 5613 5614 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 5615 5616 // Bases. 5617 for (const auto &Base : ClassDecl->bases()) { 5618 const RecordType *RT = Base.getType()->getAs<RecordType>(); 5619 if (!RT) 5620 continue; 5621 5622 // Remember direct virtual bases. 5623 if (Base.isVirtual()) { 5624 if (!VisitVirtualBases) 5625 continue; 5626 DirectVirtualBases.insert(RT); 5627 } 5628 5629 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5630 // If our base class is invalid, we probably can't get its dtor anyway. 5631 if (BaseClassDecl->isInvalidDecl()) 5632 continue; 5633 if (BaseClassDecl->hasIrrelevantDestructor()) 5634 continue; 5635 5636 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5637 assert(Dtor && "No dtor found for BaseClassDecl!"); 5638 5639 // FIXME: caret should be on the start of the class name 5640 CheckDestructorAccess(Base.getBeginLoc(), Dtor, 5641 PDiag(diag::err_access_dtor_base) 5642 << Base.getType() << Base.getSourceRange(), 5643 Context.getTypeDeclType(ClassDecl)); 5644 5645 MarkFunctionReferenced(Location, Dtor); 5646 DiagnoseUseOfDecl(Dtor, Location); 5647 } 5648 5649 if (VisitVirtualBases) 5650 MarkVirtualBaseDestructorsReferenced(Location, ClassDecl, 5651 &DirectVirtualBases); 5652 } 5653 5654 void Sema::MarkVirtualBaseDestructorsReferenced( 5655 SourceLocation Location, CXXRecordDecl *ClassDecl, 5656 llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) { 5657 // Virtual bases. 5658 for (const auto &VBase : ClassDecl->vbases()) { 5659 // Bases are always records in a well-formed non-dependent class. 5660 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 5661 5662 // Ignore already visited direct virtual bases. 5663 if (DirectVirtualBases && DirectVirtualBases->count(RT)) 5664 continue; 5665 5666 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5667 // If our base class is invalid, we probably can't get its dtor anyway. 5668 if (BaseClassDecl->isInvalidDecl()) 5669 continue; 5670 if (BaseClassDecl->hasIrrelevantDestructor()) 5671 continue; 5672 5673 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5674 assert(Dtor && "No dtor found for BaseClassDecl!"); 5675 if (CheckDestructorAccess( 5676 ClassDecl->getLocation(), Dtor, 5677 PDiag(diag::err_access_dtor_vbase) 5678 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 5679 Context.getTypeDeclType(ClassDecl)) == 5680 AR_accessible) { 5681 CheckDerivedToBaseConversion( 5682 Context.getTypeDeclType(ClassDecl), VBase.getType(), 5683 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 5684 SourceRange(), DeclarationName(), nullptr); 5685 } 5686 5687 MarkFunctionReferenced(Location, Dtor); 5688 DiagnoseUseOfDecl(Dtor, Location); 5689 } 5690 } 5691 5692 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 5693 if (!CDtorDecl) 5694 return; 5695 5696 if (CXXConstructorDecl *Constructor 5697 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 5698 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 5699 DiagnoseUninitializedFields(*this, Constructor); 5700 } 5701 } 5702 5703 bool Sema::isAbstractType(SourceLocation Loc, QualType T) { 5704 if (!getLangOpts().CPlusPlus) 5705 return false; 5706 5707 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl(); 5708 if (!RD) 5709 return false; 5710 5711 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a 5712 // class template specialization here, but doing so breaks a lot of code. 5713 5714 // We can't answer whether something is abstract until it has a 5715 // definition. If it's currently being defined, we'll walk back 5716 // over all the declarations when we have a full definition. 5717 const CXXRecordDecl *Def = RD->getDefinition(); 5718 if (!Def || Def->isBeingDefined()) 5719 return false; 5720 5721 return RD->isAbstract(); 5722 } 5723 5724 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 5725 TypeDiagnoser &Diagnoser) { 5726 if (!isAbstractType(Loc, T)) 5727 return false; 5728 5729 T = Context.getBaseElementType(T); 5730 Diagnoser.diagnose(*this, Loc, T); 5731 DiagnoseAbstractType(T->getAsCXXRecordDecl()); 5732 return true; 5733 } 5734 5735 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 5736 // Check if we've already emitted the list of pure virtual functions 5737 // for this class. 5738 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 5739 return; 5740 5741 // If the diagnostic is suppressed, don't emit the notes. We're only 5742 // going to emit them once, so try to attach them to a diagnostic we're 5743 // actually going to show. 5744 if (Diags.isLastDiagnosticIgnored()) 5745 return; 5746 5747 CXXFinalOverriderMap FinalOverriders; 5748 RD->getFinalOverriders(FinalOverriders); 5749 5750 // Keep a set of seen pure methods so we won't diagnose the same method 5751 // more than once. 5752 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 5753 5754 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 5755 MEnd = FinalOverriders.end(); 5756 M != MEnd; 5757 ++M) { 5758 for (OverridingMethods::iterator SO = M->second.begin(), 5759 SOEnd = M->second.end(); 5760 SO != SOEnd; ++SO) { 5761 // C++ [class.abstract]p4: 5762 // A class is abstract if it contains or inherits at least one 5763 // pure virtual function for which the final overrider is pure 5764 // virtual. 5765 5766 // 5767 if (SO->second.size() != 1) 5768 continue; 5769 5770 if (!SO->second.front().Method->isPure()) 5771 continue; 5772 5773 if (!SeenPureMethods.insert(SO->second.front().Method).second) 5774 continue; 5775 5776 Diag(SO->second.front().Method->getLocation(), 5777 diag::note_pure_virtual_function) 5778 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 5779 } 5780 } 5781 5782 if (!PureVirtualClassDiagSet) 5783 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 5784 PureVirtualClassDiagSet->insert(RD); 5785 } 5786 5787 namespace { 5788 struct AbstractUsageInfo { 5789 Sema &S; 5790 CXXRecordDecl *Record; 5791 CanQualType AbstractType; 5792 bool Invalid; 5793 5794 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 5795 : S(S), Record(Record), 5796 AbstractType(S.Context.getCanonicalType( 5797 S.Context.getTypeDeclType(Record))), 5798 Invalid(false) {} 5799 5800 void DiagnoseAbstractType() { 5801 if (Invalid) return; 5802 S.DiagnoseAbstractType(Record); 5803 Invalid = true; 5804 } 5805 5806 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 5807 }; 5808 5809 struct CheckAbstractUsage { 5810 AbstractUsageInfo &Info; 5811 const NamedDecl *Ctx; 5812 5813 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 5814 : Info(Info), Ctx(Ctx) {} 5815 5816 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5817 switch (TL.getTypeLocClass()) { 5818 #define ABSTRACT_TYPELOC(CLASS, PARENT) 5819 #define TYPELOC(CLASS, PARENT) \ 5820 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 5821 #include "clang/AST/TypeLocNodes.def" 5822 } 5823 } 5824 5825 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5826 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 5827 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 5828 if (!TL.getParam(I)) 5829 continue; 5830 5831 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 5832 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 5833 } 5834 } 5835 5836 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5837 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 5838 } 5839 5840 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5841 // Visit the type parameters from a permissive context. 5842 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 5843 TemplateArgumentLoc TAL = TL.getArgLoc(I); 5844 if (TAL.getArgument().getKind() == TemplateArgument::Type) 5845 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 5846 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 5847 // TODO: other template argument types? 5848 } 5849 } 5850 5851 // Visit pointee types from a permissive context. 5852 #define CheckPolymorphic(Type) \ 5853 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 5854 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 5855 } 5856 CheckPolymorphic(PointerTypeLoc) 5857 CheckPolymorphic(ReferenceTypeLoc) 5858 CheckPolymorphic(MemberPointerTypeLoc) 5859 CheckPolymorphic(BlockPointerTypeLoc) 5860 CheckPolymorphic(AtomicTypeLoc) 5861 5862 /// Handle all the types we haven't given a more specific 5863 /// implementation for above. 5864 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5865 // Every other kind of type that we haven't called out already 5866 // that has an inner type is either (1) sugar or (2) contains that 5867 // inner type in some way as a subobject. 5868 if (TypeLoc Next = TL.getNextTypeLoc()) 5869 return Visit(Next, Sel); 5870 5871 // If there's no inner type and we're in a permissive context, 5872 // don't diagnose. 5873 if (Sel == Sema::AbstractNone) return; 5874 5875 // Check whether the type matches the abstract type. 5876 QualType T = TL.getType(); 5877 if (T->isArrayType()) { 5878 Sel = Sema::AbstractArrayType; 5879 T = Info.S.Context.getBaseElementType(T); 5880 } 5881 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 5882 if (CT != Info.AbstractType) return; 5883 5884 // It matched; do some magic. 5885 if (Sel == Sema::AbstractArrayType) { 5886 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 5887 << T << TL.getSourceRange(); 5888 } else { 5889 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 5890 << Sel << T << TL.getSourceRange(); 5891 } 5892 Info.DiagnoseAbstractType(); 5893 } 5894 }; 5895 5896 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 5897 Sema::AbstractDiagSelID Sel) { 5898 CheckAbstractUsage(*this, D).Visit(TL, Sel); 5899 } 5900 5901 } 5902 5903 /// Check for invalid uses of an abstract type in a method declaration. 5904 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5905 CXXMethodDecl *MD) { 5906 // No need to do the check on definitions, which require that 5907 // the return/param types be complete. 5908 if (MD->doesThisDeclarationHaveABody()) 5909 return; 5910 5911 // For safety's sake, just ignore it if we don't have type source 5912 // information. This should never happen for non-implicit methods, 5913 // but... 5914 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 5915 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 5916 } 5917 5918 /// Check for invalid uses of an abstract type within a class definition. 5919 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5920 CXXRecordDecl *RD) { 5921 for (auto *D : RD->decls()) { 5922 if (D->isImplicit()) continue; 5923 5924 // Methods and method templates. 5925 if (isa<CXXMethodDecl>(D)) { 5926 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 5927 } else if (isa<FunctionTemplateDecl>(D)) { 5928 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 5929 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 5930 5931 // Fields and static variables. 5932 } else if (isa<FieldDecl>(D)) { 5933 FieldDecl *FD = cast<FieldDecl>(D); 5934 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 5935 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 5936 } else if (isa<VarDecl>(D)) { 5937 VarDecl *VD = cast<VarDecl>(D); 5938 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 5939 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 5940 5941 // Nested classes and class templates. 5942 } else if (isa<CXXRecordDecl>(D)) { 5943 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 5944 } else if (isa<ClassTemplateDecl>(D)) { 5945 CheckAbstractClassUsage(Info, 5946 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 5947 } 5948 } 5949 } 5950 5951 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) { 5952 Attr *ClassAttr = getDLLAttr(Class); 5953 if (!ClassAttr) 5954 return; 5955 5956 assert(ClassAttr->getKind() == attr::DLLExport); 5957 5958 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5959 5960 if (TSK == TSK_ExplicitInstantiationDeclaration) 5961 // Don't go any further if this is just an explicit instantiation 5962 // declaration. 5963 return; 5964 5965 // Add a context note to explain how we got to any diagnostics produced below. 5966 struct MarkingClassDllexported { 5967 Sema &S; 5968 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class, 5969 SourceLocation AttrLoc) 5970 : S(S) { 5971 Sema::CodeSynthesisContext Ctx; 5972 Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported; 5973 Ctx.PointOfInstantiation = AttrLoc; 5974 Ctx.Entity = Class; 5975 S.pushCodeSynthesisContext(Ctx); 5976 } 5977 ~MarkingClassDllexported() { 5978 S.popCodeSynthesisContext(); 5979 } 5980 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation()); 5981 5982 if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) 5983 S.MarkVTableUsed(Class->getLocation(), Class, true); 5984 5985 for (Decl *Member : Class->decls()) { 5986 // Skip members that were not marked exported. 5987 if (!Member->hasAttr<DLLExportAttr>()) 5988 continue; 5989 5990 // Defined static variables that are members of an exported base 5991 // class must be marked export too. 5992 auto *VD = dyn_cast<VarDecl>(Member); 5993 if (VD && VD->getStorageClass() == SC_Static && 5994 TSK == TSK_ImplicitInstantiation) 5995 S.MarkVariableReferenced(VD->getLocation(), VD); 5996 5997 auto *MD = dyn_cast<CXXMethodDecl>(Member); 5998 if (!MD) 5999 continue; 6000 6001 if (MD->isUserProvided()) { 6002 // Instantiate non-default class member functions ... 6003 6004 // .. except for certain kinds of template specializations. 6005 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 6006 continue; 6007 6008 S.MarkFunctionReferenced(Class->getLocation(), MD); 6009 6010 // The function will be passed to the consumer when its definition is 6011 // encountered. 6012 } else if (MD->isExplicitlyDefaulted()) { 6013 // Synthesize and instantiate explicitly defaulted methods. 6014 S.MarkFunctionReferenced(Class->getLocation(), MD); 6015 6016 if (TSK != TSK_ExplicitInstantiationDefinition) { 6017 // Except for explicit instantiation defs, we will not see the 6018 // definition again later, so pass it to the consumer now. 6019 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 6020 } 6021 } else if (!MD->isTrivial() || 6022 MD->isCopyAssignmentOperator() || 6023 MD->isMoveAssignmentOperator()) { 6024 // Synthesize and instantiate non-trivial implicit methods, and the copy 6025 // and move assignment operators. The latter are exported even if they 6026 // are trivial, because the address of an operator can be taken and 6027 // should compare equal across libraries. 6028 S.MarkFunctionReferenced(Class->getLocation(), MD); 6029 6030 // There is no later point when we will see the definition of this 6031 // function, so pass it to the consumer now. 6032 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 6033 } 6034 } 6035 } 6036 6037 static void checkForMultipleExportedDefaultConstructors(Sema &S, 6038 CXXRecordDecl *Class) { 6039 // Only the MS ABI has default constructor closures, so we don't need to do 6040 // this semantic checking anywhere else. 6041 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft()) 6042 return; 6043 6044 CXXConstructorDecl *LastExportedDefaultCtor = nullptr; 6045 for (Decl *Member : Class->decls()) { 6046 // Look for exported default constructors. 6047 auto *CD = dyn_cast<CXXConstructorDecl>(Member); 6048 if (!CD || !CD->isDefaultConstructor()) 6049 continue; 6050 auto *Attr = CD->getAttr<DLLExportAttr>(); 6051 if (!Attr) 6052 continue; 6053 6054 // If the class is non-dependent, mark the default arguments as ODR-used so 6055 // that we can properly codegen the constructor closure. 6056 if (!Class->isDependentContext()) { 6057 for (ParmVarDecl *PD : CD->parameters()) { 6058 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD); 6059 S.DiscardCleanupsInEvaluationContext(); 6060 } 6061 } 6062 6063 if (LastExportedDefaultCtor) { 6064 S.Diag(LastExportedDefaultCtor->getLocation(), 6065 diag::err_attribute_dll_ambiguous_default_ctor) 6066 << Class; 6067 S.Diag(CD->getLocation(), diag::note_entity_declared_at) 6068 << CD->getDeclName(); 6069 return; 6070 } 6071 LastExportedDefaultCtor = CD; 6072 } 6073 } 6074 6075 static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S, 6076 CXXRecordDecl *Class) { 6077 bool ErrorReported = false; 6078 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S, 6079 ClassTemplateDecl *TD) { 6080 if (ErrorReported) 6081 return; 6082 S.Diag(TD->getLocation(), 6083 diag::err_cuda_device_builtin_surftex_cls_template) 6084 << /*surface*/ 0 << TD; 6085 ErrorReported = true; 6086 }; 6087 6088 ClassTemplateDecl *TD = Class->getDescribedClassTemplate(); 6089 if (!TD) { 6090 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class); 6091 if (!SD) { 6092 S.Diag(Class->getLocation(), 6093 diag::err_cuda_device_builtin_surftex_ref_decl) 6094 << /*surface*/ 0 << Class; 6095 S.Diag(Class->getLocation(), 6096 diag::note_cuda_device_builtin_surftex_should_be_template_class) 6097 << Class; 6098 return; 6099 } 6100 TD = SD->getSpecializedTemplate(); 6101 } 6102 6103 TemplateParameterList *Params = TD->getTemplateParameters(); 6104 unsigned N = Params->size(); 6105 6106 if (N != 2) { 6107 reportIllegalClassTemplate(S, TD); 6108 S.Diag(TD->getLocation(), 6109 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args) 6110 << TD << 2; 6111 } 6112 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 6113 reportIllegalClassTemplate(S, TD); 6114 S.Diag(TD->getLocation(), 6115 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6116 << TD << /*1st*/ 0 << /*type*/ 0; 6117 } 6118 if (N > 1) { 6119 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 6120 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 6121 reportIllegalClassTemplate(S, TD); 6122 S.Diag(TD->getLocation(), 6123 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6124 << TD << /*2nd*/ 1 << /*integer*/ 1; 6125 } 6126 } 6127 } 6128 6129 static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S, 6130 CXXRecordDecl *Class) { 6131 bool ErrorReported = false; 6132 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S, 6133 ClassTemplateDecl *TD) { 6134 if (ErrorReported) 6135 return; 6136 S.Diag(TD->getLocation(), 6137 diag::err_cuda_device_builtin_surftex_cls_template) 6138 << /*texture*/ 1 << TD; 6139 ErrorReported = true; 6140 }; 6141 6142 ClassTemplateDecl *TD = Class->getDescribedClassTemplate(); 6143 if (!TD) { 6144 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class); 6145 if (!SD) { 6146 S.Diag(Class->getLocation(), 6147 diag::err_cuda_device_builtin_surftex_ref_decl) 6148 << /*texture*/ 1 << Class; 6149 S.Diag(Class->getLocation(), 6150 diag::note_cuda_device_builtin_surftex_should_be_template_class) 6151 << Class; 6152 return; 6153 } 6154 TD = SD->getSpecializedTemplate(); 6155 } 6156 6157 TemplateParameterList *Params = TD->getTemplateParameters(); 6158 unsigned N = Params->size(); 6159 6160 if (N != 3) { 6161 reportIllegalClassTemplate(S, TD); 6162 S.Diag(TD->getLocation(), 6163 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args) 6164 << TD << 3; 6165 } 6166 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 6167 reportIllegalClassTemplate(S, TD); 6168 S.Diag(TD->getLocation(), 6169 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6170 << TD << /*1st*/ 0 << /*type*/ 0; 6171 } 6172 if (N > 1) { 6173 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 6174 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 6175 reportIllegalClassTemplate(S, TD); 6176 S.Diag(TD->getLocation(), 6177 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6178 << TD << /*2nd*/ 1 << /*integer*/ 1; 6179 } 6180 } 6181 if (N > 2) { 6182 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2)); 6183 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 6184 reportIllegalClassTemplate(S, TD); 6185 S.Diag(TD->getLocation(), 6186 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6187 << TD << /*3rd*/ 2 << /*integer*/ 1; 6188 } 6189 } 6190 } 6191 6192 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) { 6193 // Mark any compiler-generated routines with the implicit code_seg attribute. 6194 for (auto *Method : Class->methods()) { 6195 if (Method->isUserProvided()) 6196 continue; 6197 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true)) 6198 Method->addAttr(A); 6199 } 6200 } 6201 6202 /// Check class-level dllimport/dllexport attribute. 6203 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) { 6204 Attr *ClassAttr = getDLLAttr(Class); 6205 6206 // MSVC inherits DLL attributes to partial class template specializations. 6207 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) { 6208 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 6209 if (Attr *TemplateAttr = 6210 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 6211 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext())); 6212 A->setInherited(true); 6213 ClassAttr = A; 6214 } 6215 } 6216 } 6217 6218 if (!ClassAttr) 6219 return; 6220 6221 if (!Class->isExternallyVisible()) { 6222 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) 6223 << Class << ClassAttr; 6224 return; 6225 } 6226 6227 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && 6228 !ClassAttr->isInherited()) { 6229 // Diagnose dll attributes on members of class with dll attribute. 6230 for (Decl *Member : Class->decls()) { 6231 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 6232 continue; 6233 InheritableAttr *MemberAttr = getDLLAttr(Member); 6234 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 6235 continue; 6236 6237 Diag(MemberAttr->getLocation(), 6238 diag::err_attribute_dll_member_of_dll_class) 6239 << MemberAttr << ClassAttr; 6240 Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 6241 Member->setInvalidDecl(); 6242 } 6243 } 6244 6245 if (Class->getDescribedClassTemplate()) 6246 // Don't inherit dll attribute until the template is instantiated. 6247 return; 6248 6249 // The class is either imported or exported. 6250 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 6251 6252 // Check if this was a dllimport attribute propagated from a derived class to 6253 // a base class template specialization. We don't apply these attributes to 6254 // static data members. 6255 const bool PropagatedImport = 6256 !ClassExported && 6257 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate(); 6258 6259 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 6260 6261 // Ignore explicit dllexport on explicit class template instantiation 6262 // declarations, except in MinGW mode. 6263 if (ClassExported && !ClassAttr->isInherited() && 6264 TSK == TSK_ExplicitInstantiationDeclaration && 6265 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) { 6266 Class->dropAttr<DLLExportAttr>(); 6267 return; 6268 } 6269 6270 // Force declaration of implicit members so they can inherit the attribute. 6271 ForceDeclarationOfImplicitMembers(Class); 6272 6273 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 6274 // seem to be true in practice? 6275 6276 for (Decl *Member : Class->decls()) { 6277 VarDecl *VD = dyn_cast<VarDecl>(Member); 6278 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 6279 6280 // Only methods and static fields inherit the attributes. 6281 if (!VD && !MD) 6282 continue; 6283 6284 if (MD) { 6285 // Don't process deleted methods. 6286 if (MD->isDeleted()) 6287 continue; 6288 6289 if (MD->isInlined()) { 6290 // MinGW does not import or export inline methods. But do it for 6291 // template instantiations. 6292 if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() && 6293 TSK != TSK_ExplicitInstantiationDeclaration && 6294 TSK != TSK_ExplicitInstantiationDefinition) 6295 continue; 6296 6297 // MSVC versions before 2015 don't export the move assignment operators 6298 // and move constructor, so don't attempt to import/export them if 6299 // we have a definition. 6300 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD); 6301 if ((MD->isMoveAssignmentOperator() || 6302 (Ctor && Ctor->isMoveConstructor())) && 6303 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015)) 6304 continue; 6305 6306 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign 6307 // operator is exported anyway. 6308 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 6309 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial()) 6310 continue; 6311 } 6312 } 6313 6314 // Don't apply dllimport attributes to static data members of class template 6315 // instantiations when the attribute is propagated from a derived class. 6316 if (VD && PropagatedImport) 6317 continue; 6318 6319 if (!cast<NamedDecl>(Member)->isExternallyVisible()) 6320 continue; 6321 6322 if (!getDLLAttr(Member)) { 6323 InheritableAttr *NewAttr = nullptr; 6324 6325 // Do not export/import inline function when -fno-dllexport-inlines is 6326 // passed. But add attribute for later local static var check. 6327 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() && 6328 TSK != TSK_ExplicitInstantiationDeclaration && 6329 TSK != TSK_ExplicitInstantiationDefinition) { 6330 if (ClassExported) { 6331 NewAttr = ::new (getASTContext()) 6332 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr); 6333 } else { 6334 NewAttr = ::new (getASTContext()) 6335 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr); 6336 } 6337 } else { 6338 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6339 } 6340 6341 NewAttr->setInherited(true); 6342 Member->addAttr(NewAttr); 6343 6344 if (MD) { 6345 // Propagate DLLAttr to friend re-declarations of MD that have already 6346 // been constructed. 6347 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD; 6348 FD = FD->getPreviousDecl()) { 6349 if (FD->getFriendObjectKind() == Decl::FOK_None) 6350 continue; 6351 assert(!getDLLAttr(FD) && 6352 "friend re-decl should not already have a DLLAttr"); 6353 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6354 NewAttr->setInherited(true); 6355 FD->addAttr(NewAttr); 6356 } 6357 } 6358 } 6359 } 6360 6361 if (ClassExported) 6362 DelayedDllExportClasses.push_back(Class); 6363 } 6364 6365 /// Perform propagation of DLL attributes from a derived class to a 6366 /// templated base class for MS compatibility. 6367 void Sema::propagateDLLAttrToBaseClassTemplate( 6368 CXXRecordDecl *Class, Attr *ClassAttr, 6369 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 6370 if (getDLLAttr( 6371 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 6372 // If the base class template has a DLL attribute, don't try to change it. 6373 return; 6374 } 6375 6376 auto TSK = BaseTemplateSpec->getSpecializationKind(); 6377 if (!getDLLAttr(BaseTemplateSpec) && 6378 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration || 6379 TSK == TSK_ImplicitInstantiation)) { 6380 // The template hasn't been instantiated yet (or it has, but only as an 6381 // explicit instantiation declaration or implicit instantiation, which means 6382 // we haven't codegenned any members yet), so propagate the attribute. 6383 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6384 NewAttr->setInherited(true); 6385 BaseTemplateSpec->addAttr(NewAttr); 6386 6387 // If this was an import, mark that we propagated it from a derived class to 6388 // a base class template specialization. 6389 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr)) 6390 ImportAttr->setPropagatedToBaseTemplate(); 6391 6392 // If the template is already instantiated, checkDLLAttributeRedeclaration() 6393 // needs to be run again to work see the new attribute. Otherwise this will 6394 // get run whenever the template is instantiated. 6395 if (TSK != TSK_Undeclared) 6396 checkClassLevelDLLAttribute(BaseTemplateSpec); 6397 6398 return; 6399 } 6400 6401 if (getDLLAttr(BaseTemplateSpec)) { 6402 // The template has already been specialized or instantiated with an 6403 // attribute, explicitly or through propagation. We should not try to change 6404 // it. 6405 return; 6406 } 6407 6408 // The template was previously instantiated or explicitly specialized without 6409 // a dll attribute, It's too late for us to add an attribute, so warn that 6410 // this is unsupported. 6411 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 6412 << BaseTemplateSpec->isExplicitSpecialization(); 6413 Diag(ClassAttr->getLocation(), diag::note_attribute); 6414 if (BaseTemplateSpec->isExplicitSpecialization()) { 6415 Diag(BaseTemplateSpec->getLocation(), 6416 diag::note_template_class_explicit_specialization_was_here) 6417 << BaseTemplateSpec; 6418 } else { 6419 Diag(BaseTemplateSpec->getPointOfInstantiation(), 6420 diag::note_template_class_instantiation_was_here) 6421 << BaseTemplateSpec; 6422 } 6423 } 6424 6425 /// Determine the kind of defaulting that would be done for a given function. 6426 /// 6427 /// If the function is both a default constructor and a copy / move constructor 6428 /// (due to having a default argument for the first parameter), this picks 6429 /// CXXDefaultConstructor. 6430 /// 6431 /// FIXME: Check that case is properly handled by all callers. 6432 Sema::DefaultedFunctionKind 6433 Sema::getDefaultedFunctionKind(const FunctionDecl *FD) { 6434 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 6435 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 6436 if (Ctor->isDefaultConstructor()) 6437 return Sema::CXXDefaultConstructor; 6438 6439 if (Ctor->isCopyConstructor()) 6440 return Sema::CXXCopyConstructor; 6441 6442 if (Ctor->isMoveConstructor()) 6443 return Sema::CXXMoveConstructor; 6444 } 6445 6446 if (MD->isCopyAssignmentOperator()) 6447 return Sema::CXXCopyAssignment; 6448 6449 if (MD->isMoveAssignmentOperator()) 6450 return Sema::CXXMoveAssignment; 6451 6452 if (isa<CXXDestructorDecl>(FD)) 6453 return Sema::CXXDestructor; 6454 } 6455 6456 switch (FD->getDeclName().getCXXOverloadedOperator()) { 6457 case OO_EqualEqual: 6458 return DefaultedComparisonKind::Equal; 6459 6460 case OO_ExclaimEqual: 6461 return DefaultedComparisonKind::NotEqual; 6462 6463 case OO_Spaceship: 6464 // No point allowing this if <=> doesn't exist in the current language mode. 6465 if (!getLangOpts().CPlusPlus20) 6466 break; 6467 return DefaultedComparisonKind::ThreeWay; 6468 6469 case OO_Less: 6470 case OO_LessEqual: 6471 case OO_Greater: 6472 case OO_GreaterEqual: 6473 // No point allowing this if <=> doesn't exist in the current language mode. 6474 if (!getLangOpts().CPlusPlus20) 6475 break; 6476 return DefaultedComparisonKind::Relational; 6477 6478 default: 6479 break; 6480 } 6481 6482 // Not defaultable. 6483 return DefaultedFunctionKind(); 6484 } 6485 6486 static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD, 6487 SourceLocation DefaultLoc) { 6488 Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD); 6489 if (DFK.isComparison()) 6490 return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison()); 6491 6492 switch (DFK.asSpecialMember()) { 6493 case Sema::CXXDefaultConstructor: 6494 S.DefineImplicitDefaultConstructor(DefaultLoc, 6495 cast<CXXConstructorDecl>(FD)); 6496 break; 6497 case Sema::CXXCopyConstructor: 6498 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD)); 6499 break; 6500 case Sema::CXXCopyAssignment: 6501 S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD)); 6502 break; 6503 case Sema::CXXDestructor: 6504 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD)); 6505 break; 6506 case Sema::CXXMoveConstructor: 6507 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD)); 6508 break; 6509 case Sema::CXXMoveAssignment: 6510 S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD)); 6511 break; 6512 case Sema::CXXInvalid: 6513 llvm_unreachable("Invalid special member."); 6514 } 6515 } 6516 6517 /// Determine whether a type is permitted to be passed or returned in 6518 /// registers, per C++ [class.temporary]p3. 6519 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D, 6520 TargetInfo::CallingConvKind CCK) { 6521 if (D->isDependentType() || D->isInvalidDecl()) 6522 return false; 6523 6524 // Clang <= 4 used the pre-C++11 rule, which ignores move operations. 6525 // The PS4 platform ABI follows the behavior of Clang 3.2. 6526 if (CCK == TargetInfo::CCK_ClangABI4OrPS4) 6527 return !D->hasNonTrivialDestructorForCall() && 6528 !D->hasNonTrivialCopyConstructorForCall(); 6529 6530 if (CCK == TargetInfo::CCK_MicrosoftWin64) { 6531 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false; 6532 bool DtorIsTrivialForCall = false; 6533 6534 // If a class has at least one non-deleted, trivial copy constructor, it 6535 // is passed according to the C ABI. Otherwise, it is passed indirectly. 6536 // 6537 // Note: This permits classes with non-trivial copy or move ctors to be 6538 // passed in registers, so long as they *also* have a trivial copy ctor, 6539 // which is non-conforming. 6540 if (D->needsImplicitCopyConstructor()) { 6541 if (!D->defaultedCopyConstructorIsDeleted()) { 6542 if (D->hasTrivialCopyConstructor()) 6543 CopyCtorIsTrivial = true; 6544 if (D->hasTrivialCopyConstructorForCall()) 6545 CopyCtorIsTrivialForCall = true; 6546 } 6547 } else { 6548 for (const CXXConstructorDecl *CD : D->ctors()) { 6549 if (CD->isCopyConstructor() && !CD->isDeleted()) { 6550 if (CD->isTrivial()) 6551 CopyCtorIsTrivial = true; 6552 if (CD->isTrivialForCall()) 6553 CopyCtorIsTrivialForCall = true; 6554 } 6555 } 6556 } 6557 6558 if (D->needsImplicitDestructor()) { 6559 if (!D->defaultedDestructorIsDeleted() && 6560 D->hasTrivialDestructorForCall()) 6561 DtorIsTrivialForCall = true; 6562 } else if (const auto *DD = D->getDestructor()) { 6563 if (!DD->isDeleted() && DD->isTrivialForCall()) 6564 DtorIsTrivialForCall = true; 6565 } 6566 6567 // If the copy ctor and dtor are both trivial-for-calls, pass direct. 6568 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall) 6569 return true; 6570 6571 // If a class has a destructor, we'd really like to pass it indirectly 6572 // because it allows us to elide copies. Unfortunately, MSVC makes that 6573 // impossible for small types, which it will pass in a single register or 6574 // stack slot. Most objects with dtors are large-ish, so handle that early. 6575 // We can't call out all large objects as being indirect because there are 6576 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate 6577 // how we pass large POD types. 6578 6579 // Note: This permits small classes with nontrivial destructors to be 6580 // passed in registers, which is non-conforming. 6581 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64(); 6582 uint64_t TypeSize = isAArch64 ? 128 : 64; 6583 6584 if (CopyCtorIsTrivial && 6585 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize) 6586 return true; 6587 return false; 6588 } 6589 6590 // Per C++ [class.temporary]p3, the relevant condition is: 6591 // each copy constructor, move constructor, and destructor of X is 6592 // either trivial or deleted, and X has at least one non-deleted copy 6593 // or move constructor 6594 bool HasNonDeletedCopyOrMove = false; 6595 6596 if (D->needsImplicitCopyConstructor() && 6597 !D->defaultedCopyConstructorIsDeleted()) { 6598 if (!D->hasTrivialCopyConstructorForCall()) 6599 return false; 6600 HasNonDeletedCopyOrMove = true; 6601 } 6602 6603 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() && 6604 !D->defaultedMoveConstructorIsDeleted()) { 6605 if (!D->hasTrivialMoveConstructorForCall()) 6606 return false; 6607 HasNonDeletedCopyOrMove = true; 6608 } 6609 6610 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() && 6611 !D->hasTrivialDestructorForCall()) 6612 return false; 6613 6614 for (const CXXMethodDecl *MD : D->methods()) { 6615 if (MD->isDeleted()) 6616 continue; 6617 6618 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 6619 if (CD && CD->isCopyOrMoveConstructor()) 6620 HasNonDeletedCopyOrMove = true; 6621 else if (!isa<CXXDestructorDecl>(MD)) 6622 continue; 6623 6624 if (!MD->isTrivialForCall()) 6625 return false; 6626 } 6627 6628 return HasNonDeletedCopyOrMove; 6629 } 6630 6631 /// Report an error regarding overriding, along with any relevant 6632 /// overridden methods. 6633 /// 6634 /// \param DiagID the primary error to report. 6635 /// \param MD the overriding method. 6636 static bool 6637 ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD, 6638 llvm::function_ref<bool(const CXXMethodDecl *)> Report) { 6639 bool IssuedDiagnostic = false; 6640 for (const CXXMethodDecl *O : MD->overridden_methods()) { 6641 if (Report(O)) { 6642 if (!IssuedDiagnostic) { 6643 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 6644 IssuedDiagnostic = true; 6645 } 6646 S.Diag(O->getLocation(), diag::note_overridden_virtual_function); 6647 } 6648 } 6649 return IssuedDiagnostic; 6650 } 6651 6652 /// Perform semantic checks on a class definition that has been 6653 /// completing, introducing implicitly-declared members, checking for 6654 /// abstract types, etc. 6655 /// 6656 /// \param S The scope in which the class was parsed. Null if we didn't just 6657 /// parse a class definition. 6658 /// \param Record The completed class. 6659 void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) { 6660 if (!Record) 6661 return; 6662 6663 if (Record->isAbstract() && !Record->isInvalidDecl()) { 6664 AbstractUsageInfo Info(*this, Record); 6665 CheckAbstractClassUsage(Info, Record); 6666 } 6667 6668 // If this is not an aggregate type and has no user-declared constructor, 6669 // complain about any non-static data members of reference or const scalar 6670 // type, since they will never get initializers. 6671 if (!Record->isInvalidDecl() && !Record->isDependentType() && 6672 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 6673 !Record->isLambda()) { 6674 bool Complained = false; 6675 for (const auto *F : Record->fields()) { 6676 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 6677 continue; 6678 6679 if (F->getType()->isReferenceType() || 6680 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 6681 if (!Complained) { 6682 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 6683 << Record->getTagKind() << Record; 6684 Complained = true; 6685 } 6686 6687 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 6688 << F->getType()->isReferenceType() 6689 << F->getDeclName(); 6690 } 6691 } 6692 } 6693 6694 if (Record->getIdentifier()) { 6695 // C++ [class.mem]p13: 6696 // If T is the name of a class, then each of the following shall have a 6697 // name different from T: 6698 // - every member of every anonymous union that is a member of class T. 6699 // 6700 // C++ [class.mem]p14: 6701 // In addition, if class T has a user-declared constructor (12.1), every 6702 // non-static data member of class T shall have a name different from T. 6703 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 6704 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 6705 ++I) { 6706 NamedDecl *D = (*I)->getUnderlyingDecl(); 6707 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) && 6708 Record->hasUserDeclaredConstructor()) || 6709 isa<IndirectFieldDecl>(D)) { 6710 Diag((*I)->getLocation(), diag::err_member_name_of_class) 6711 << D->getDeclName(); 6712 break; 6713 } 6714 } 6715 } 6716 6717 // Warn if the class has virtual methods but non-virtual public destructor. 6718 if (Record->isPolymorphic() && !Record->isDependentType()) { 6719 CXXDestructorDecl *dtor = Record->getDestructor(); 6720 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 6721 !Record->hasAttr<FinalAttr>()) 6722 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 6723 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 6724 } 6725 6726 if (Record->isAbstract()) { 6727 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 6728 Diag(Record->getLocation(), diag::warn_abstract_final_class) 6729 << FA->isSpelledAsSealed(); 6730 DiagnoseAbstractType(Record); 6731 } 6732 } 6733 6734 // Warn if the class has a final destructor but is not itself marked final. 6735 if (!Record->hasAttr<FinalAttr>()) { 6736 if (const CXXDestructorDecl *dtor = Record->getDestructor()) { 6737 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) { 6738 Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class) 6739 << FA->isSpelledAsSealed() 6740 << FixItHint::CreateInsertion( 6741 getLocForEndOfToken(Record->getLocation()), 6742 (FA->isSpelledAsSealed() ? " sealed" : " final")); 6743 Diag(Record->getLocation(), 6744 diag::note_final_dtor_non_final_class_silence) 6745 << Context.getRecordType(Record) << FA->isSpelledAsSealed(); 6746 } 6747 } 6748 } 6749 6750 // See if trivial_abi has to be dropped. 6751 if (Record->hasAttr<TrivialABIAttr>()) 6752 checkIllFormedTrivialABIStruct(*Record); 6753 6754 // Set HasTrivialSpecialMemberForCall if the record has attribute 6755 // "trivial_abi". 6756 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>(); 6757 6758 if (HasTrivialABI) 6759 Record->setHasTrivialSpecialMemberForCall(); 6760 6761 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=). 6762 // We check these last because they can depend on the properties of the 6763 // primary comparison functions (==, <=>). 6764 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons; 6765 6766 // Perform checks that can't be done until we know all the properties of a 6767 // member function (whether it's defaulted, deleted, virtual, overriding, 6768 // ...). 6769 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) { 6770 // A static function cannot override anything. 6771 if (MD->getStorageClass() == SC_Static) { 6772 if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD, 6773 [](const CXXMethodDecl *) { return true; })) 6774 return; 6775 } 6776 6777 // A deleted function cannot override a non-deleted function and vice 6778 // versa. 6779 if (ReportOverrides(*this, 6780 MD->isDeleted() ? diag::err_deleted_override 6781 : diag::err_non_deleted_override, 6782 MD, [&](const CXXMethodDecl *V) { 6783 return MD->isDeleted() != V->isDeleted(); 6784 })) { 6785 if (MD->isDefaulted() && MD->isDeleted()) 6786 // Explain why this defaulted function was deleted. 6787 DiagnoseDeletedDefaultedFunction(MD); 6788 return; 6789 } 6790 6791 // A consteval function cannot override a non-consteval function and vice 6792 // versa. 6793 if (ReportOverrides(*this, 6794 MD->isConsteval() ? diag::err_consteval_override 6795 : diag::err_non_consteval_override, 6796 MD, [&](const CXXMethodDecl *V) { 6797 return MD->isConsteval() != V->isConsteval(); 6798 })) { 6799 if (MD->isDefaulted() && MD->isDeleted()) 6800 // Explain why this defaulted function was deleted. 6801 DiagnoseDeletedDefaultedFunction(MD); 6802 return; 6803 } 6804 }; 6805 6806 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool { 6807 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted()) 6808 return false; 6809 6810 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD); 6811 if (DFK.asComparison() == DefaultedComparisonKind::NotEqual || 6812 DFK.asComparison() == DefaultedComparisonKind::Relational) { 6813 DefaultedSecondaryComparisons.push_back(FD); 6814 return true; 6815 } 6816 6817 CheckExplicitlyDefaultedFunction(S, FD); 6818 return false; 6819 }; 6820 6821 auto CompleteMemberFunction = [&](CXXMethodDecl *M) { 6822 // Check whether the explicitly-defaulted members are valid. 6823 bool Incomplete = CheckForDefaultedFunction(M); 6824 6825 // Skip the rest of the checks for a member of a dependent class. 6826 if (Record->isDependentType()) 6827 return; 6828 6829 // For an explicitly defaulted or deleted special member, we defer 6830 // determining triviality until the class is complete. That time is now! 6831 CXXSpecialMember CSM = getSpecialMember(M); 6832 if (!M->isImplicit() && !M->isUserProvided()) { 6833 if (CSM != CXXInvalid) { 6834 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 6835 // Inform the class that we've finished declaring this member. 6836 Record->finishedDefaultedOrDeletedMember(M); 6837 M->setTrivialForCall( 6838 HasTrivialABI || 6839 SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI)); 6840 Record->setTrivialForCallFlags(M); 6841 } 6842 } 6843 6844 // Set triviality for the purpose of calls if this is a user-provided 6845 // copy/move constructor or destructor. 6846 if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor || 6847 CSM == CXXDestructor) && M->isUserProvided()) { 6848 M->setTrivialForCall(HasTrivialABI); 6849 Record->setTrivialForCallFlags(M); 6850 } 6851 6852 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() && 6853 M->hasAttr<DLLExportAttr>()) { 6854 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 6855 M->isTrivial() && 6856 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor || 6857 CSM == CXXDestructor)) 6858 M->dropAttr<DLLExportAttr>(); 6859 6860 if (M->hasAttr<DLLExportAttr>()) { 6861 // Define after any fields with in-class initializers have been parsed. 6862 DelayedDllExportMemberFunctions.push_back(M); 6863 } 6864 } 6865 6866 // Define defaulted constexpr virtual functions that override a base class 6867 // function right away. 6868 // FIXME: We can defer doing this until the vtable is marked as used. 6869 if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods()) 6870 DefineDefaultedFunction(*this, M, M->getLocation()); 6871 6872 if (!Incomplete) 6873 CheckCompletedMemberFunction(M); 6874 }; 6875 6876 // Check the destructor before any other member function. We need to 6877 // determine whether it's trivial in order to determine whether the claas 6878 // type is a literal type, which is a prerequisite for determining whether 6879 // other special member functions are valid and whether they're implicitly 6880 // 'constexpr'. 6881 if (CXXDestructorDecl *Dtor = Record->getDestructor()) 6882 CompleteMemberFunction(Dtor); 6883 6884 bool HasMethodWithOverrideControl = false, 6885 HasOverridingMethodWithoutOverrideControl = false; 6886 for (auto *D : Record->decls()) { 6887 if (auto *M = dyn_cast<CXXMethodDecl>(D)) { 6888 // FIXME: We could do this check for dependent types with non-dependent 6889 // bases. 6890 if (!Record->isDependentType()) { 6891 // See if a method overloads virtual methods in a base 6892 // class without overriding any. 6893 if (!M->isStatic()) 6894 DiagnoseHiddenVirtualMethods(M); 6895 if (M->hasAttr<OverrideAttr>()) 6896 HasMethodWithOverrideControl = true; 6897 else if (M->size_overridden_methods() > 0) 6898 HasOverridingMethodWithoutOverrideControl = true; 6899 } 6900 6901 if (!isa<CXXDestructorDecl>(M)) 6902 CompleteMemberFunction(M); 6903 } else if (auto *F = dyn_cast<FriendDecl>(D)) { 6904 CheckForDefaultedFunction( 6905 dyn_cast_or_null<FunctionDecl>(F->getFriendDecl())); 6906 } 6907 } 6908 6909 if (HasOverridingMethodWithoutOverrideControl) { 6910 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl; 6911 for (auto *M : Record->methods()) 6912 DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl); 6913 } 6914 6915 // Check the defaulted secondary comparisons after any other member functions. 6916 for (FunctionDecl *FD : DefaultedSecondaryComparisons) { 6917 CheckExplicitlyDefaultedFunction(S, FD); 6918 6919 // If this is a member function, we deferred checking it until now. 6920 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) 6921 CheckCompletedMemberFunction(MD); 6922 } 6923 6924 // ms_struct is a request to use the same ABI rules as MSVC. Check 6925 // whether this class uses any C++ features that are implemented 6926 // completely differently in MSVC, and if so, emit a diagnostic. 6927 // That diagnostic defaults to an error, but we allow projects to 6928 // map it down to a warning (or ignore it). It's a fairly common 6929 // practice among users of the ms_struct pragma to mass-annotate 6930 // headers, sweeping up a bunch of types that the project doesn't 6931 // really rely on MSVC-compatible layout for. We must therefore 6932 // support "ms_struct except for C++ stuff" as a secondary ABI. 6933 // Don't emit this diagnostic if the feature was enabled as a 6934 // language option (as opposed to via a pragma or attribute), as 6935 // the option -mms-bitfields otherwise essentially makes it impossible 6936 // to build C++ code, unless this diagnostic is turned off. 6937 if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields && 6938 (Record->isPolymorphic() || Record->getNumBases())) { 6939 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 6940 } 6941 6942 checkClassLevelDLLAttribute(Record); 6943 checkClassLevelCodeSegAttribute(Record); 6944 6945 bool ClangABICompat4 = 6946 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4; 6947 TargetInfo::CallingConvKind CCK = 6948 Context.getTargetInfo().getCallingConvKind(ClangABICompat4); 6949 bool CanPass = canPassInRegisters(*this, Record, CCK); 6950 6951 // Do not change ArgPassingRestrictions if it has already been set to 6952 // APK_CanNeverPassInRegs. 6953 if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs) 6954 Record->setArgPassingRestrictions(CanPass 6955 ? RecordDecl::APK_CanPassInRegs 6956 : RecordDecl::APK_CannotPassInRegs); 6957 6958 // If canPassInRegisters returns true despite the record having a non-trivial 6959 // destructor, the record is destructed in the callee. This happens only when 6960 // the record or one of its subobjects has a field annotated with trivial_abi 6961 // or a field qualified with ObjC __strong/__weak. 6962 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee()) 6963 Record->setParamDestroyedInCallee(true); 6964 else if (Record->hasNonTrivialDestructor()) 6965 Record->setParamDestroyedInCallee(CanPass); 6966 6967 if (getLangOpts().ForceEmitVTables) { 6968 // If we want to emit all the vtables, we need to mark it as used. This 6969 // is especially required for cases like vtable assumption loads. 6970 MarkVTableUsed(Record->getInnerLocStart(), Record); 6971 } 6972 6973 if (getLangOpts().CUDA) { 6974 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>()) 6975 checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record); 6976 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>()) 6977 checkCUDADeviceBuiltinTextureClassTemplate(*this, Record); 6978 } 6979 } 6980 6981 /// Look up the special member function that would be called by a special 6982 /// member function for a subobject of class type. 6983 /// 6984 /// \param Class The class type of the subobject. 6985 /// \param CSM The kind of special member function. 6986 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 6987 /// \param ConstRHS True if this is a copy operation with a const object 6988 /// on its RHS, that is, if the argument to the outer special member 6989 /// function is 'const' and this is not a field marked 'mutable'. 6990 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember( 6991 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 6992 unsigned FieldQuals, bool ConstRHS) { 6993 unsigned LHSQuals = 0; 6994 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 6995 LHSQuals = FieldQuals; 6996 6997 unsigned RHSQuals = FieldQuals; 6998 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 6999 RHSQuals = 0; 7000 else if (ConstRHS) 7001 RHSQuals |= Qualifiers::Const; 7002 7003 return S.LookupSpecialMember(Class, CSM, 7004 RHSQuals & Qualifiers::Const, 7005 RHSQuals & Qualifiers::Volatile, 7006 false, 7007 LHSQuals & Qualifiers::Const, 7008 LHSQuals & Qualifiers::Volatile); 7009 } 7010 7011 class Sema::InheritedConstructorInfo { 7012 Sema &S; 7013 SourceLocation UseLoc; 7014 7015 /// A mapping from the base classes through which the constructor was 7016 /// inherited to the using shadow declaration in that base class (or a null 7017 /// pointer if the constructor was declared in that base class). 7018 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *> 7019 InheritedFromBases; 7020 7021 public: 7022 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, 7023 ConstructorUsingShadowDecl *Shadow) 7024 : S(S), UseLoc(UseLoc) { 7025 bool DiagnosedMultipleConstructedBases = false; 7026 CXXRecordDecl *ConstructedBase = nullptr; 7027 BaseUsingDecl *ConstructedBaseIntroducer = nullptr; 7028 7029 // Find the set of such base class subobjects and check that there's a 7030 // unique constructed subobject. 7031 for (auto *D : Shadow->redecls()) { 7032 auto *DShadow = cast<ConstructorUsingShadowDecl>(D); 7033 auto *DNominatedBase = DShadow->getNominatedBaseClass(); 7034 auto *DConstructedBase = DShadow->getConstructedBaseClass(); 7035 7036 InheritedFromBases.insert( 7037 std::make_pair(DNominatedBase->getCanonicalDecl(), 7038 DShadow->getNominatedBaseClassShadowDecl())); 7039 if (DShadow->constructsVirtualBase()) 7040 InheritedFromBases.insert( 7041 std::make_pair(DConstructedBase->getCanonicalDecl(), 7042 DShadow->getConstructedBaseClassShadowDecl())); 7043 else 7044 assert(DNominatedBase == DConstructedBase); 7045 7046 // [class.inhctor.init]p2: 7047 // If the constructor was inherited from multiple base class subobjects 7048 // of type B, the program is ill-formed. 7049 if (!ConstructedBase) { 7050 ConstructedBase = DConstructedBase; 7051 ConstructedBaseIntroducer = D->getIntroducer(); 7052 } else if (ConstructedBase != DConstructedBase && 7053 !Shadow->isInvalidDecl()) { 7054 if (!DiagnosedMultipleConstructedBases) { 7055 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor) 7056 << Shadow->getTargetDecl(); 7057 S.Diag(ConstructedBaseIntroducer->getLocation(), 7058 diag::note_ambiguous_inherited_constructor_using) 7059 << ConstructedBase; 7060 DiagnosedMultipleConstructedBases = true; 7061 } 7062 S.Diag(D->getIntroducer()->getLocation(), 7063 diag::note_ambiguous_inherited_constructor_using) 7064 << DConstructedBase; 7065 } 7066 } 7067 7068 if (DiagnosedMultipleConstructedBases) 7069 Shadow->setInvalidDecl(); 7070 } 7071 7072 /// Find the constructor to use for inherited construction of a base class, 7073 /// and whether that base class constructor inherits the constructor from a 7074 /// virtual base class (in which case it won't actually invoke it). 7075 std::pair<CXXConstructorDecl *, bool> 7076 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const { 7077 auto It = InheritedFromBases.find(Base->getCanonicalDecl()); 7078 if (It == InheritedFromBases.end()) 7079 return std::make_pair(nullptr, false); 7080 7081 // This is an intermediary class. 7082 if (It->second) 7083 return std::make_pair( 7084 S.findInheritingConstructor(UseLoc, Ctor, It->second), 7085 It->second->constructsVirtualBase()); 7086 7087 // This is the base class from which the constructor was inherited. 7088 return std::make_pair(Ctor, false); 7089 } 7090 }; 7091 7092 /// Is the special member function which would be selected to perform the 7093 /// specified operation on the specified class type a constexpr constructor? 7094 static bool 7095 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 7096 Sema::CXXSpecialMember CSM, unsigned Quals, 7097 bool ConstRHS, 7098 CXXConstructorDecl *InheritedCtor = nullptr, 7099 Sema::InheritedConstructorInfo *Inherited = nullptr) { 7100 // If we're inheriting a constructor, see if we need to call it for this base 7101 // class. 7102 if (InheritedCtor) { 7103 assert(CSM == Sema::CXXDefaultConstructor); 7104 auto BaseCtor = 7105 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first; 7106 if (BaseCtor) 7107 return BaseCtor->isConstexpr(); 7108 } 7109 7110 if (CSM == Sema::CXXDefaultConstructor) 7111 return ClassDecl->hasConstexprDefaultConstructor(); 7112 if (CSM == Sema::CXXDestructor) 7113 return ClassDecl->hasConstexprDestructor(); 7114 7115 Sema::SpecialMemberOverloadResult SMOR = 7116 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 7117 if (!SMOR.getMethod()) 7118 // A constructor we wouldn't select can't be "involved in initializing" 7119 // anything. 7120 return true; 7121 return SMOR.getMethod()->isConstexpr(); 7122 } 7123 7124 /// Determine whether the specified special member function would be constexpr 7125 /// if it were implicitly defined. 7126 static bool defaultedSpecialMemberIsConstexpr( 7127 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, 7128 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr, 7129 Sema::InheritedConstructorInfo *Inherited = nullptr) { 7130 if (!S.getLangOpts().CPlusPlus11) 7131 return false; 7132 7133 // C++11 [dcl.constexpr]p4: 7134 // In the definition of a constexpr constructor [...] 7135 bool Ctor = true; 7136 switch (CSM) { 7137 case Sema::CXXDefaultConstructor: 7138 if (Inherited) 7139 break; 7140 // Since default constructor lookup is essentially trivial (and cannot 7141 // involve, for instance, template instantiation), we compute whether a 7142 // defaulted default constructor is constexpr directly within CXXRecordDecl. 7143 // 7144 // This is important for performance; we need to know whether the default 7145 // constructor is constexpr to determine whether the type is a literal type. 7146 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 7147 7148 case Sema::CXXCopyConstructor: 7149 case Sema::CXXMoveConstructor: 7150 // For copy or move constructors, we need to perform overload resolution. 7151 break; 7152 7153 case Sema::CXXCopyAssignment: 7154 case Sema::CXXMoveAssignment: 7155 if (!S.getLangOpts().CPlusPlus14) 7156 return false; 7157 // In C++1y, we need to perform overload resolution. 7158 Ctor = false; 7159 break; 7160 7161 case Sema::CXXDestructor: 7162 return ClassDecl->defaultedDestructorIsConstexpr(); 7163 7164 case Sema::CXXInvalid: 7165 return false; 7166 } 7167 7168 // -- if the class is a non-empty union, or for each non-empty anonymous 7169 // union member of a non-union class, exactly one non-static data member 7170 // shall be initialized; [DR1359] 7171 // 7172 // If we squint, this is guaranteed, since exactly one non-static data member 7173 // will be initialized (if the constructor isn't deleted), we just don't know 7174 // which one. 7175 if (Ctor && ClassDecl->isUnion()) 7176 return CSM == Sema::CXXDefaultConstructor 7177 ? ClassDecl->hasInClassInitializer() || 7178 !ClassDecl->hasVariantMembers() 7179 : true; 7180 7181 // -- the class shall not have any virtual base classes; 7182 if (Ctor && ClassDecl->getNumVBases()) 7183 return false; 7184 7185 // C++1y [class.copy]p26: 7186 // -- [the class] is a literal type, and 7187 if (!Ctor && !ClassDecl->isLiteral()) 7188 return false; 7189 7190 // -- every constructor involved in initializing [...] base class 7191 // sub-objects shall be a constexpr constructor; 7192 // -- the assignment operator selected to copy/move each direct base 7193 // class is a constexpr function, and 7194 for (const auto &B : ClassDecl->bases()) { 7195 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 7196 if (!BaseType) continue; 7197 7198 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7199 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg, 7200 InheritedCtor, Inherited)) 7201 return false; 7202 } 7203 7204 // -- every constructor involved in initializing non-static data members 7205 // [...] shall be a constexpr constructor; 7206 // -- every non-static data member and base class sub-object shall be 7207 // initialized 7208 // -- for each non-static data member of X that is of class type (or array 7209 // thereof), the assignment operator selected to copy/move that member is 7210 // a constexpr function 7211 for (const auto *F : ClassDecl->fields()) { 7212 if (F->isInvalidDecl()) 7213 continue; 7214 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer()) 7215 continue; 7216 QualType BaseType = S.Context.getBaseElementType(F->getType()); 7217 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 7218 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 7219 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 7220 BaseType.getCVRQualifiers(), 7221 ConstArg && !F->isMutable())) 7222 return false; 7223 } else if (CSM == Sema::CXXDefaultConstructor) { 7224 return false; 7225 } 7226 } 7227 7228 // All OK, it's constexpr! 7229 return true; 7230 } 7231 7232 namespace { 7233 /// RAII object to register a defaulted function as having its exception 7234 /// specification computed. 7235 struct ComputingExceptionSpec { 7236 Sema &S; 7237 7238 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc) 7239 : S(S) { 7240 Sema::CodeSynthesisContext Ctx; 7241 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation; 7242 Ctx.PointOfInstantiation = Loc; 7243 Ctx.Entity = FD; 7244 S.pushCodeSynthesisContext(Ctx); 7245 } 7246 ~ComputingExceptionSpec() { 7247 S.popCodeSynthesisContext(); 7248 } 7249 }; 7250 } 7251 7252 static Sema::ImplicitExceptionSpecification 7253 ComputeDefaultedSpecialMemberExceptionSpec( 7254 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 7255 Sema::InheritedConstructorInfo *ICI); 7256 7257 static Sema::ImplicitExceptionSpecification 7258 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, 7259 FunctionDecl *FD, 7260 Sema::DefaultedComparisonKind DCK); 7261 7262 static Sema::ImplicitExceptionSpecification 7263 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) { 7264 auto DFK = S.getDefaultedFunctionKind(FD); 7265 if (DFK.isSpecialMember()) 7266 return ComputeDefaultedSpecialMemberExceptionSpec( 7267 S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr); 7268 if (DFK.isComparison()) 7269 return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD, 7270 DFK.asComparison()); 7271 7272 auto *CD = cast<CXXConstructorDecl>(FD); 7273 assert(CD->getInheritedConstructor() && 7274 "only defaulted functions and inherited constructors have implicit " 7275 "exception specs"); 7276 Sema::InheritedConstructorInfo ICI( 7277 S, Loc, CD->getInheritedConstructor().getShadowDecl()); 7278 return ComputeDefaultedSpecialMemberExceptionSpec( 7279 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI); 7280 } 7281 7282 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 7283 CXXMethodDecl *MD) { 7284 FunctionProtoType::ExtProtoInfo EPI; 7285 7286 // Build an exception specification pointing back at this member. 7287 EPI.ExceptionSpec.Type = EST_Unevaluated; 7288 EPI.ExceptionSpec.SourceDecl = MD; 7289 7290 // Set the calling convention to the default for C++ instance methods. 7291 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 7292 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 7293 /*IsCXXMethod=*/true)); 7294 return EPI; 7295 } 7296 7297 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) { 7298 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>(); 7299 if (FPT->getExceptionSpecType() != EST_Unevaluated) 7300 return; 7301 7302 // Evaluate the exception specification. 7303 auto IES = computeImplicitExceptionSpec(*this, Loc, FD); 7304 auto ESI = IES.getExceptionSpec(); 7305 7306 // Update the type of the special member to use it. 7307 UpdateExceptionSpec(FD, ESI); 7308 } 7309 7310 void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) { 7311 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted"); 7312 7313 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD); 7314 if (!DefKind) { 7315 assert(FD->getDeclContext()->isDependentContext()); 7316 return; 7317 } 7318 7319 if (DefKind.isComparison()) 7320 UnusedPrivateFields.clear(); 7321 7322 if (DefKind.isSpecialMember() 7323 ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD), 7324 DefKind.asSpecialMember()) 7325 : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison())) 7326 FD->setInvalidDecl(); 7327 } 7328 7329 bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD, 7330 CXXSpecialMember CSM) { 7331 CXXRecordDecl *RD = MD->getParent(); 7332 7333 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 7334 "not an explicitly-defaulted special member"); 7335 7336 // Defer all checking for special members of a dependent type. 7337 if (RD->isDependentType()) 7338 return false; 7339 7340 // Whether this was the first-declared instance of the constructor. 7341 // This affects whether we implicitly add an exception spec and constexpr. 7342 bool First = MD == MD->getCanonicalDecl(); 7343 7344 bool HadError = false; 7345 7346 // C++11 [dcl.fct.def.default]p1: 7347 // A function that is explicitly defaulted shall 7348 // -- be a special member function [...] (checked elsewhere), 7349 // -- have the same type (except for ref-qualifiers, and except that a 7350 // copy operation can take a non-const reference) as an implicit 7351 // declaration, and 7352 // -- not have default arguments. 7353 // C++2a changes the second bullet to instead delete the function if it's 7354 // defaulted on its first declaration, unless it's "an assignment operator, 7355 // and its return type differs or its parameter type is not a reference". 7356 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First; 7357 bool ShouldDeleteForTypeMismatch = false; 7358 unsigned ExpectedParams = 1; 7359 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 7360 ExpectedParams = 0; 7361 if (MD->getNumParams() != ExpectedParams) { 7362 // This checks for default arguments: a copy or move constructor with a 7363 // default argument is classified as a default constructor, and assignment 7364 // operations and destructors can't have default arguments. 7365 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 7366 << CSM << MD->getSourceRange(); 7367 HadError = true; 7368 } else if (MD->isVariadic()) { 7369 if (DeleteOnTypeMismatch) 7370 ShouldDeleteForTypeMismatch = true; 7371 else { 7372 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 7373 << CSM << MD->getSourceRange(); 7374 HadError = true; 7375 } 7376 } 7377 7378 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 7379 7380 bool CanHaveConstParam = false; 7381 if (CSM == CXXCopyConstructor) 7382 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 7383 else if (CSM == CXXCopyAssignment) 7384 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 7385 7386 QualType ReturnType = Context.VoidTy; 7387 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 7388 // Check for return type matching. 7389 ReturnType = Type->getReturnType(); 7390 7391 QualType DeclType = Context.getTypeDeclType(RD); 7392 DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace()); 7393 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType); 7394 7395 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 7396 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 7397 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 7398 HadError = true; 7399 } 7400 7401 // A defaulted special member cannot have cv-qualifiers. 7402 if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) { 7403 if (DeleteOnTypeMismatch) 7404 ShouldDeleteForTypeMismatch = true; 7405 else { 7406 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 7407 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 7408 HadError = true; 7409 } 7410 } 7411 } 7412 7413 // Check for parameter type matching. 7414 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 7415 bool HasConstParam = false; 7416 if (ExpectedParams && ArgType->isReferenceType()) { 7417 // Argument must be reference to possibly-const T. 7418 QualType ReferentType = ArgType->getPointeeType(); 7419 HasConstParam = ReferentType.isConstQualified(); 7420 7421 if (ReferentType.isVolatileQualified()) { 7422 if (DeleteOnTypeMismatch) 7423 ShouldDeleteForTypeMismatch = true; 7424 else { 7425 Diag(MD->getLocation(), 7426 diag::err_defaulted_special_member_volatile_param) << CSM; 7427 HadError = true; 7428 } 7429 } 7430 7431 if (HasConstParam && !CanHaveConstParam) { 7432 if (DeleteOnTypeMismatch) 7433 ShouldDeleteForTypeMismatch = true; 7434 else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 7435 Diag(MD->getLocation(), 7436 diag::err_defaulted_special_member_copy_const_param) 7437 << (CSM == CXXCopyAssignment); 7438 // FIXME: Explain why this special member can't be const. 7439 HadError = true; 7440 } else { 7441 Diag(MD->getLocation(), 7442 diag::err_defaulted_special_member_move_const_param) 7443 << (CSM == CXXMoveAssignment); 7444 HadError = true; 7445 } 7446 } 7447 } else if (ExpectedParams) { 7448 // A copy assignment operator can take its argument by value, but a 7449 // defaulted one cannot. 7450 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 7451 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 7452 HadError = true; 7453 } 7454 7455 // C++11 [dcl.fct.def.default]p2: 7456 // An explicitly-defaulted function may be declared constexpr only if it 7457 // would have been implicitly declared as constexpr, 7458 // Do not apply this rule to members of class templates, since core issue 1358 7459 // makes such functions always instantiate to constexpr functions. For 7460 // functions which cannot be constexpr (for non-constructors in C++11 and for 7461 // destructors in C++14 and C++17), this is checked elsewhere. 7462 // 7463 // FIXME: This should not apply if the member is deleted. 7464 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 7465 HasConstParam); 7466 if ((getLangOpts().CPlusPlus20 || 7467 (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 7468 : isa<CXXConstructorDecl>(MD))) && 7469 MD->isConstexpr() && !Constexpr && 7470 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 7471 Diag(MD->getBeginLoc(), MD->isConsteval() 7472 ? diag::err_incorrect_defaulted_consteval 7473 : diag::err_incorrect_defaulted_constexpr) 7474 << CSM; 7475 // FIXME: Explain why the special member can't be constexpr. 7476 HadError = true; 7477 } 7478 7479 if (First) { 7480 // C++2a [dcl.fct.def.default]p3: 7481 // If a function is explicitly defaulted on its first declaration, it is 7482 // implicitly considered to be constexpr if the implicit declaration 7483 // would be. 7484 MD->setConstexprKind(Constexpr ? (MD->isConsteval() 7485 ? ConstexprSpecKind::Consteval 7486 : ConstexprSpecKind::Constexpr) 7487 : ConstexprSpecKind::Unspecified); 7488 7489 if (!Type->hasExceptionSpec()) { 7490 // C++2a [except.spec]p3: 7491 // If a declaration of a function does not have a noexcept-specifier 7492 // [and] is defaulted on its first declaration, [...] the exception 7493 // specification is as specified below 7494 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 7495 EPI.ExceptionSpec.Type = EST_Unevaluated; 7496 EPI.ExceptionSpec.SourceDecl = MD; 7497 MD->setType(Context.getFunctionType(ReturnType, 7498 llvm::makeArrayRef(&ArgType, 7499 ExpectedParams), 7500 EPI)); 7501 } 7502 } 7503 7504 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) { 7505 if (First) { 7506 SetDeclDeleted(MD, MD->getLocation()); 7507 if (!inTemplateInstantiation() && !HadError) { 7508 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM; 7509 if (ShouldDeleteForTypeMismatch) { 7510 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM; 7511 } else { 7512 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 7513 } 7514 } 7515 if (ShouldDeleteForTypeMismatch && !HadError) { 7516 Diag(MD->getLocation(), 7517 diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM; 7518 } 7519 } else { 7520 // C++11 [dcl.fct.def.default]p4: 7521 // [For a] user-provided explicitly-defaulted function [...] if such a 7522 // function is implicitly defined as deleted, the program is ill-formed. 7523 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 7524 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl"); 7525 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 7526 HadError = true; 7527 } 7528 } 7529 7530 return HadError; 7531 } 7532 7533 namespace { 7534 /// Helper class for building and checking a defaulted comparison. 7535 /// 7536 /// Defaulted functions are built in two phases: 7537 /// 7538 /// * First, the set of operations that the function will perform are 7539 /// identified, and some of them are checked. If any of the checked 7540 /// operations is invalid in certain ways, the comparison function is 7541 /// defined as deleted and no body is built. 7542 /// * Then, if the function is not defined as deleted, the body is built. 7543 /// 7544 /// This is accomplished by performing two visitation steps over the eventual 7545 /// body of the function. 7546 template<typename Derived, typename ResultList, typename Result, 7547 typename Subobject> 7548 class DefaultedComparisonVisitor { 7549 public: 7550 using DefaultedComparisonKind = Sema::DefaultedComparisonKind; 7551 7552 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7553 DefaultedComparisonKind DCK) 7554 : S(S), RD(RD), FD(FD), DCK(DCK) { 7555 if (auto *Info = FD->getDefaultedFunctionInfo()) { 7556 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an 7557 // UnresolvedSet to avoid this copy. 7558 Fns.assign(Info->getUnqualifiedLookups().begin(), 7559 Info->getUnqualifiedLookups().end()); 7560 } 7561 } 7562 7563 ResultList visit() { 7564 // The type of an lvalue naming a parameter of this function. 7565 QualType ParamLvalType = 7566 FD->getParamDecl(0)->getType().getNonReferenceType(); 7567 7568 ResultList Results; 7569 7570 switch (DCK) { 7571 case DefaultedComparisonKind::None: 7572 llvm_unreachable("not a defaulted comparison"); 7573 7574 case DefaultedComparisonKind::Equal: 7575 case DefaultedComparisonKind::ThreeWay: 7576 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers()); 7577 return Results; 7578 7579 case DefaultedComparisonKind::NotEqual: 7580 case DefaultedComparisonKind::Relational: 7581 Results.add(getDerived().visitExpandedSubobject( 7582 ParamLvalType, getDerived().getCompleteObject())); 7583 return Results; 7584 } 7585 llvm_unreachable(""); 7586 } 7587 7588 protected: 7589 Derived &getDerived() { return static_cast<Derived&>(*this); } 7590 7591 /// Visit the expanded list of subobjects of the given type, as specified in 7592 /// C++2a [class.compare.default]. 7593 /// 7594 /// \return \c true if the ResultList object said we're done, \c false if not. 7595 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record, 7596 Qualifiers Quals) { 7597 // C++2a [class.compare.default]p4: 7598 // The direct base class subobjects of C 7599 for (CXXBaseSpecifier &Base : Record->bases()) 7600 if (Results.add(getDerived().visitSubobject( 7601 S.Context.getQualifiedType(Base.getType(), Quals), 7602 getDerived().getBase(&Base)))) 7603 return true; 7604 7605 // followed by the non-static data members of C 7606 for (FieldDecl *Field : Record->fields()) { 7607 // Recursively expand anonymous structs. 7608 if (Field->isAnonymousStructOrUnion()) { 7609 if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(), 7610 Quals)) 7611 return true; 7612 continue; 7613 } 7614 7615 // Figure out the type of an lvalue denoting this field. 7616 Qualifiers FieldQuals = Quals; 7617 if (Field->isMutable()) 7618 FieldQuals.removeConst(); 7619 QualType FieldType = 7620 S.Context.getQualifiedType(Field->getType(), FieldQuals); 7621 7622 if (Results.add(getDerived().visitSubobject( 7623 FieldType, getDerived().getField(Field)))) 7624 return true; 7625 } 7626 7627 // form a list of subobjects. 7628 return false; 7629 } 7630 7631 Result visitSubobject(QualType Type, Subobject Subobj) { 7632 // In that list, any subobject of array type is recursively expanded 7633 const ArrayType *AT = S.Context.getAsArrayType(Type); 7634 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT)) 7635 return getDerived().visitSubobjectArray(CAT->getElementType(), 7636 CAT->getSize(), Subobj); 7637 return getDerived().visitExpandedSubobject(Type, Subobj); 7638 } 7639 7640 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size, 7641 Subobject Subobj) { 7642 return getDerived().visitSubobject(Type, Subobj); 7643 } 7644 7645 protected: 7646 Sema &S; 7647 CXXRecordDecl *RD; 7648 FunctionDecl *FD; 7649 DefaultedComparisonKind DCK; 7650 UnresolvedSet<16> Fns; 7651 }; 7652 7653 /// Information about a defaulted comparison, as determined by 7654 /// DefaultedComparisonAnalyzer. 7655 struct DefaultedComparisonInfo { 7656 bool Deleted = false; 7657 bool Constexpr = true; 7658 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering; 7659 7660 static DefaultedComparisonInfo deleted() { 7661 DefaultedComparisonInfo Deleted; 7662 Deleted.Deleted = true; 7663 return Deleted; 7664 } 7665 7666 bool add(const DefaultedComparisonInfo &R) { 7667 Deleted |= R.Deleted; 7668 Constexpr &= R.Constexpr; 7669 Category = commonComparisonType(Category, R.Category); 7670 return Deleted; 7671 } 7672 }; 7673 7674 /// An element in the expanded list of subobjects of a defaulted comparison, as 7675 /// specified in C++2a [class.compare.default]p4. 7676 struct DefaultedComparisonSubobject { 7677 enum { CompleteObject, Member, Base } Kind; 7678 NamedDecl *Decl; 7679 SourceLocation Loc; 7680 }; 7681 7682 /// A visitor over the notional body of a defaulted comparison that determines 7683 /// whether that body would be deleted or constexpr. 7684 class DefaultedComparisonAnalyzer 7685 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer, 7686 DefaultedComparisonInfo, 7687 DefaultedComparisonInfo, 7688 DefaultedComparisonSubobject> { 7689 public: 7690 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr }; 7691 7692 private: 7693 DiagnosticKind Diagnose; 7694 7695 public: 7696 using Base = DefaultedComparisonVisitor; 7697 using Result = DefaultedComparisonInfo; 7698 using Subobject = DefaultedComparisonSubobject; 7699 7700 friend Base; 7701 7702 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7703 DefaultedComparisonKind DCK, 7704 DiagnosticKind Diagnose = NoDiagnostics) 7705 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {} 7706 7707 Result visit() { 7708 if ((DCK == DefaultedComparisonKind::Equal || 7709 DCK == DefaultedComparisonKind::ThreeWay) && 7710 RD->hasVariantMembers()) { 7711 // C++2a [class.compare.default]p2 [P2002R0]: 7712 // A defaulted comparison operator function for class C is defined as 7713 // deleted if [...] C has variant members. 7714 if (Diagnose == ExplainDeleted) { 7715 S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union) 7716 << FD << RD->isUnion() << RD; 7717 } 7718 return Result::deleted(); 7719 } 7720 7721 return Base::visit(); 7722 } 7723 7724 private: 7725 Subobject getCompleteObject() { 7726 return Subobject{Subobject::CompleteObject, RD, FD->getLocation()}; 7727 } 7728 7729 Subobject getBase(CXXBaseSpecifier *Base) { 7730 return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(), 7731 Base->getBaseTypeLoc()}; 7732 } 7733 7734 Subobject getField(FieldDecl *Field) { 7735 return Subobject{Subobject::Member, Field, Field->getLocation()}; 7736 } 7737 7738 Result visitExpandedSubobject(QualType Type, Subobject Subobj) { 7739 // C++2a [class.compare.default]p2 [P2002R0]: 7740 // A defaulted <=> or == operator function for class C is defined as 7741 // deleted if any non-static data member of C is of reference type 7742 if (Type->isReferenceType()) { 7743 if (Diagnose == ExplainDeleted) { 7744 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member) 7745 << FD << RD; 7746 } 7747 return Result::deleted(); 7748 } 7749 7750 // [...] Let xi be an lvalue denoting the ith element [...] 7751 OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue); 7752 Expr *Args[] = {&Xi, &Xi}; 7753 7754 // All operators start by trying to apply that same operator recursively. 7755 OverloadedOperatorKind OO = FD->getOverloadedOperator(); 7756 assert(OO != OO_None && "not an overloaded operator!"); 7757 return visitBinaryOperator(OO, Args, Subobj); 7758 } 7759 7760 Result 7761 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args, 7762 Subobject Subobj, 7763 OverloadCandidateSet *SpaceshipCandidates = nullptr) { 7764 // Note that there is no need to consider rewritten candidates here if 7765 // we've already found there is no viable 'operator<=>' candidate (and are 7766 // considering synthesizing a '<=>' from '==' and '<'). 7767 OverloadCandidateSet CandidateSet( 7768 FD->getLocation(), OverloadCandidateSet::CSK_Operator, 7769 OverloadCandidateSet::OperatorRewriteInfo( 7770 OO, /*AllowRewrittenCandidates=*/!SpaceshipCandidates)); 7771 7772 /// C++2a [class.compare.default]p1 [P2002R0]: 7773 /// [...] the defaulted function itself is never a candidate for overload 7774 /// resolution [...] 7775 CandidateSet.exclude(FD); 7776 7777 if (Args[0]->getType()->isOverloadableType()) 7778 S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args); 7779 else 7780 // FIXME: We determine whether this is a valid expression by checking to 7781 // see if there's a viable builtin operator candidate for it. That isn't 7782 // really what the rules ask us to do, but should give the right results. 7783 S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet); 7784 7785 Result R; 7786 7787 OverloadCandidateSet::iterator Best; 7788 switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) { 7789 case OR_Success: { 7790 // C++2a [class.compare.secondary]p2 [P2002R0]: 7791 // The operator function [...] is defined as deleted if [...] the 7792 // candidate selected by overload resolution is not a rewritten 7793 // candidate. 7794 if ((DCK == DefaultedComparisonKind::NotEqual || 7795 DCK == DefaultedComparisonKind::Relational) && 7796 !Best->RewriteKind) { 7797 if (Diagnose == ExplainDeleted) { 7798 S.Diag(Best->Function->getLocation(), 7799 diag::note_defaulted_comparison_not_rewritten_callee) 7800 << FD; 7801 } 7802 return Result::deleted(); 7803 } 7804 7805 // Throughout C++2a [class.compare]: if overload resolution does not 7806 // result in a usable function, the candidate function is defined as 7807 // deleted. This requires that we selected an accessible function. 7808 // 7809 // Note that this only considers the access of the function when named 7810 // within the type of the subobject, and not the access path for any 7811 // derived-to-base conversion. 7812 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl(); 7813 if (ArgClass && Best->FoundDecl.getDecl() && 7814 Best->FoundDecl.getDecl()->isCXXClassMember()) { 7815 QualType ObjectType = Subobj.Kind == Subobject::Member 7816 ? Args[0]->getType() 7817 : S.Context.getRecordType(RD); 7818 if (!S.isMemberAccessibleForDeletion( 7819 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc, 7820 Diagnose == ExplainDeleted 7821 ? S.PDiag(diag::note_defaulted_comparison_inaccessible) 7822 << FD << Subobj.Kind << Subobj.Decl 7823 : S.PDiag())) 7824 return Result::deleted(); 7825 } 7826 7827 bool NeedsDeducing = 7828 OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType(); 7829 7830 if (FunctionDecl *BestFD = Best->Function) { 7831 // C++2a [class.compare.default]p3 [P2002R0]: 7832 // A defaulted comparison function is constexpr-compatible if 7833 // [...] no overlod resolution performed [...] results in a 7834 // non-constexpr function. 7835 assert(!BestFD->isDeleted() && "wrong overload resolution result"); 7836 // If it's not constexpr, explain why not. 7837 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) { 7838 if (Subobj.Kind != Subobject::CompleteObject) 7839 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr) 7840 << Subobj.Kind << Subobj.Decl; 7841 S.Diag(BestFD->getLocation(), 7842 diag::note_defaulted_comparison_not_constexpr_here); 7843 // Bail out after explaining; we don't want any more notes. 7844 return Result::deleted(); 7845 } 7846 R.Constexpr &= BestFD->isConstexpr(); 7847 7848 if (NeedsDeducing) { 7849 // If any callee has an undeduced return type, deduce it now. 7850 // FIXME: It's not clear how a failure here should be handled. For 7851 // now, we produce an eager diagnostic, because that is forward 7852 // compatible with most (all?) other reasonable options. 7853 if (BestFD->getReturnType()->isUndeducedType() && 7854 S.DeduceReturnType(BestFD, FD->getLocation(), 7855 /*Diagnose=*/false)) { 7856 // Don't produce a duplicate error when asked to explain why the 7857 // comparison is deleted: we diagnosed that when initially checking 7858 // the defaulted operator. 7859 if (Diagnose == NoDiagnostics) { 7860 S.Diag( 7861 FD->getLocation(), 7862 diag::err_defaulted_comparison_cannot_deduce_undeduced_auto) 7863 << Subobj.Kind << Subobj.Decl; 7864 S.Diag( 7865 Subobj.Loc, 7866 diag::note_defaulted_comparison_cannot_deduce_undeduced_auto) 7867 << Subobj.Kind << Subobj.Decl; 7868 S.Diag(BestFD->getLocation(), 7869 diag::note_defaulted_comparison_cannot_deduce_callee) 7870 << Subobj.Kind << Subobj.Decl; 7871 } 7872 return Result::deleted(); 7873 } 7874 auto *Info = S.Context.CompCategories.lookupInfoForType( 7875 BestFD->getCallResultType()); 7876 if (!Info) { 7877 if (Diagnose == ExplainDeleted) { 7878 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce) 7879 << Subobj.Kind << Subobj.Decl 7880 << BestFD->getCallResultType().withoutLocalFastQualifiers(); 7881 S.Diag(BestFD->getLocation(), 7882 diag::note_defaulted_comparison_cannot_deduce_callee) 7883 << Subobj.Kind << Subobj.Decl; 7884 } 7885 return Result::deleted(); 7886 } 7887 R.Category = Info->Kind; 7888 } 7889 } else { 7890 QualType T = Best->BuiltinParamTypes[0]; 7891 assert(T == Best->BuiltinParamTypes[1] && 7892 "builtin comparison for different types?"); 7893 assert(Best->BuiltinParamTypes[2].isNull() && 7894 "invalid builtin comparison"); 7895 7896 if (NeedsDeducing) { 7897 Optional<ComparisonCategoryType> Cat = 7898 getComparisonCategoryForBuiltinCmp(T); 7899 assert(Cat && "no category for builtin comparison?"); 7900 R.Category = *Cat; 7901 } 7902 } 7903 7904 // Note that we might be rewriting to a different operator. That call is 7905 // not considered until we come to actually build the comparison function. 7906 break; 7907 } 7908 7909 case OR_Ambiguous: 7910 if (Diagnose == ExplainDeleted) { 7911 unsigned Kind = 0; 7912 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship) 7913 Kind = OO == OO_EqualEqual ? 1 : 2; 7914 CandidateSet.NoteCandidates( 7915 PartialDiagnosticAt( 7916 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous) 7917 << FD << Kind << Subobj.Kind << Subobj.Decl), 7918 S, OCD_AmbiguousCandidates, Args); 7919 } 7920 R = Result::deleted(); 7921 break; 7922 7923 case OR_Deleted: 7924 if (Diagnose == ExplainDeleted) { 7925 if ((DCK == DefaultedComparisonKind::NotEqual || 7926 DCK == DefaultedComparisonKind::Relational) && 7927 !Best->RewriteKind) { 7928 S.Diag(Best->Function->getLocation(), 7929 diag::note_defaulted_comparison_not_rewritten_callee) 7930 << FD; 7931 } else { 7932 S.Diag(Subobj.Loc, 7933 diag::note_defaulted_comparison_calls_deleted) 7934 << FD << Subobj.Kind << Subobj.Decl; 7935 S.NoteDeletedFunction(Best->Function); 7936 } 7937 } 7938 R = Result::deleted(); 7939 break; 7940 7941 case OR_No_Viable_Function: 7942 // If there's no usable candidate, we're done unless we can rewrite a 7943 // '<=>' in terms of '==' and '<'. 7944 if (OO == OO_Spaceship && 7945 S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) { 7946 // For any kind of comparison category return type, we need a usable 7947 // '==' and a usable '<'. 7948 if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj, 7949 &CandidateSet))) 7950 R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet)); 7951 break; 7952 } 7953 7954 if (Diagnose == ExplainDeleted) { 7955 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function) 7956 << FD << Subobj.Kind << Subobj.Decl; 7957 7958 // For a three-way comparison, list both the candidates for the 7959 // original operator and the candidates for the synthesized operator. 7960 if (SpaceshipCandidates) { 7961 SpaceshipCandidates->NoteCandidates( 7962 S, Args, 7963 SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates, 7964 Args, FD->getLocation())); 7965 S.Diag(Subobj.Loc, 7966 diag::note_defaulted_comparison_no_viable_function_synthesized) 7967 << (OO == OO_EqualEqual ? 0 : 1); 7968 } 7969 7970 CandidateSet.NoteCandidates( 7971 S, Args, 7972 CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args, 7973 FD->getLocation())); 7974 } 7975 R = Result::deleted(); 7976 break; 7977 } 7978 7979 return R; 7980 } 7981 }; 7982 7983 /// A list of statements. 7984 struct StmtListResult { 7985 bool IsInvalid = false; 7986 llvm::SmallVector<Stmt*, 16> Stmts; 7987 7988 bool add(const StmtResult &S) { 7989 IsInvalid |= S.isInvalid(); 7990 if (IsInvalid) 7991 return true; 7992 Stmts.push_back(S.get()); 7993 return false; 7994 } 7995 }; 7996 7997 /// A visitor over the notional body of a defaulted comparison that synthesizes 7998 /// the actual body. 7999 class DefaultedComparisonSynthesizer 8000 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer, 8001 StmtListResult, StmtResult, 8002 std::pair<ExprResult, ExprResult>> { 8003 SourceLocation Loc; 8004 unsigned ArrayDepth = 0; 8005 8006 public: 8007 using Base = DefaultedComparisonVisitor; 8008 using ExprPair = std::pair<ExprResult, ExprResult>; 8009 8010 friend Base; 8011 8012 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 8013 DefaultedComparisonKind DCK, 8014 SourceLocation BodyLoc) 8015 : Base(S, RD, FD, DCK), Loc(BodyLoc) {} 8016 8017 /// Build a suitable function body for this defaulted comparison operator. 8018 StmtResult build() { 8019 Sema::CompoundScopeRAII CompoundScope(S); 8020 8021 StmtListResult Stmts = visit(); 8022 if (Stmts.IsInvalid) 8023 return StmtError(); 8024 8025 ExprResult RetVal; 8026 switch (DCK) { 8027 case DefaultedComparisonKind::None: 8028 llvm_unreachable("not a defaulted comparison"); 8029 8030 case DefaultedComparisonKind::Equal: { 8031 // C++2a [class.eq]p3: 8032 // [...] compar[e] the corresponding elements [...] until the first 8033 // index i where xi == yi yields [...] false. If no such index exists, 8034 // V is true. Otherwise, V is false. 8035 // 8036 // Join the comparisons with '&&'s and return the result. Use a right 8037 // fold (traversing the conditions right-to-left), because that 8038 // short-circuits more naturally. 8039 auto OldStmts = std::move(Stmts.Stmts); 8040 Stmts.Stmts.clear(); 8041 ExprResult CmpSoFar; 8042 // Finish a particular comparison chain. 8043 auto FinishCmp = [&] { 8044 if (Expr *Prior = CmpSoFar.get()) { 8045 // Convert the last expression to 'return ...;' 8046 if (RetVal.isUnset() && Stmts.Stmts.empty()) 8047 RetVal = CmpSoFar; 8048 // Convert any prior comparison to 'if (!(...)) return false;' 8049 else if (Stmts.add(buildIfNotCondReturnFalse(Prior))) 8050 return true; 8051 CmpSoFar = ExprResult(); 8052 } 8053 return false; 8054 }; 8055 for (Stmt *EAsStmt : llvm::reverse(OldStmts)) { 8056 Expr *E = dyn_cast<Expr>(EAsStmt); 8057 if (!E) { 8058 // Found an array comparison. 8059 if (FinishCmp() || Stmts.add(EAsStmt)) 8060 return StmtError(); 8061 continue; 8062 } 8063 8064 if (CmpSoFar.isUnset()) { 8065 CmpSoFar = E; 8066 continue; 8067 } 8068 CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get()); 8069 if (CmpSoFar.isInvalid()) 8070 return StmtError(); 8071 } 8072 if (FinishCmp()) 8073 return StmtError(); 8074 std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end()); 8075 // If no such index exists, V is true. 8076 if (RetVal.isUnset()) 8077 RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true); 8078 break; 8079 } 8080 8081 case DefaultedComparisonKind::ThreeWay: { 8082 // Per C++2a [class.spaceship]p3, as a fallback add: 8083 // return static_cast<R>(std::strong_ordering::equal); 8084 QualType StrongOrdering = S.CheckComparisonCategoryType( 8085 ComparisonCategoryType::StrongOrdering, Loc, 8086 Sema::ComparisonCategoryUsage::DefaultedOperator); 8087 if (StrongOrdering.isNull()) 8088 return StmtError(); 8089 VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering) 8090 .getValueInfo(ComparisonCategoryResult::Equal) 8091 ->VD; 8092 RetVal = getDecl(EqualVD); 8093 if (RetVal.isInvalid()) 8094 return StmtError(); 8095 RetVal = buildStaticCastToR(RetVal.get()); 8096 break; 8097 } 8098 8099 case DefaultedComparisonKind::NotEqual: 8100 case DefaultedComparisonKind::Relational: 8101 RetVal = cast<Expr>(Stmts.Stmts.pop_back_val()); 8102 break; 8103 } 8104 8105 // Build the final return statement. 8106 if (RetVal.isInvalid()) 8107 return StmtError(); 8108 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get()); 8109 if (ReturnStmt.isInvalid()) 8110 return StmtError(); 8111 Stmts.Stmts.push_back(ReturnStmt.get()); 8112 8113 return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false); 8114 } 8115 8116 private: 8117 ExprResult getDecl(ValueDecl *VD) { 8118 return S.BuildDeclarationNameExpr( 8119 CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD); 8120 } 8121 8122 ExprResult getParam(unsigned I) { 8123 ParmVarDecl *PD = FD->getParamDecl(I); 8124 return getDecl(PD); 8125 } 8126 8127 ExprPair getCompleteObject() { 8128 unsigned Param = 0; 8129 ExprResult LHS; 8130 if (isa<CXXMethodDecl>(FD)) { 8131 // LHS is '*this'. 8132 LHS = S.ActOnCXXThis(Loc); 8133 if (!LHS.isInvalid()) 8134 LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get()); 8135 } else { 8136 LHS = getParam(Param++); 8137 } 8138 ExprResult RHS = getParam(Param++); 8139 assert(Param == FD->getNumParams()); 8140 return {LHS, RHS}; 8141 } 8142 8143 ExprPair getBase(CXXBaseSpecifier *Base) { 8144 ExprPair Obj = getCompleteObject(); 8145 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 8146 return {ExprError(), ExprError()}; 8147 CXXCastPath Path = {Base}; 8148 return {S.ImpCastExprToType(Obj.first.get(), Base->getType(), 8149 CK_DerivedToBase, VK_LValue, &Path), 8150 S.ImpCastExprToType(Obj.second.get(), Base->getType(), 8151 CK_DerivedToBase, VK_LValue, &Path)}; 8152 } 8153 8154 ExprPair getField(FieldDecl *Field) { 8155 ExprPair Obj = getCompleteObject(); 8156 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 8157 return {ExprError(), ExprError()}; 8158 8159 DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess()); 8160 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc); 8161 return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc, 8162 CXXScopeSpec(), Field, Found, NameInfo), 8163 S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc, 8164 CXXScopeSpec(), Field, Found, NameInfo)}; 8165 } 8166 8167 // FIXME: When expanding a subobject, register a note in the code synthesis 8168 // stack to say which subobject we're comparing. 8169 8170 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) { 8171 if (Cond.isInvalid()) 8172 return StmtError(); 8173 8174 ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get()); 8175 if (NotCond.isInvalid()) 8176 return StmtError(); 8177 8178 ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false); 8179 assert(!False.isInvalid() && "should never fail"); 8180 StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get()); 8181 if (ReturnFalse.isInvalid()) 8182 return StmtError(); 8183 8184 return S.ActOnIfStmt(Loc, false, Loc, nullptr, 8185 S.ActOnCondition(nullptr, Loc, NotCond.get(), 8186 Sema::ConditionKind::Boolean), 8187 Loc, ReturnFalse.get(), SourceLocation(), nullptr); 8188 } 8189 8190 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size, 8191 ExprPair Subobj) { 8192 QualType SizeType = S.Context.getSizeType(); 8193 Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType)); 8194 8195 // Build 'size_t i$n = 0'. 8196 IdentifierInfo *IterationVarName = nullptr; 8197 { 8198 SmallString<8> Str; 8199 llvm::raw_svector_ostream OS(Str); 8200 OS << "i" << ArrayDepth; 8201 IterationVarName = &S.Context.Idents.get(OS.str()); 8202 } 8203 VarDecl *IterationVar = VarDecl::Create( 8204 S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType, 8205 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None); 8206 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 8207 IterationVar->setInit( 8208 IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 8209 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc); 8210 8211 auto IterRef = [&] { 8212 ExprResult Ref = S.BuildDeclarationNameExpr( 8213 CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc), 8214 IterationVar); 8215 assert(!Ref.isInvalid() && "can't reference our own variable?"); 8216 return Ref.get(); 8217 }; 8218 8219 // Build 'i$n != Size'. 8220 ExprResult Cond = S.CreateBuiltinBinOp( 8221 Loc, BO_NE, IterRef(), 8222 IntegerLiteral::Create(S.Context, Size, SizeType, Loc)); 8223 assert(!Cond.isInvalid() && "should never fail"); 8224 8225 // Build '++i$n'. 8226 ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef()); 8227 assert(!Inc.isInvalid() && "should never fail"); 8228 8229 // Build 'a[i$n]' and 'b[i$n]'. 8230 auto Index = [&](ExprResult E) { 8231 if (E.isInvalid()) 8232 return ExprError(); 8233 return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc); 8234 }; 8235 Subobj.first = Index(Subobj.first); 8236 Subobj.second = Index(Subobj.second); 8237 8238 // Compare the array elements. 8239 ++ArrayDepth; 8240 StmtResult Substmt = visitSubobject(Type, Subobj); 8241 --ArrayDepth; 8242 8243 if (Substmt.isInvalid()) 8244 return StmtError(); 8245 8246 // For the inner level of an 'operator==', build 'if (!cmp) return false;'. 8247 // For outer levels or for an 'operator<=>' we already have a suitable 8248 // statement that returns as necessary. 8249 if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) { 8250 assert(DCK == DefaultedComparisonKind::Equal && 8251 "should have non-expression statement"); 8252 Substmt = buildIfNotCondReturnFalse(ElemCmp); 8253 if (Substmt.isInvalid()) 8254 return StmtError(); 8255 } 8256 8257 // Build 'for (...) ...' 8258 return S.ActOnForStmt(Loc, Loc, Init, 8259 S.ActOnCondition(nullptr, Loc, Cond.get(), 8260 Sema::ConditionKind::Boolean), 8261 S.MakeFullDiscardedValueExpr(Inc.get()), Loc, 8262 Substmt.get()); 8263 } 8264 8265 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) { 8266 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 8267 return StmtError(); 8268 8269 OverloadedOperatorKind OO = FD->getOverloadedOperator(); 8270 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO); 8271 ExprResult Op; 8272 if (Type->isOverloadableType()) 8273 Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(), 8274 Obj.second.get(), /*PerformADL=*/true, 8275 /*AllowRewrittenCandidates=*/true, FD); 8276 else 8277 Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get()); 8278 if (Op.isInvalid()) 8279 return StmtError(); 8280 8281 switch (DCK) { 8282 case DefaultedComparisonKind::None: 8283 llvm_unreachable("not a defaulted comparison"); 8284 8285 case DefaultedComparisonKind::Equal: 8286 // Per C++2a [class.eq]p2, each comparison is individually contextually 8287 // converted to bool. 8288 Op = S.PerformContextuallyConvertToBool(Op.get()); 8289 if (Op.isInvalid()) 8290 return StmtError(); 8291 return Op.get(); 8292 8293 case DefaultedComparisonKind::ThreeWay: { 8294 // Per C++2a [class.spaceship]p3, form: 8295 // if (R cmp = static_cast<R>(op); cmp != 0) 8296 // return cmp; 8297 QualType R = FD->getReturnType(); 8298 Op = buildStaticCastToR(Op.get()); 8299 if (Op.isInvalid()) 8300 return StmtError(); 8301 8302 // R cmp = ...; 8303 IdentifierInfo *Name = &S.Context.Idents.get("cmp"); 8304 VarDecl *VD = 8305 VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R, 8306 S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None); 8307 S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false); 8308 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc); 8309 8310 // cmp != 0 8311 ExprResult VDRef = getDecl(VD); 8312 if (VDRef.isInvalid()) 8313 return StmtError(); 8314 llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0); 8315 Expr *Zero = 8316 IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc); 8317 ExprResult Comp; 8318 if (VDRef.get()->getType()->isOverloadableType()) 8319 Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true, 8320 true, FD); 8321 else 8322 Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero); 8323 if (Comp.isInvalid()) 8324 return StmtError(); 8325 Sema::ConditionResult Cond = S.ActOnCondition( 8326 nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean); 8327 if (Cond.isInvalid()) 8328 return StmtError(); 8329 8330 // return cmp; 8331 VDRef = getDecl(VD); 8332 if (VDRef.isInvalid()) 8333 return StmtError(); 8334 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get()); 8335 if (ReturnStmt.isInvalid()) 8336 return StmtError(); 8337 8338 // if (...) 8339 return S.ActOnIfStmt(Loc, /*IsConstexpr=*/false, Loc, InitStmt, Cond, Loc, 8340 ReturnStmt.get(), 8341 /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr); 8342 } 8343 8344 case DefaultedComparisonKind::NotEqual: 8345 case DefaultedComparisonKind::Relational: 8346 // C++2a [class.compare.secondary]p2: 8347 // Otherwise, the operator function yields x @ y. 8348 return Op.get(); 8349 } 8350 llvm_unreachable(""); 8351 } 8352 8353 /// Build "static_cast<R>(E)". 8354 ExprResult buildStaticCastToR(Expr *E) { 8355 QualType R = FD->getReturnType(); 8356 assert(!R->isUndeducedType() && "type should have been deduced already"); 8357 8358 // Don't bother forming a no-op cast in the common case. 8359 if (E->isPRValue() && S.Context.hasSameType(E->getType(), R)) 8360 return E; 8361 return S.BuildCXXNamedCast(Loc, tok::kw_static_cast, 8362 S.Context.getTrivialTypeSourceInfo(R, Loc), E, 8363 SourceRange(Loc, Loc), SourceRange(Loc, Loc)); 8364 } 8365 }; 8366 } 8367 8368 /// Perform the unqualified lookups that might be needed to form a defaulted 8369 /// comparison function for the given operator. 8370 static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S, 8371 UnresolvedSetImpl &Operators, 8372 OverloadedOperatorKind Op) { 8373 auto Lookup = [&](OverloadedOperatorKind OO) { 8374 Self.LookupOverloadedOperatorName(OO, S, Operators); 8375 }; 8376 8377 // Every defaulted operator looks up itself. 8378 Lookup(Op); 8379 // ... and the rewritten form of itself, if any. 8380 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op)) 8381 Lookup(ExtraOp); 8382 8383 // For 'operator<=>', we also form a 'cmp != 0' expression, and might 8384 // synthesize a three-way comparison from '<' and '=='. In a dependent 8385 // context, we also need to look up '==' in case we implicitly declare a 8386 // defaulted 'operator=='. 8387 if (Op == OO_Spaceship) { 8388 Lookup(OO_ExclaimEqual); 8389 Lookup(OO_Less); 8390 Lookup(OO_EqualEqual); 8391 } 8392 } 8393 8394 bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD, 8395 DefaultedComparisonKind DCK) { 8396 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison"); 8397 8398 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()); 8399 assert(RD && "defaulted comparison is not defaulted in a class"); 8400 8401 // Perform any unqualified lookups we're going to need to default this 8402 // function. 8403 if (S) { 8404 UnresolvedSet<32> Operators; 8405 lookupOperatorsForDefaultedComparison(*this, S, Operators, 8406 FD->getOverloadedOperator()); 8407 FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create( 8408 Context, Operators.pairs())); 8409 } 8410 8411 // C++2a [class.compare.default]p1: 8412 // A defaulted comparison operator function for some class C shall be a 8413 // non-template function declared in the member-specification of C that is 8414 // -- a non-static const member of C having one parameter of type 8415 // const C&, or 8416 // -- a friend of C having two parameters of type const C& or two 8417 // parameters of type C. 8418 QualType ExpectedParmType1 = Context.getRecordType(RD); 8419 QualType ExpectedParmType2 = 8420 Context.getLValueReferenceType(ExpectedParmType1.withConst()); 8421 if (isa<CXXMethodDecl>(FD)) 8422 ExpectedParmType1 = ExpectedParmType2; 8423 for (const ParmVarDecl *Param : FD->parameters()) { 8424 if (!Param->getType()->isDependentType() && 8425 !Context.hasSameType(Param->getType(), ExpectedParmType1) && 8426 !Context.hasSameType(Param->getType(), ExpectedParmType2)) { 8427 // Don't diagnose an implicit 'operator=='; we will have diagnosed the 8428 // corresponding defaulted 'operator<=>' already. 8429 if (!FD->isImplicit()) { 8430 Diag(FD->getLocation(), diag::err_defaulted_comparison_param) 8431 << (int)DCK << Param->getType() << ExpectedParmType1 8432 << !isa<CXXMethodDecl>(FD) 8433 << ExpectedParmType2 << Param->getSourceRange(); 8434 } 8435 return true; 8436 } 8437 } 8438 if (FD->getNumParams() == 2 && 8439 !Context.hasSameType(FD->getParamDecl(0)->getType(), 8440 FD->getParamDecl(1)->getType())) { 8441 if (!FD->isImplicit()) { 8442 Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch) 8443 << (int)DCK 8444 << FD->getParamDecl(0)->getType() 8445 << FD->getParamDecl(0)->getSourceRange() 8446 << FD->getParamDecl(1)->getType() 8447 << FD->getParamDecl(1)->getSourceRange(); 8448 } 8449 return true; 8450 } 8451 8452 // ... non-static const member ... 8453 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 8454 assert(!MD->isStatic() && "comparison function cannot be a static member"); 8455 if (!MD->isConst()) { 8456 SourceLocation InsertLoc; 8457 if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc()) 8458 InsertLoc = getLocForEndOfToken(Loc.getRParenLoc()); 8459 // Don't diagnose an implicit 'operator=='; we will have diagnosed the 8460 // corresponding defaulted 'operator<=>' already. 8461 if (!MD->isImplicit()) { 8462 Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const) 8463 << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const"); 8464 } 8465 8466 // Add the 'const' to the type to recover. 8467 const auto *FPT = MD->getType()->castAs<FunctionProtoType>(); 8468 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8469 EPI.TypeQuals.addConst(); 8470 MD->setType(Context.getFunctionType(FPT->getReturnType(), 8471 FPT->getParamTypes(), EPI)); 8472 } 8473 } else { 8474 // A non-member function declared in a class must be a friend. 8475 assert(FD->getFriendObjectKind() && "expected a friend declaration"); 8476 } 8477 8478 // C++2a [class.eq]p1, [class.rel]p1: 8479 // A [defaulted comparison other than <=>] shall have a declared return 8480 // type bool. 8481 if (DCK != DefaultedComparisonKind::ThreeWay && 8482 !FD->getDeclaredReturnType()->isDependentType() && 8483 !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) { 8484 Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool) 8485 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy 8486 << FD->getReturnTypeSourceRange(); 8487 return true; 8488 } 8489 // C++2a [class.spaceship]p2 [P2002R0]: 8490 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise, 8491 // R shall not contain a placeholder type. 8492 if (DCK == DefaultedComparisonKind::ThreeWay && 8493 FD->getDeclaredReturnType()->getContainedDeducedType() && 8494 !Context.hasSameType(FD->getDeclaredReturnType(), 8495 Context.getAutoDeductType())) { 8496 Diag(FD->getLocation(), 8497 diag::err_defaulted_comparison_deduced_return_type_not_auto) 8498 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy 8499 << FD->getReturnTypeSourceRange(); 8500 return true; 8501 } 8502 8503 // For a defaulted function in a dependent class, defer all remaining checks 8504 // until instantiation. 8505 if (RD->isDependentType()) 8506 return false; 8507 8508 // Determine whether the function should be defined as deleted. 8509 DefaultedComparisonInfo Info = 8510 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit(); 8511 8512 bool First = FD == FD->getCanonicalDecl(); 8513 8514 // If we want to delete the function, then do so; there's nothing else to 8515 // check in that case. 8516 if (Info.Deleted) { 8517 if (!First) { 8518 // C++11 [dcl.fct.def.default]p4: 8519 // [For a] user-provided explicitly-defaulted function [...] if such a 8520 // function is implicitly defined as deleted, the program is ill-formed. 8521 // 8522 // This is really just a consequence of the general rule that you can 8523 // only delete a function on its first declaration. 8524 Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes) 8525 << FD->isImplicit() << (int)DCK; 8526 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8527 DefaultedComparisonAnalyzer::ExplainDeleted) 8528 .visit(); 8529 return true; 8530 } 8531 8532 SetDeclDeleted(FD, FD->getLocation()); 8533 if (!inTemplateInstantiation() && !FD->isImplicit()) { 8534 Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted) 8535 << (int)DCK; 8536 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8537 DefaultedComparisonAnalyzer::ExplainDeleted) 8538 .visit(); 8539 } 8540 return false; 8541 } 8542 8543 // C++2a [class.spaceship]p2: 8544 // The return type is deduced as the common comparison type of R0, R1, ... 8545 if (DCK == DefaultedComparisonKind::ThreeWay && 8546 FD->getDeclaredReturnType()->isUndeducedAutoType()) { 8547 SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin(); 8548 if (RetLoc.isInvalid()) 8549 RetLoc = FD->getBeginLoc(); 8550 // FIXME: Should we really care whether we have the complete type and the 8551 // 'enumerator' constants here? A forward declaration seems sufficient. 8552 QualType Cat = CheckComparisonCategoryType( 8553 Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator); 8554 if (Cat.isNull()) 8555 return true; 8556 Context.adjustDeducedFunctionResultType( 8557 FD, SubstAutoType(FD->getDeclaredReturnType(), Cat)); 8558 } 8559 8560 // C++2a [dcl.fct.def.default]p3 [P2002R0]: 8561 // An explicitly-defaulted function that is not defined as deleted may be 8562 // declared constexpr or consteval only if it is constexpr-compatible. 8563 // C++2a [class.compare.default]p3 [P2002R0]: 8564 // A defaulted comparison function is constexpr-compatible if it satisfies 8565 // the requirements for a constexpr function [...] 8566 // The only relevant requirements are that the parameter and return types are 8567 // literal types. The remaining conditions are checked by the analyzer. 8568 if (FD->isConstexpr()) { 8569 if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) && 8570 CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) && 8571 !Info.Constexpr) { 8572 Diag(FD->getBeginLoc(), 8573 diag::err_incorrect_defaulted_comparison_constexpr) 8574 << FD->isImplicit() << (int)DCK << FD->isConsteval(); 8575 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8576 DefaultedComparisonAnalyzer::ExplainConstexpr) 8577 .visit(); 8578 } 8579 } 8580 8581 // C++2a [dcl.fct.def.default]p3 [P2002R0]: 8582 // If a constexpr-compatible function is explicitly defaulted on its first 8583 // declaration, it is implicitly considered to be constexpr. 8584 // FIXME: Only applying this to the first declaration seems problematic, as 8585 // simple reorderings can affect the meaning of the program. 8586 if (First && !FD->isConstexpr() && Info.Constexpr) 8587 FD->setConstexprKind(ConstexprSpecKind::Constexpr); 8588 8589 // C++2a [except.spec]p3: 8590 // If a declaration of a function does not have a noexcept-specifier 8591 // [and] is defaulted on its first declaration, [...] the exception 8592 // specification is as specified below 8593 if (FD->getExceptionSpecType() == EST_None) { 8594 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 8595 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8596 EPI.ExceptionSpec.Type = EST_Unevaluated; 8597 EPI.ExceptionSpec.SourceDecl = FD; 8598 FD->setType(Context.getFunctionType(FPT->getReturnType(), 8599 FPT->getParamTypes(), EPI)); 8600 } 8601 8602 return false; 8603 } 8604 8605 void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD, 8606 FunctionDecl *Spaceship) { 8607 Sema::CodeSynthesisContext Ctx; 8608 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison; 8609 Ctx.PointOfInstantiation = Spaceship->getEndLoc(); 8610 Ctx.Entity = Spaceship; 8611 pushCodeSynthesisContext(Ctx); 8612 8613 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship)) 8614 EqualEqual->setImplicit(); 8615 8616 popCodeSynthesisContext(); 8617 } 8618 8619 void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD, 8620 DefaultedComparisonKind DCK) { 8621 assert(FD->isDefaulted() && !FD->isDeleted() && 8622 !FD->doesThisDeclarationHaveABody()); 8623 if (FD->willHaveBody() || FD->isInvalidDecl()) 8624 return; 8625 8626 SynthesizedFunctionScope Scope(*this, FD); 8627 8628 // Add a context note for diagnostics produced after this point. 8629 Scope.addContextNote(UseLoc); 8630 8631 { 8632 // Build and set up the function body. 8633 CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent()); 8634 SourceLocation BodyLoc = 8635 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation(); 8636 StmtResult Body = 8637 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build(); 8638 if (Body.isInvalid()) { 8639 FD->setInvalidDecl(); 8640 return; 8641 } 8642 FD->setBody(Body.get()); 8643 FD->markUsed(Context); 8644 } 8645 8646 // The exception specification is needed because we are defining the 8647 // function. Note that this will reuse the body we just built. 8648 ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>()); 8649 8650 if (ASTMutationListener *L = getASTMutationListener()) 8651 L->CompletedImplicitDefinition(FD); 8652 } 8653 8654 static Sema::ImplicitExceptionSpecification 8655 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, 8656 FunctionDecl *FD, 8657 Sema::DefaultedComparisonKind DCK) { 8658 ComputingExceptionSpec CES(S, FD, Loc); 8659 Sema::ImplicitExceptionSpecification ExceptSpec(S); 8660 8661 if (FD->isInvalidDecl()) 8662 return ExceptSpec; 8663 8664 // The common case is that we just defined the comparison function. In that 8665 // case, just look at whether the body can throw. 8666 if (FD->hasBody()) { 8667 ExceptSpec.CalledStmt(FD->getBody()); 8668 } else { 8669 // Otherwise, build a body so we can check it. This should ideally only 8670 // happen when we're not actually marking the function referenced. (This is 8671 // only really important for efficiency: we don't want to build and throw 8672 // away bodies for comparison functions more than we strictly need to.) 8673 8674 // Pretend to synthesize the function body in an unevaluated context. 8675 // Note that we can't actually just go ahead and define the function here: 8676 // we are not permitted to mark its callees as referenced. 8677 Sema::SynthesizedFunctionScope Scope(S, FD); 8678 EnterExpressionEvaluationContext Context( 8679 S, Sema::ExpressionEvaluationContext::Unevaluated); 8680 8681 CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent()); 8682 SourceLocation BodyLoc = 8683 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation(); 8684 StmtResult Body = 8685 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build(); 8686 if (!Body.isInvalid()) 8687 ExceptSpec.CalledStmt(Body.get()); 8688 8689 // FIXME: Can we hold onto this body and just transform it to potentially 8690 // evaluated when we're asked to define the function rather than rebuilding 8691 // it? Either that, or we should only build the bits of the body that we 8692 // need (the expressions, not the statements). 8693 } 8694 8695 return ExceptSpec; 8696 } 8697 8698 void Sema::CheckDelayedMemberExceptionSpecs() { 8699 decltype(DelayedOverridingExceptionSpecChecks) Overriding; 8700 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent; 8701 8702 std::swap(Overriding, DelayedOverridingExceptionSpecChecks); 8703 std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks); 8704 8705 // Perform any deferred checking of exception specifications for virtual 8706 // destructors. 8707 for (auto &Check : Overriding) 8708 CheckOverridingFunctionExceptionSpec(Check.first, Check.second); 8709 8710 // Perform any deferred checking of exception specifications for befriended 8711 // special members. 8712 for (auto &Check : Equivalent) 8713 CheckEquivalentExceptionSpec(Check.second, Check.first); 8714 } 8715 8716 namespace { 8717 /// CRTP base class for visiting operations performed by a special member 8718 /// function (or inherited constructor). 8719 template<typename Derived> 8720 struct SpecialMemberVisitor { 8721 Sema &S; 8722 CXXMethodDecl *MD; 8723 Sema::CXXSpecialMember CSM; 8724 Sema::InheritedConstructorInfo *ICI; 8725 8726 // Properties of the special member, computed for convenience. 8727 bool IsConstructor = false, IsAssignment = false, ConstArg = false; 8728 8729 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 8730 Sema::InheritedConstructorInfo *ICI) 8731 : S(S), MD(MD), CSM(CSM), ICI(ICI) { 8732 switch (CSM) { 8733 case Sema::CXXDefaultConstructor: 8734 case Sema::CXXCopyConstructor: 8735 case Sema::CXXMoveConstructor: 8736 IsConstructor = true; 8737 break; 8738 case Sema::CXXCopyAssignment: 8739 case Sema::CXXMoveAssignment: 8740 IsAssignment = true; 8741 break; 8742 case Sema::CXXDestructor: 8743 break; 8744 case Sema::CXXInvalid: 8745 llvm_unreachable("invalid special member kind"); 8746 } 8747 8748 if (MD->getNumParams()) { 8749 if (const ReferenceType *RT = 8750 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 8751 ConstArg = RT->getPointeeType().isConstQualified(); 8752 } 8753 } 8754 8755 Derived &getDerived() { return static_cast<Derived&>(*this); } 8756 8757 /// Is this a "move" special member? 8758 bool isMove() const { 8759 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment; 8760 } 8761 8762 /// Look up the corresponding special member in the given class. 8763 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class, 8764 unsigned Quals, bool IsMutable) { 8765 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 8766 ConstArg && !IsMutable); 8767 } 8768 8769 /// Look up the constructor for the specified base class to see if it's 8770 /// overridden due to this being an inherited constructor. 8771 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) { 8772 if (!ICI) 8773 return {}; 8774 assert(CSM == Sema::CXXDefaultConstructor); 8775 auto *BaseCtor = 8776 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor(); 8777 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first) 8778 return MD; 8779 return {}; 8780 } 8781 8782 /// A base or member subobject. 8783 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 8784 8785 /// Get the location to use for a subobject in diagnostics. 8786 static SourceLocation getSubobjectLoc(Subobject Subobj) { 8787 // FIXME: For an indirect virtual base, the direct base leading to 8788 // the indirect virtual base would be a more useful choice. 8789 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>()) 8790 return B->getBaseTypeLoc(); 8791 else 8792 return Subobj.get<FieldDecl*>()->getLocation(); 8793 } 8794 8795 enum BasesToVisit { 8796 /// Visit all non-virtual (direct) bases. 8797 VisitNonVirtualBases, 8798 /// Visit all direct bases, virtual or not. 8799 VisitDirectBases, 8800 /// Visit all non-virtual bases, and all virtual bases if the class 8801 /// is not abstract. 8802 VisitPotentiallyConstructedBases, 8803 /// Visit all direct or virtual bases. 8804 VisitAllBases 8805 }; 8806 8807 // Visit the bases and members of the class. 8808 bool visit(BasesToVisit Bases) { 8809 CXXRecordDecl *RD = MD->getParent(); 8810 8811 if (Bases == VisitPotentiallyConstructedBases) 8812 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases; 8813 8814 for (auto &B : RD->bases()) 8815 if ((Bases == VisitDirectBases || !B.isVirtual()) && 8816 getDerived().visitBase(&B)) 8817 return true; 8818 8819 if (Bases == VisitAllBases) 8820 for (auto &B : RD->vbases()) 8821 if (getDerived().visitBase(&B)) 8822 return true; 8823 8824 for (auto *F : RD->fields()) 8825 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() && 8826 getDerived().visitField(F)) 8827 return true; 8828 8829 return false; 8830 } 8831 }; 8832 } 8833 8834 namespace { 8835 struct SpecialMemberDeletionInfo 8836 : SpecialMemberVisitor<SpecialMemberDeletionInfo> { 8837 bool Diagnose; 8838 8839 SourceLocation Loc; 8840 8841 bool AllFieldsAreConst; 8842 8843 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 8844 Sema::CXXSpecialMember CSM, 8845 Sema::InheritedConstructorInfo *ICI, bool Diagnose) 8846 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose), 8847 Loc(MD->getLocation()), AllFieldsAreConst(true) {} 8848 8849 bool inUnion() const { return MD->getParent()->isUnion(); } 8850 8851 Sema::CXXSpecialMember getEffectiveCSM() { 8852 return ICI ? Sema::CXXInvalid : CSM; 8853 } 8854 8855 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType); 8856 8857 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); } 8858 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); } 8859 8860 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 8861 bool shouldDeleteForField(FieldDecl *FD); 8862 bool shouldDeleteForAllConstMembers(); 8863 8864 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 8865 unsigned Quals); 8866 bool shouldDeleteForSubobjectCall(Subobject Subobj, 8867 Sema::SpecialMemberOverloadResult SMOR, 8868 bool IsDtorCallInCtor); 8869 8870 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 8871 }; 8872 } 8873 8874 /// Is the given special member inaccessible when used on the given 8875 /// sub-object. 8876 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 8877 CXXMethodDecl *target) { 8878 /// If we're operating on a base class, the object type is the 8879 /// type of this special member. 8880 QualType objectTy; 8881 AccessSpecifier access = target->getAccess(); 8882 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 8883 objectTy = S.Context.getTypeDeclType(MD->getParent()); 8884 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 8885 8886 // If we're operating on a field, the object type is the type of the field. 8887 } else { 8888 objectTy = S.Context.getTypeDeclType(target->getParent()); 8889 } 8890 8891 return S.isMemberAccessibleForDeletion( 8892 target->getParent(), DeclAccessPair::make(target, access), objectTy); 8893 } 8894 8895 /// Check whether we should delete a special member due to the implicit 8896 /// definition containing a call to a special member of a subobject. 8897 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 8898 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR, 8899 bool IsDtorCallInCtor) { 8900 CXXMethodDecl *Decl = SMOR.getMethod(); 8901 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 8902 8903 int DiagKind = -1; 8904 8905 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 8906 DiagKind = !Decl ? 0 : 1; 8907 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 8908 DiagKind = 2; 8909 else if (!isAccessible(Subobj, Decl)) 8910 DiagKind = 3; 8911 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 8912 !Decl->isTrivial()) { 8913 // A member of a union must have a trivial corresponding special member. 8914 // As a weird special case, a destructor call from a union's constructor 8915 // must be accessible and non-deleted, but need not be trivial. Such a 8916 // destructor is never actually called, but is semantically checked as 8917 // if it were. 8918 DiagKind = 4; 8919 } 8920 8921 if (DiagKind == -1) 8922 return false; 8923 8924 if (Diagnose) { 8925 if (Field) { 8926 S.Diag(Field->getLocation(), 8927 diag::note_deleted_special_member_class_subobject) 8928 << getEffectiveCSM() << MD->getParent() << /*IsField*/true 8929 << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false; 8930 } else { 8931 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 8932 S.Diag(Base->getBeginLoc(), 8933 diag::note_deleted_special_member_class_subobject) 8934 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 8935 << Base->getType() << DiagKind << IsDtorCallInCtor 8936 << /*IsObjCPtr*/false; 8937 } 8938 8939 if (DiagKind == 1) 8940 S.NoteDeletedFunction(Decl); 8941 // FIXME: Explain inaccessibility if DiagKind == 3. 8942 } 8943 8944 return true; 8945 } 8946 8947 /// Check whether we should delete a special member function due to having a 8948 /// direct or virtual base class or non-static data member of class type M. 8949 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 8950 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 8951 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 8952 bool IsMutable = Field && Field->isMutable(); 8953 8954 // C++11 [class.ctor]p5: 8955 // -- any direct or virtual base class, or non-static data member with no 8956 // brace-or-equal-initializer, has class type M (or array thereof) and 8957 // either M has no default constructor or overload resolution as applied 8958 // to M's default constructor results in an ambiguity or in a function 8959 // that is deleted or inaccessible 8960 // C++11 [class.copy]p11, C++11 [class.copy]p23: 8961 // -- a direct or virtual base class B that cannot be copied/moved because 8962 // overload resolution, as applied to B's corresponding special member, 8963 // results in an ambiguity or a function that is deleted or inaccessible 8964 // from the defaulted special member 8965 // C++11 [class.dtor]p5: 8966 // -- any direct or virtual base class [...] has a type with a destructor 8967 // that is deleted or inaccessible 8968 if (!(CSM == Sema::CXXDefaultConstructor && 8969 Field && Field->hasInClassInitializer()) && 8970 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 8971 false)) 8972 return true; 8973 8974 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 8975 // -- any direct or virtual base class or non-static data member has a 8976 // type with a destructor that is deleted or inaccessible 8977 if (IsConstructor) { 8978 Sema::SpecialMemberOverloadResult SMOR = 8979 S.LookupSpecialMember(Class, Sema::CXXDestructor, 8980 false, false, false, false, false); 8981 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 8982 return true; 8983 } 8984 8985 return false; 8986 } 8987 8988 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember( 8989 FieldDecl *FD, QualType FieldType) { 8990 // The defaulted special functions are defined as deleted if this is a variant 8991 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak 8992 // type under ARC. 8993 if (!FieldType.hasNonTrivialObjCLifetime()) 8994 return false; 8995 8996 // Don't make the defaulted default constructor defined as deleted if the 8997 // member has an in-class initializer. 8998 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) 8999 return false; 9000 9001 if (Diagnose) { 9002 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent()); 9003 S.Diag(FD->getLocation(), 9004 diag::note_deleted_special_member_class_subobject) 9005 << getEffectiveCSM() << ParentClass << /*IsField*/true 9006 << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true; 9007 } 9008 9009 return true; 9010 } 9011 9012 /// Check whether we should delete a special member function due to the class 9013 /// having a particular direct or virtual base class. 9014 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 9015 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 9016 // If program is correct, BaseClass cannot be null, but if it is, the error 9017 // must be reported elsewhere. 9018 if (!BaseClass) 9019 return false; 9020 // If we have an inheriting constructor, check whether we're calling an 9021 // inherited constructor instead of a default constructor. 9022 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 9023 if (auto *BaseCtor = SMOR.getMethod()) { 9024 // Note that we do not check access along this path; other than that, 9025 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false); 9026 // FIXME: Check that the base has a usable destructor! Sink this into 9027 // shouldDeleteForClassSubobject. 9028 if (BaseCtor->isDeleted() && Diagnose) { 9029 S.Diag(Base->getBeginLoc(), 9030 diag::note_deleted_special_member_class_subobject) 9031 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 9032 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false 9033 << /*IsObjCPtr*/false; 9034 S.NoteDeletedFunction(BaseCtor); 9035 } 9036 return BaseCtor->isDeleted(); 9037 } 9038 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 9039 } 9040 9041 /// Check whether we should delete a special member function due to the class 9042 /// having a particular non-static data member. 9043 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 9044 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 9045 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 9046 9047 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType)) 9048 return true; 9049 9050 if (CSM == Sema::CXXDefaultConstructor) { 9051 // For a default constructor, all references must be initialized in-class 9052 // and, if a union, it must have a non-const member. 9053 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 9054 if (Diagnose) 9055 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 9056 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0; 9057 return true; 9058 } 9059 // C++11 [class.ctor]p5: any non-variant non-static data member of 9060 // const-qualified type (or array thereof) with no 9061 // brace-or-equal-initializer does not have a user-provided default 9062 // constructor. 9063 if (!inUnion() && FieldType.isConstQualified() && 9064 !FD->hasInClassInitializer() && 9065 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 9066 if (Diagnose) 9067 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 9068 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1; 9069 return true; 9070 } 9071 9072 if (inUnion() && !FieldType.isConstQualified()) 9073 AllFieldsAreConst = false; 9074 } else if (CSM == Sema::CXXCopyConstructor) { 9075 // For a copy constructor, data members must not be of rvalue reference 9076 // type. 9077 if (FieldType->isRValueReferenceType()) { 9078 if (Diagnose) 9079 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 9080 << MD->getParent() << FD << FieldType; 9081 return true; 9082 } 9083 } else if (IsAssignment) { 9084 // For an assignment operator, data members must not be of reference type. 9085 if (FieldType->isReferenceType()) { 9086 if (Diagnose) 9087 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 9088 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0; 9089 return true; 9090 } 9091 if (!FieldRecord && FieldType.isConstQualified()) { 9092 // C++11 [class.copy]p23: 9093 // -- a non-static data member of const non-class type (or array thereof) 9094 if (Diagnose) 9095 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 9096 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1; 9097 return true; 9098 } 9099 } 9100 9101 if (FieldRecord) { 9102 // Some additional restrictions exist on the variant members. 9103 if (!inUnion() && FieldRecord->isUnion() && 9104 FieldRecord->isAnonymousStructOrUnion()) { 9105 bool AllVariantFieldsAreConst = true; 9106 9107 // FIXME: Handle anonymous unions declared within anonymous unions. 9108 for (auto *UI : FieldRecord->fields()) { 9109 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 9110 9111 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType)) 9112 return true; 9113 9114 if (!UnionFieldType.isConstQualified()) 9115 AllVariantFieldsAreConst = false; 9116 9117 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 9118 if (UnionFieldRecord && 9119 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 9120 UnionFieldType.getCVRQualifiers())) 9121 return true; 9122 } 9123 9124 // At least one member in each anonymous union must be non-const 9125 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 9126 !FieldRecord->field_empty()) { 9127 if (Diagnose) 9128 S.Diag(FieldRecord->getLocation(), 9129 diag::note_deleted_default_ctor_all_const) 9130 << !!ICI << MD->getParent() << /*anonymous union*/1; 9131 return true; 9132 } 9133 9134 // Don't check the implicit member of the anonymous union type. 9135 // This is technically non-conformant, but sanity demands it. 9136 return false; 9137 } 9138 9139 if (shouldDeleteForClassSubobject(FieldRecord, FD, 9140 FieldType.getCVRQualifiers())) 9141 return true; 9142 } 9143 9144 return false; 9145 } 9146 9147 /// C++11 [class.ctor] p5: 9148 /// A defaulted default constructor for a class X is defined as deleted if 9149 /// X is a union and all of its variant members are of const-qualified type. 9150 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 9151 // This is a silly definition, because it gives an empty union a deleted 9152 // default constructor. Don't do that. 9153 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) { 9154 bool AnyFields = false; 9155 for (auto *F : MD->getParent()->fields()) 9156 if ((AnyFields = !F->isUnnamedBitfield())) 9157 break; 9158 if (!AnyFields) 9159 return false; 9160 if (Diagnose) 9161 S.Diag(MD->getParent()->getLocation(), 9162 diag::note_deleted_default_ctor_all_const) 9163 << !!ICI << MD->getParent() << /*not anonymous union*/0; 9164 return true; 9165 } 9166 return false; 9167 } 9168 9169 /// Determine whether a defaulted special member function should be defined as 9170 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 9171 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 9172 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 9173 InheritedConstructorInfo *ICI, 9174 bool Diagnose) { 9175 if (MD->isInvalidDecl()) 9176 return false; 9177 CXXRecordDecl *RD = MD->getParent(); 9178 assert(!RD->isDependentType() && "do deletion after instantiation"); 9179 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 9180 return false; 9181 9182 // C++11 [expr.lambda.prim]p19: 9183 // The closure type associated with a lambda-expression has a 9184 // deleted (8.4.3) default constructor and a deleted copy 9185 // assignment operator. 9186 // C++2a adds back these operators if the lambda has no lambda-capture. 9187 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() && 9188 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 9189 if (Diagnose) 9190 Diag(RD->getLocation(), diag::note_lambda_decl); 9191 return true; 9192 } 9193 9194 // For an anonymous struct or union, the copy and assignment special members 9195 // will never be used, so skip the check. For an anonymous union declared at 9196 // namespace scope, the constructor and destructor are used. 9197 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 9198 RD->isAnonymousStructOrUnion()) 9199 return false; 9200 9201 // C++11 [class.copy]p7, p18: 9202 // If the class definition declares a move constructor or move assignment 9203 // operator, an implicitly declared copy constructor or copy assignment 9204 // operator is defined as deleted. 9205 if (MD->isImplicit() && 9206 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 9207 CXXMethodDecl *UserDeclaredMove = nullptr; 9208 9209 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the 9210 // deletion of the corresponding copy operation, not both copy operations. 9211 // MSVC 2015 has adopted the standards conforming behavior. 9212 bool DeletesOnlyMatchingCopy = 9213 getLangOpts().MSVCCompat && 9214 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015); 9215 9216 if (RD->hasUserDeclaredMoveConstructor() && 9217 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) { 9218 if (!Diagnose) return true; 9219 9220 // Find any user-declared move constructor. 9221 for (auto *I : RD->ctors()) { 9222 if (I->isMoveConstructor()) { 9223 UserDeclaredMove = I; 9224 break; 9225 } 9226 } 9227 assert(UserDeclaredMove); 9228 } else if (RD->hasUserDeclaredMoveAssignment() && 9229 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) { 9230 if (!Diagnose) return true; 9231 9232 // Find any user-declared move assignment operator. 9233 for (auto *I : RD->methods()) { 9234 if (I->isMoveAssignmentOperator()) { 9235 UserDeclaredMove = I; 9236 break; 9237 } 9238 } 9239 assert(UserDeclaredMove); 9240 } 9241 9242 if (UserDeclaredMove) { 9243 Diag(UserDeclaredMove->getLocation(), 9244 diag::note_deleted_copy_user_declared_move) 9245 << (CSM == CXXCopyAssignment) << RD 9246 << UserDeclaredMove->isMoveAssignmentOperator(); 9247 return true; 9248 } 9249 } 9250 9251 // Do access control from the special member function 9252 ContextRAII MethodContext(*this, MD); 9253 9254 // C++11 [class.dtor]p5: 9255 // -- for a virtual destructor, lookup of the non-array deallocation function 9256 // results in an ambiguity or in a function that is deleted or inaccessible 9257 if (CSM == CXXDestructor && MD->isVirtual()) { 9258 FunctionDecl *OperatorDelete = nullptr; 9259 DeclarationName Name = 9260 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 9261 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 9262 OperatorDelete, /*Diagnose*/false)) { 9263 if (Diagnose) 9264 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 9265 return true; 9266 } 9267 } 9268 9269 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose); 9270 9271 // Per DR1611, do not consider virtual bases of constructors of abstract 9272 // classes, since we are not going to construct them. 9273 // Per DR1658, do not consider virtual bases of destructors of abstract 9274 // classes either. 9275 // Per DR2180, for assignment operators we only assign (and thus only 9276 // consider) direct bases. 9277 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases 9278 : SMI.VisitPotentiallyConstructedBases)) 9279 return true; 9280 9281 if (SMI.shouldDeleteForAllConstMembers()) 9282 return true; 9283 9284 if (getLangOpts().CUDA) { 9285 // We should delete the special member in CUDA mode if target inference 9286 // failed. 9287 // For inherited constructors (non-null ICI), CSM may be passed so that MD 9288 // is treated as certain special member, which may not reflect what special 9289 // member MD really is. However inferCUDATargetForImplicitSpecialMember 9290 // expects CSM to match MD, therefore recalculate CSM. 9291 assert(ICI || CSM == getSpecialMember(MD)); 9292 auto RealCSM = CSM; 9293 if (ICI) 9294 RealCSM = getSpecialMember(MD); 9295 9296 return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD, 9297 SMI.ConstArg, Diagnose); 9298 } 9299 9300 return false; 9301 } 9302 9303 void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) { 9304 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD); 9305 assert(DFK && "not a defaultable function"); 9306 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted"); 9307 9308 if (DFK.isSpecialMember()) { 9309 ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), 9310 nullptr, /*Diagnose=*/true); 9311 } else { 9312 DefaultedComparisonAnalyzer( 9313 *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD, 9314 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted) 9315 .visit(); 9316 } 9317 } 9318 9319 /// Perform lookup for a special member of the specified kind, and determine 9320 /// whether it is trivial. If the triviality can be determined without the 9321 /// lookup, skip it. This is intended for use when determining whether a 9322 /// special member of a containing object is trivial, and thus does not ever 9323 /// perform overload resolution for default constructors. 9324 /// 9325 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 9326 /// member that was most likely to be intended to be trivial, if any. 9327 /// 9328 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to 9329 /// determine whether the special member is trivial. 9330 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 9331 Sema::CXXSpecialMember CSM, unsigned Quals, 9332 bool ConstRHS, 9333 Sema::TrivialABIHandling TAH, 9334 CXXMethodDecl **Selected) { 9335 if (Selected) 9336 *Selected = nullptr; 9337 9338 switch (CSM) { 9339 case Sema::CXXInvalid: 9340 llvm_unreachable("not a special member"); 9341 9342 case Sema::CXXDefaultConstructor: 9343 // C++11 [class.ctor]p5: 9344 // A default constructor is trivial if: 9345 // - all the [direct subobjects] have trivial default constructors 9346 // 9347 // Note, no overload resolution is performed in this case. 9348 if (RD->hasTrivialDefaultConstructor()) 9349 return true; 9350 9351 if (Selected) { 9352 // If there's a default constructor which could have been trivial, dig it 9353 // out. Otherwise, if there's any user-provided default constructor, point 9354 // to that as an example of why there's not a trivial one. 9355 CXXConstructorDecl *DefCtor = nullptr; 9356 if (RD->needsImplicitDefaultConstructor()) 9357 S.DeclareImplicitDefaultConstructor(RD); 9358 for (auto *CI : RD->ctors()) { 9359 if (!CI->isDefaultConstructor()) 9360 continue; 9361 DefCtor = CI; 9362 if (!DefCtor->isUserProvided()) 9363 break; 9364 } 9365 9366 *Selected = DefCtor; 9367 } 9368 9369 return false; 9370 9371 case Sema::CXXDestructor: 9372 // C++11 [class.dtor]p5: 9373 // A destructor is trivial if: 9374 // - all the direct [subobjects] have trivial destructors 9375 if (RD->hasTrivialDestructor() || 9376 (TAH == Sema::TAH_ConsiderTrivialABI && 9377 RD->hasTrivialDestructorForCall())) 9378 return true; 9379 9380 if (Selected) { 9381 if (RD->needsImplicitDestructor()) 9382 S.DeclareImplicitDestructor(RD); 9383 *Selected = RD->getDestructor(); 9384 } 9385 9386 return false; 9387 9388 case Sema::CXXCopyConstructor: 9389 // C++11 [class.copy]p12: 9390 // A copy constructor is trivial if: 9391 // - the constructor selected to copy each direct [subobject] is trivial 9392 if (RD->hasTrivialCopyConstructor() || 9393 (TAH == Sema::TAH_ConsiderTrivialABI && 9394 RD->hasTrivialCopyConstructorForCall())) { 9395 if (Quals == Qualifiers::Const) 9396 // We must either select the trivial copy constructor or reach an 9397 // ambiguity; no need to actually perform overload resolution. 9398 return true; 9399 } else if (!Selected) { 9400 return false; 9401 } 9402 // In C++98, we are not supposed to perform overload resolution here, but we 9403 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 9404 // cases like B as having a non-trivial copy constructor: 9405 // struct A { template<typename T> A(T&); }; 9406 // struct B { mutable A a; }; 9407 goto NeedOverloadResolution; 9408 9409 case Sema::CXXCopyAssignment: 9410 // C++11 [class.copy]p25: 9411 // A copy assignment operator is trivial if: 9412 // - the assignment operator selected to copy each direct [subobject] is 9413 // trivial 9414 if (RD->hasTrivialCopyAssignment()) { 9415 if (Quals == Qualifiers::Const) 9416 return true; 9417 } else if (!Selected) { 9418 return false; 9419 } 9420 // In C++98, we are not supposed to perform overload resolution here, but we 9421 // treat that as a language defect. 9422 goto NeedOverloadResolution; 9423 9424 case Sema::CXXMoveConstructor: 9425 case Sema::CXXMoveAssignment: 9426 NeedOverloadResolution: 9427 Sema::SpecialMemberOverloadResult SMOR = 9428 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 9429 9430 // The standard doesn't describe how to behave if the lookup is ambiguous. 9431 // We treat it as not making the member non-trivial, just like the standard 9432 // mandates for the default constructor. This should rarely matter, because 9433 // the member will also be deleted. 9434 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 9435 return true; 9436 9437 if (!SMOR.getMethod()) { 9438 assert(SMOR.getKind() == 9439 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 9440 return false; 9441 } 9442 9443 // We deliberately don't check if we found a deleted special member. We're 9444 // not supposed to! 9445 if (Selected) 9446 *Selected = SMOR.getMethod(); 9447 9448 if (TAH == Sema::TAH_ConsiderTrivialABI && 9449 (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor)) 9450 return SMOR.getMethod()->isTrivialForCall(); 9451 return SMOR.getMethod()->isTrivial(); 9452 } 9453 9454 llvm_unreachable("unknown special method kind"); 9455 } 9456 9457 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 9458 for (auto *CI : RD->ctors()) 9459 if (!CI->isImplicit()) 9460 return CI; 9461 9462 // Look for constructor templates. 9463 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 9464 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 9465 if (CXXConstructorDecl *CD = 9466 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 9467 return CD; 9468 } 9469 9470 return nullptr; 9471 } 9472 9473 /// The kind of subobject we are checking for triviality. The values of this 9474 /// enumeration are used in diagnostics. 9475 enum TrivialSubobjectKind { 9476 /// The subobject is a base class. 9477 TSK_BaseClass, 9478 /// The subobject is a non-static data member. 9479 TSK_Field, 9480 /// The object is actually the complete object. 9481 TSK_CompleteObject 9482 }; 9483 9484 /// Check whether the special member selected for a given type would be trivial. 9485 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 9486 QualType SubType, bool ConstRHS, 9487 Sema::CXXSpecialMember CSM, 9488 TrivialSubobjectKind Kind, 9489 Sema::TrivialABIHandling TAH, bool Diagnose) { 9490 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 9491 if (!SubRD) 9492 return true; 9493 9494 CXXMethodDecl *Selected; 9495 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 9496 ConstRHS, TAH, Diagnose ? &Selected : nullptr)) 9497 return true; 9498 9499 if (Diagnose) { 9500 if (ConstRHS) 9501 SubType.addConst(); 9502 9503 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 9504 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 9505 << Kind << SubType.getUnqualifiedType(); 9506 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 9507 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 9508 } else if (!Selected) 9509 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 9510 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 9511 else if (Selected->isUserProvided()) { 9512 if (Kind == TSK_CompleteObject) 9513 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 9514 << Kind << SubType.getUnqualifiedType() << CSM; 9515 else { 9516 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 9517 << Kind << SubType.getUnqualifiedType() << CSM; 9518 S.Diag(Selected->getLocation(), diag::note_declared_at); 9519 } 9520 } else { 9521 if (Kind != TSK_CompleteObject) 9522 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 9523 << Kind << SubType.getUnqualifiedType() << CSM; 9524 9525 // Explain why the defaulted or deleted special member isn't trivial. 9526 S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI, 9527 Diagnose); 9528 } 9529 } 9530 9531 return false; 9532 } 9533 9534 /// Check whether the members of a class type allow a special member to be 9535 /// trivial. 9536 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 9537 Sema::CXXSpecialMember CSM, 9538 bool ConstArg, 9539 Sema::TrivialABIHandling TAH, 9540 bool Diagnose) { 9541 for (const auto *FI : RD->fields()) { 9542 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 9543 continue; 9544 9545 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 9546 9547 // Pretend anonymous struct or union members are members of this class. 9548 if (FI->isAnonymousStructOrUnion()) { 9549 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 9550 CSM, ConstArg, TAH, Diagnose)) 9551 return false; 9552 continue; 9553 } 9554 9555 // C++11 [class.ctor]p5: 9556 // A default constructor is trivial if [...] 9557 // -- no non-static data member of its class has a 9558 // brace-or-equal-initializer 9559 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 9560 if (Diagnose) 9561 S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init) 9562 << FI; 9563 return false; 9564 } 9565 9566 // Objective C ARC 4.3.5: 9567 // [...] nontrivally ownership-qualified types are [...] not trivially 9568 // default constructible, copy constructible, move constructible, copy 9569 // assignable, move assignable, or destructible [...] 9570 if (FieldType.hasNonTrivialObjCLifetime()) { 9571 if (Diagnose) 9572 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 9573 << RD << FieldType.getObjCLifetime(); 9574 return false; 9575 } 9576 9577 bool ConstRHS = ConstArg && !FI->isMutable(); 9578 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 9579 CSM, TSK_Field, TAH, Diagnose)) 9580 return false; 9581 } 9582 9583 return true; 9584 } 9585 9586 /// Diagnose why the specified class does not have a trivial special member of 9587 /// the given kind. 9588 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 9589 QualType Ty = Context.getRecordType(RD); 9590 9591 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 9592 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 9593 TSK_CompleteObject, TAH_IgnoreTrivialABI, 9594 /*Diagnose*/true); 9595 } 9596 9597 /// Determine whether a defaulted or deleted special member function is trivial, 9598 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 9599 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 9600 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 9601 TrivialABIHandling TAH, bool Diagnose) { 9602 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 9603 9604 CXXRecordDecl *RD = MD->getParent(); 9605 9606 bool ConstArg = false; 9607 9608 // C++11 [class.copy]p12, p25: [DR1593] 9609 // A [special member] is trivial if [...] its parameter-type-list is 9610 // equivalent to the parameter-type-list of an implicit declaration [...] 9611 switch (CSM) { 9612 case CXXDefaultConstructor: 9613 case CXXDestructor: 9614 // Trivial default constructors and destructors cannot have parameters. 9615 break; 9616 9617 case CXXCopyConstructor: 9618 case CXXCopyAssignment: { 9619 // Trivial copy operations always have const, non-volatile parameter types. 9620 ConstArg = true; 9621 const ParmVarDecl *Param0 = MD->getParamDecl(0); 9622 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 9623 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 9624 if (Diagnose) 9625 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 9626 << Param0->getSourceRange() << Param0->getType() 9627 << Context.getLValueReferenceType( 9628 Context.getRecordType(RD).withConst()); 9629 return false; 9630 } 9631 break; 9632 } 9633 9634 case CXXMoveConstructor: 9635 case CXXMoveAssignment: { 9636 // Trivial move operations always have non-cv-qualified parameters. 9637 const ParmVarDecl *Param0 = MD->getParamDecl(0); 9638 const RValueReferenceType *RT = 9639 Param0->getType()->getAs<RValueReferenceType>(); 9640 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 9641 if (Diagnose) 9642 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 9643 << Param0->getSourceRange() << Param0->getType() 9644 << Context.getRValueReferenceType(Context.getRecordType(RD)); 9645 return false; 9646 } 9647 break; 9648 } 9649 9650 case CXXInvalid: 9651 llvm_unreachable("not a special member"); 9652 } 9653 9654 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 9655 if (Diagnose) 9656 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 9657 diag::note_nontrivial_default_arg) 9658 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 9659 return false; 9660 } 9661 if (MD->isVariadic()) { 9662 if (Diagnose) 9663 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 9664 return false; 9665 } 9666 9667 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 9668 // A copy/move [constructor or assignment operator] is trivial if 9669 // -- the [member] selected to copy/move each direct base class subobject 9670 // is trivial 9671 // 9672 // C++11 [class.copy]p12, C++11 [class.copy]p25: 9673 // A [default constructor or destructor] is trivial if 9674 // -- all the direct base classes have trivial [default constructors or 9675 // destructors] 9676 for (const auto &BI : RD->bases()) 9677 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(), 9678 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose)) 9679 return false; 9680 9681 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 9682 // A copy/move [constructor or assignment operator] for a class X is 9683 // trivial if 9684 // -- for each non-static data member of X that is of class type (or array 9685 // thereof), the constructor selected to copy/move that member is 9686 // trivial 9687 // 9688 // C++11 [class.copy]p12, C++11 [class.copy]p25: 9689 // A [default constructor or destructor] is trivial if 9690 // -- for all of the non-static data members of its class that are of class 9691 // type (or array thereof), each such class has a trivial [default 9692 // constructor or destructor] 9693 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose)) 9694 return false; 9695 9696 // C++11 [class.dtor]p5: 9697 // A destructor is trivial if [...] 9698 // -- the destructor is not virtual 9699 if (CSM == CXXDestructor && MD->isVirtual()) { 9700 if (Diagnose) 9701 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 9702 return false; 9703 } 9704 9705 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 9706 // A [special member] for class X is trivial if [...] 9707 // -- class X has no virtual functions and no virtual base classes 9708 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 9709 if (!Diagnose) 9710 return false; 9711 9712 if (RD->getNumVBases()) { 9713 // Check for virtual bases. We already know that the corresponding 9714 // member in all bases is trivial, so vbases must all be direct. 9715 CXXBaseSpecifier &BS = *RD->vbases_begin(); 9716 assert(BS.isVirtual()); 9717 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1; 9718 return false; 9719 } 9720 9721 // Must have a virtual method. 9722 for (const auto *MI : RD->methods()) { 9723 if (MI->isVirtual()) { 9724 SourceLocation MLoc = MI->getBeginLoc(); 9725 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 9726 return false; 9727 } 9728 } 9729 9730 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 9731 } 9732 9733 // Looks like it's trivial! 9734 return true; 9735 } 9736 9737 namespace { 9738 struct FindHiddenVirtualMethod { 9739 Sema *S; 9740 CXXMethodDecl *Method; 9741 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 9742 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 9743 9744 private: 9745 /// Check whether any most overridden method from MD in Methods 9746 static bool CheckMostOverridenMethods( 9747 const CXXMethodDecl *MD, 9748 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) { 9749 if (MD->size_overridden_methods() == 0) 9750 return Methods.count(MD->getCanonicalDecl()); 9751 for (const CXXMethodDecl *O : MD->overridden_methods()) 9752 if (CheckMostOverridenMethods(O, Methods)) 9753 return true; 9754 return false; 9755 } 9756 9757 public: 9758 /// Member lookup function that determines whether a given C++ 9759 /// method overloads virtual methods in a base class without overriding any, 9760 /// to be used with CXXRecordDecl::lookupInBases(). 9761 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 9762 RecordDecl *BaseRecord = 9763 Specifier->getType()->castAs<RecordType>()->getDecl(); 9764 9765 DeclarationName Name = Method->getDeclName(); 9766 assert(Name.getNameKind() == DeclarationName::Identifier); 9767 9768 bool foundSameNameMethod = false; 9769 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 9770 for (Path.Decls = BaseRecord->lookup(Name).begin(); 9771 Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) { 9772 NamedDecl *D = *Path.Decls; 9773 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 9774 MD = MD->getCanonicalDecl(); 9775 foundSameNameMethod = true; 9776 // Interested only in hidden virtual methods. 9777 if (!MD->isVirtual()) 9778 continue; 9779 // If the method we are checking overrides a method from its base 9780 // don't warn about the other overloaded methods. Clang deviates from 9781 // GCC by only diagnosing overloads of inherited virtual functions that 9782 // do not override any other virtual functions in the base. GCC's 9783 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 9784 // function from a base class. These cases may be better served by a 9785 // warning (not specific to virtual functions) on call sites when the 9786 // call would select a different function from the base class, were it 9787 // visible. 9788 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 9789 if (!S->IsOverload(Method, MD, false)) 9790 return true; 9791 // Collect the overload only if its hidden. 9792 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods)) 9793 overloadedMethods.push_back(MD); 9794 } 9795 } 9796 9797 if (foundSameNameMethod) 9798 OverloadedMethods.append(overloadedMethods.begin(), 9799 overloadedMethods.end()); 9800 return foundSameNameMethod; 9801 } 9802 }; 9803 } // end anonymous namespace 9804 9805 /// Add the most overriden methods from MD to Methods 9806 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 9807 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 9808 if (MD->size_overridden_methods() == 0) 9809 Methods.insert(MD->getCanonicalDecl()); 9810 else 9811 for (const CXXMethodDecl *O : MD->overridden_methods()) 9812 AddMostOverridenMethods(O, Methods); 9813 } 9814 9815 /// Check if a method overloads virtual methods in a base class without 9816 /// overriding any. 9817 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 9818 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 9819 if (!MD->getDeclName().isIdentifier()) 9820 return; 9821 9822 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 9823 /*bool RecordPaths=*/false, 9824 /*bool DetectVirtual=*/false); 9825 FindHiddenVirtualMethod FHVM; 9826 FHVM.Method = MD; 9827 FHVM.S = this; 9828 9829 // Keep the base methods that were overridden or introduced in the subclass 9830 // by 'using' in a set. A base method not in this set is hidden. 9831 CXXRecordDecl *DC = MD->getParent(); 9832 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 9833 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 9834 NamedDecl *ND = *I; 9835 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 9836 ND = shad->getTargetDecl(); 9837 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 9838 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods); 9839 } 9840 9841 if (DC->lookupInBases(FHVM, Paths)) 9842 OverloadedMethods = FHVM.OverloadedMethods; 9843 } 9844 9845 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 9846 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 9847 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 9848 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 9849 PartialDiagnostic PD = PDiag( 9850 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 9851 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 9852 Diag(overloadedMD->getLocation(), PD); 9853 } 9854 } 9855 9856 /// Diagnose methods which overload virtual methods in a base class 9857 /// without overriding any. 9858 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 9859 if (MD->isInvalidDecl()) 9860 return; 9861 9862 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 9863 return; 9864 9865 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 9866 FindHiddenVirtualMethods(MD, OverloadedMethods); 9867 if (!OverloadedMethods.empty()) { 9868 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 9869 << MD << (OverloadedMethods.size() > 1); 9870 9871 NoteHiddenVirtualMethods(MD, OverloadedMethods); 9872 } 9873 } 9874 9875 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) { 9876 auto PrintDiagAndRemoveAttr = [&](unsigned N) { 9877 // No diagnostics if this is a template instantiation. 9878 if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) { 9879 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), 9880 diag::ext_cannot_use_trivial_abi) << &RD; 9881 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), 9882 diag::note_cannot_use_trivial_abi_reason) << &RD << N; 9883 } 9884 RD.dropAttr<TrivialABIAttr>(); 9885 }; 9886 9887 // Ill-formed if the copy and move constructors are deleted. 9888 auto HasNonDeletedCopyOrMoveConstructor = [&]() { 9889 // If the type is dependent, then assume it might have 9890 // implicit copy or move ctor because we won't know yet at this point. 9891 if (RD.isDependentType()) 9892 return true; 9893 if (RD.needsImplicitCopyConstructor() && 9894 !RD.defaultedCopyConstructorIsDeleted()) 9895 return true; 9896 if (RD.needsImplicitMoveConstructor() && 9897 !RD.defaultedMoveConstructorIsDeleted()) 9898 return true; 9899 for (const CXXConstructorDecl *CD : RD.ctors()) 9900 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted()) 9901 return true; 9902 return false; 9903 }; 9904 9905 if (!HasNonDeletedCopyOrMoveConstructor()) { 9906 PrintDiagAndRemoveAttr(0); 9907 return; 9908 } 9909 9910 // Ill-formed if the struct has virtual functions. 9911 if (RD.isPolymorphic()) { 9912 PrintDiagAndRemoveAttr(1); 9913 return; 9914 } 9915 9916 for (const auto &B : RD.bases()) { 9917 // Ill-formed if the base class is non-trivial for the purpose of calls or a 9918 // virtual base. 9919 if (!B.getType()->isDependentType() && 9920 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) { 9921 PrintDiagAndRemoveAttr(2); 9922 return; 9923 } 9924 9925 if (B.isVirtual()) { 9926 PrintDiagAndRemoveAttr(3); 9927 return; 9928 } 9929 } 9930 9931 for (const auto *FD : RD.fields()) { 9932 // Ill-formed if the field is an ObjectiveC pointer or of a type that is 9933 // non-trivial for the purpose of calls. 9934 QualType FT = FD->getType(); 9935 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) { 9936 PrintDiagAndRemoveAttr(4); 9937 return; 9938 } 9939 9940 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>()) 9941 if (!RT->isDependentType() && 9942 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) { 9943 PrintDiagAndRemoveAttr(5); 9944 return; 9945 } 9946 } 9947 } 9948 9949 void Sema::ActOnFinishCXXMemberSpecification( 9950 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, 9951 SourceLocation RBrac, const ParsedAttributesView &AttrList) { 9952 if (!TagDecl) 9953 return; 9954 9955 AdjustDeclIfTemplate(TagDecl); 9956 9957 for (const ParsedAttr &AL : AttrList) { 9958 if (AL.getKind() != ParsedAttr::AT_Visibility) 9959 continue; 9960 AL.setInvalid(); 9961 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL; 9962 } 9963 9964 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 9965 // strict aliasing violation! 9966 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 9967 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 9968 9969 CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl)); 9970 } 9971 9972 /// Find the equality comparison functions that should be implicitly declared 9973 /// in a given class definition, per C++2a [class.compare.default]p3. 9974 static void findImplicitlyDeclaredEqualityComparisons( 9975 ASTContext &Ctx, CXXRecordDecl *RD, 9976 llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) { 9977 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual); 9978 if (!RD->lookup(EqEq).empty()) 9979 // Member operator== explicitly declared: no implicit operator==s. 9980 return; 9981 9982 // Traverse friends looking for an '==' or a '<=>'. 9983 for (FriendDecl *Friend : RD->friends()) { 9984 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl()); 9985 if (!FD) continue; 9986 9987 if (FD->getOverloadedOperator() == OO_EqualEqual) { 9988 // Friend operator== explicitly declared: no implicit operator==s. 9989 Spaceships.clear(); 9990 return; 9991 } 9992 9993 if (FD->getOverloadedOperator() == OO_Spaceship && 9994 FD->isExplicitlyDefaulted()) 9995 Spaceships.push_back(FD); 9996 } 9997 9998 // Look for members named 'operator<=>'. 9999 DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship); 10000 for (NamedDecl *ND : RD->lookup(Cmp)) { 10001 // Note that we could find a non-function here (either a function template 10002 // or a using-declaration). Neither case results in an implicit 10003 // 'operator=='. 10004 if (auto *FD = dyn_cast<FunctionDecl>(ND)) 10005 if (FD->isExplicitlyDefaulted()) 10006 Spaceships.push_back(FD); 10007 } 10008 } 10009 10010 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 10011 /// special functions, such as the default constructor, copy 10012 /// constructor, or destructor, to the given C++ class (C++ 10013 /// [special]p1). This routine can only be executed just before the 10014 /// definition of the class is complete. 10015 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 10016 // Don't add implicit special members to templated classes. 10017 // FIXME: This means unqualified lookups for 'operator=' within a class 10018 // template don't work properly. 10019 if (!ClassDecl->isDependentType()) { 10020 if (ClassDecl->needsImplicitDefaultConstructor()) { 10021 ++getASTContext().NumImplicitDefaultConstructors; 10022 10023 if (ClassDecl->hasInheritedConstructor()) 10024 DeclareImplicitDefaultConstructor(ClassDecl); 10025 } 10026 10027 if (ClassDecl->needsImplicitCopyConstructor()) { 10028 ++getASTContext().NumImplicitCopyConstructors; 10029 10030 // If the properties or semantics of the copy constructor couldn't be 10031 // determined while the class was being declared, force a declaration 10032 // of it now. 10033 if (ClassDecl->needsOverloadResolutionForCopyConstructor() || 10034 ClassDecl->hasInheritedConstructor()) 10035 DeclareImplicitCopyConstructor(ClassDecl); 10036 // For the MS ABI we need to know whether the copy ctor is deleted. A 10037 // prerequisite for deleting the implicit copy ctor is that the class has 10038 // a move ctor or move assignment that is either user-declared or whose 10039 // semantics are inherited from a subobject. FIXME: We should provide a 10040 // more direct way for CodeGen to ask whether the constructor was deleted. 10041 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 10042 (ClassDecl->hasUserDeclaredMoveConstructor() || 10043 ClassDecl->needsOverloadResolutionForMoveConstructor() || 10044 ClassDecl->hasUserDeclaredMoveAssignment() || 10045 ClassDecl->needsOverloadResolutionForMoveAssignment())) 10046 DeclareImplicitCopyConstructor(ClassDecl); 10047 } 10048 10049 if (getLangOpts().CPlusPlus11 && 10050 ClassDecl->needsImplicitMoveConstructor()) { 10051 ++getASTContext().NumImplicitMoveConstructors; 10052 10053 if (ClassDecl->needsOverloadResolutionForMoveConstructor() || 10054 ClassDecl->hasInheritedConstructor()) 10055 DeclareImplicitMoveConstructor(ClassDecl); 10056 } 10057 10058 if (ClassDecl->needsImplicitCopyAssignment()) { 10059 ++getASTContext().NumImplicitCopyAssignmentOperators; 10060 10061 // If we have a dynamic class, then the copy assignment operator may be 10062 // virtual, so we have to declare it immediately. This ensures that, e.g., 10063 // it shows up in the right place in the vtable and that we diagnose 10064 // problems with the implicit exception specification. 10065 if (ClassDecl->isDynamicClass() || 10066 ClassDecl->needsOverloadResolutionForCopyAssignment() || 10067 ClassDecl->hasInheritedAssignment()) 10068 DeclareImplicitCopyAssignment(ClassDecl); 10069 } 10070 10071 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 10072 ++getASTContext().NumImplicitMoveAssignmentOperators; 10073 10074 // Likewise for the move assignment operator. 10075 if (ClassDecl->isDynamicClass() || 10076 ClassDecl->needsOverloadResolutionForMoveAssignment() || 10077 ClassDecl->hasInheritedAssignment()) 10078 DeclareImplicitMoveAssignment(ClassDecl); 10079 } 10080 10081 if (ClassDecl->needsImplicitDestructor()) { 10082 ++getASTContext().NumImplicitDestructors; 10083 10084 // If we have a dynamic class, then the destructor may be virtual, so we 10085 // have to declare the destructor immediately. This ensures that, e.g., it 10086 // shows up in the right place in the vtable and that we diagnose problems 10087 // with the implicit exception specification. 10088 if (ClassDecl->isDynamicClass() || 10089 ClassDecl->needsOverloadResolutionForDestructor()) 10090 DeclareImplicitDestructor(ClassDecl); 10091 } 10092 } 10093 10094 // C++2a [class.compare.default]p3: 10095 // If the member-specification does not explicitly declare any member or 10096 // friend named operator==, an == operator function is declared implicitly 10097 // for each defaulted three-way comparison operator function defined in 10098 // the member-specification 10099 // FIXME: Consider doing this lazily. 10100 // We do this during the initial parse for a class template, not during 10101 // instantiation, so that we can handle unqualified lookups for 'operator==' 10102 // when parsing the template. 10103 if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) { 10104 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships; 10105 findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl, 10106 DefaultedSpaceships); 10107 for (auto *FD : DefaultedSpaceships) 10108 DeclareImplicitEqualityComparison(ClassDecl, FD); 10109 } 10110 } 10111 10112 unsigned 10113 Sema::ActOnReenterTemplateScope(Decl *D, 10114 llvm::function_ref<Scope *()> EnterScope) { 10115 if (!D) 10116 return 0; 10117 AdjustDeclIfTemplate(D); 10118 10119 // In order to get name lookup right, reenter template scopes in order from 10120 // outermost to innermost. 10121 SmallVector<TemplateParameterList *, 4> ParameterLists; 10122 DeclContext *LookupDC = dyn_cast<DeclContext>(D); 10123 10124 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 10125 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 10126 ParameterLists.push_back(DD->getTemplateParameterList(i)); 10127 10128 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 10129 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 10130 ParameterLists.push_back(FTD->getTemplateParameters()); 10131 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 10132 LookupDC = VD->getDeclContext(); 10133 10134 if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate()) 10135 ParameterLists.push_back(VTD->getTemplateParameters()); 10136 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D)) 10137 ParameterLists.push_back(PSD->getTemplateParameters()); 10138 } 10139 } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 10140 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 10141 ParameterLists.push_back(TD->getTemplateParameterList(i)); 10142 10143 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 10144 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 10145 ParameterLists.push_back(CTD->getTemplateParameters()); 10146 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 10147 ParameterLists.push_back(PSD->getTemplateParameters()); 10148 } 10149 } 10150 // FIXME: Alias declarations and concepts. 10151 10152 unsigned Count = 0; 10153 Scope *InnermostTemplateScope = nullptr; 10154 for (TemplateParameterList *Params : ParameterLists) { 10155 // Ignore explicit specializations; they don't contribute to the template 10156 // depth. 10157 if (Params->size() == 0) 10158 continue; 10159 10160 InnermostTemplateScope = EnterScope(); 10161 for (NamedDecl *Param : *Params) { 10162 if (Param->getDeclName()) { 10163 InnermostTemplateScope->AddDecl(Param); 10164 IdResolver.AddDecl(Param); 10165 } 10166 } 10167 ++Count; 10168 } 10169 10170 // Associate the new template scopes with the corresponding entities. 10171 if (InnermostTemplateScope) { 10172 assert(LookupDC && "no enclosing DeclContext for template lookup"); 10173 EnterTemplatedContext(InnermostTemplateScope, LookupDC); 10174 } 10175 10176 return Count; 10177 } 10178 10179 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 10180 if (!RecordD) return; 10181 AdjustDeclIfTemplate(RecordD); 10182 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 10183 PushDeclContext(S, Record); 10184 } 10185 10186 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 10187 if (!RecordD) return; 10188 PopDeclContext(); 10189 } 10190 10191 /// This is used to implement the constant expression evaluation part of the 10192 /// attribute enable_if extension. There is nothing in standard C++ which would 10193 /// require reentering parameters. 10194 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 10195 if (!Param) 10196 return; 10197 10198 S->AddDecl(Param); 10199 if (Param->getDeclName()) 10200 IdResolver.AddDecl(Param); 10201 } 10202 10203 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 10204 /// parsing a top-level (non-nested) C++ class, and we are now 10205 /// parsing those parts of the given Method declaration that could 10206 /// not be parsed earlier (C++ [class.mem]p2), such as default 10207 /// arguments. This action should enter the scope of the given 10208 /// Method declaration as if we had just parsed the qualified method 10209 /// name. However, it should not bring the parameters into scope; 10210 /// that will be performed by ActOnDelayedCXXMethodParameter. 10211 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 10212 } 10213 10214 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 10215 /// C++ method declaration. We're (re-)introducing the given 10216 /// function parameter into scope for use in parsing later parts of 10217 /// the method declaration. For example, we could see an 10218 /// ActOnParamDefaultArgument event for this parameter. 10219 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 10220 if (!ParamD) 10221 return; 10222 10223 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 10224 10225 S->AddDecl(Param); 10226 if (Param->getDeclName()) 10227 IdResolver.AddDecl(Param); 10228 } 10229 10230 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 10231 /// processing the delayed method declaration for Method. The method 10232 /// declaration is now considered finished. There may be a separate 10233 /// ActOnStartOfFunctionDef action later (not necessarily 10234 /// immediately!) for this method, if it was also defined inside the 10235 /// class body. 10236 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 10237 if (!MethodD) 10238 return; 10239 10240 AdjustDeclIfTemplate(MethodD); 10241 10242 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 10243 10244 // Now that we have our default arguments, check the constructor 10245 // again. It could produce additional diagnostics or affect whether 10246 // the class has implicitly-declared destructors, among other 10247 // things. 10248 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 10249 CheckConstructor(Constructor); 10250 10251 // Check the default arguments, which we may have added. 10252 if (!Method->isInvalidDecl()) 10253 CheckCXXDefaultArguments(Method); 10254 } 10255 10256 // Emit the given diagnostic for each non-address-space qualifier. 10257 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator. 10258 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) { 10259 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10260 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) { 10261 bool DiagOccured = false; 10262 FTI.MethodQualifiers->forEachQualifier( 10263 [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName, 10264 SourceLocation SL) { 10265 // This diagnostic should be emitted on any qualifier except an addr 10266 // space qualifier. However, forEachQualifier currently doesn't visit 10267 // addr space qualifiers, so there's no way to write this condition 10268 // right now; we just diagnose on everything. 10269 S.Diag(SL, DiagID) << QualName << SourceRange(SL); 10270 DiagOccured = true; 10271 }); 10272 if (DiagOccured) 10273 D.setInvalidType(); 10274 } 10275 } 10276 10277 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 10278 /// the well-formedness of the constructor declarator @p D with type @p 10279 /// R. If there are any errors in the declarator, this routine will 10280 /// emit diagnostics and set the invalid bit to true. In any case, the type 10281 /// will be updated to reflect a well-formed type for the constructor and 10282 /// returned. 10283 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 10284 StorageClass &SC) { 10285 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 10286 10287 // C++ [class.ctor]p3: 10288 // A constructor shall not be virtual (10.3) or static (9.4). A 10289 // constructor can be invoked for a const, volatile or const 10290 // volatile object. A constructor shall not be declared const, 10291 // volatile, or const volatile (9.3.2). 10292 if (isVirtual) { 10293 if (!D.isInvalidType()) 10294 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 10295 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 10296 << SourceRange(D.getIdentifierLoc()); 10297 D.setInvalidType(); 10298 } 10299 if (SC == SC_Static) { 10300 if (!D.isInvalidType()) 10301 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 10302 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10303 << SourceRange(D.getIdentifierLoc()); 10304 D.setInvalidType(); 10305 SC = SC_None; 10306 } 10307 10308 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 10309 diagnoseIgnoredQualifiers( 10310 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 10311 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 10312 D.getDeclSpec().getRestrictSpecLoc(), 10313 D.getDeclSpec().getAtomicSpecLoc()); 10314 D.setInvalidType(); 10315 } 10316 10317 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor); 10318 10319 // C++0x [class.ctor]p4: 10320 // A constructor shall not be declared with a ref-qualifier. 10321 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10322 if (FTI.hasRefQualifier()) { 10323 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 10324 << FTI.RefQualifierIsLValueRef 10325 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 10326 D.setInvalidType(); 10327 } 10328 10329 // Rebuild the function type "R" without any type qualifiers (in 10330 // case any of the errors above fired) and with "void" as the 10331 // return type, since constructors don't have return types. 10332 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>(); 10333 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 10334 return R; 10335 10336 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 10337 EPI.TypeQuals = Qualifiers(); 10338 EPI.RefQualifier = RQ_None; 10339 10340 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 10341 } 10342 10343 /// CheckConstructor - Checks a fully-formed constructor for 10344 /// well-formedness, issuing any diagnostics required. Returns true if 10345 /// the constructor declarator is invalid. 10346 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 10347 CXXRecordDecl *ClassDecl 10348 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 10349 if (!ClassDecl) 10350 return Constructor->setInvalidDecl(); 10351 10352 // C++ [class.copy]p3: 10353 // A declaration of a constructor for a class X is ill-formed if 10354 // its first parameter is of type (optionally cv-qualified) X and 10355 // either there are no other parameters or else all other 10356 // parameters have default arguments. 10357 if (!Constructor->isInvalidDecl() && 10358 Constructor->hasOneParamOrDefaultArgs() && 10359 Constructor->getTemplateSpecializationKind() != 10360 TSK_ImplicitInstantiation) { 10361 QualType ParamType = Constructor->getParamDecl(0)->getType(); 10362 QualType ClassTy = Context.getTagDeclType(ClassDecl); 10363 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 10364 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 10365 const char *ConstRef 10366 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 10367 : " const &"; 10368 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 10369 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 10370 10371 // FIXME: Rather that making the constructor invalid, we should endeavor 10372 // to fix the type. 10373 Constructor->setInvalidDecl(); 10374 } 10375 } 10376 } 10377 10378 /// CheckDestructor - Checks a fully-formed destructor definition for 10379 /// well-formedness, issuing any diagnostics required. Returns true 10380 /// on error. 10381 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 10382 CXXRecordDecl *RD = Destructor->getParent(); 10383 10384 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 10385 SourceLocation Loc; 10386 10387 if (!Destructor->isImplicit()) 10388 Loc = Destructor->getLocation(); 10389 else 10390 Loc = RD->getLocation(); 10391 10392 // If we have a virtual destructor, look up the deallocation function 10393 if (FunctionDecl *OperatorDelete = 10394 FindDeallocationFunctionForDestructor(Loc, RD)) { 10395 Expr *ThisArg = nullptr; 10396 10397 // If the notional 'delete this' expression requires a non-trivial 10398 // conversion from 'this' to the type of a destroying operator delete's 10399 // first parameter, perform that conversion now. 10400 if (OperatorDelete->isDestroyingOperatorDelete()) { 10401 QualType ParamType = OperatorDelete->getParamDecl(0)->getType(); 10402 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) { 10403 // C++ [class.dtor]p13: 10404 // ... as if for the expression 'delete this' appearing in a 10405 // non-virtual destructor of the destructor's class. 10406 ContextRAII SwitchContext(*this, Destructor); 10407 ExprResult This = 10408 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation()); 10409 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?"); 10410 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing); 10411 if (This.isInvalid()) { 10412 // FIXME: Register this as a context note so that it comes out 10413 // in the right order. 10414 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here); 10415 return true; 10416 } 10417 ThisArg = This.get(); 10418 } 10419 } 10420 10421 DiagnoseUseOfDecl(OperatorDelete, Loc); 10422 MarkFunctionReferenced(Loc, OperatorDelete); 10423 Destructor->setOperatorDelete(OperatorDelete, ThisArg); 10424 } 10425 } 10426 10427 return false; 10428 } 10429 10430 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 10431 /// the well-formednes of the destructor declarator @p D with type @p 10432 /// R. If there are any errors in the declarator, this routine will 10433 /// emit diagnostics and set the declarator to invalid. Even if this happens, 10434 /// will be updated to reflect a well-formed type for the destructor and 10435 /// returned. 10436 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 10437 StorageClass& SC) { 10438 // C++ [class.dtor]p1: 10439 // [...] A typedef-name that names a class is a class-name 10440 // (7.1.3); however, a typedef-name that names a class shall not 10441 // be used as the identifier in the declarator for a destructor 10442 // declaration. 10443 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 10444 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 10445 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name) 10446 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 10447 else if (const TemplateSpecializationType *TST = 10448 DeclaratorType->getAs<TemplateSpecializationType>()) 10449 if (TST->isTypeAlias()) 10450 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name) 10451 << DeclaratorType << 1; 10452 10453 // C++ [class.dtor]p2: 10454 // A destructor is used to destroy objects of its class type. A 10455 // destructor takes no parameters, and no return type can be 10456 // specified for it (not even void). The address of a destructor 10457 // shall not be taken. A destructor shall not be static. A 10458 // destructor can be invoked for a const, volatile or const 10459 // volatile object. A destructor shall not be declared const, 10460 // volatile or const volatile (9.3.2). 10461 if (SC == SC_Static) { 10462 if (!D.isInvalidType()) 10463 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 10464 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10465 << SourceRange(D.getIdentifierLoc()) 10466 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 10467 10468 SC = SC_None; 10469 } 10470 if (!D.isInvalidType()) { 10471 // Destructors don't have return types, but the parser will 10472 // happily parse something like: 10473 // 10474 // class X { 10475 // float ~X(); 10476 // }; 10477 // 10478 // The return type will be eliminated later. 10479 if (D.getDeclSpec().hasTypeSpecifier()) 10480 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 10481 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 10482 << SourceRange(D.getIdentifierLoc()); 10483 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 10484 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 10485 SourceLocation(), 10486 D.getDeclSpec().getConstSpecLoc(), 10487 D.getDeclSpec().getVolatileSpecLoc(), 10488 D.getDeclSpec().getRestrictSpecLoc(), 10489 D.getDeclSpec().getAtomicSpecLoc()); 10490 D.setInvalidType(); 10491 } 10492 } 10493 10494 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor); 10495 10496 // C++0x [class.dtor]p2: 10497 // A destructor shall not be declared with a ref-qualifier. 10498 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10499 if (FTI.hasRefQualifier()) { 10500 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 10501 << FTI.RefQualifierIsLValueRef 10502 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 10503 D.setInvalidType(); 10504 } 10505 10506 // Make sure we don't have any parameters. 10507 if (FTIHasNonVoidParameters(FTI)) { 10508 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 10509 10510 // Delete the parameters. 10511 FTI.freeParams(); 10512 D.setInvalidType(); 10513 } 10514 10515 // Make sure the destructor isn't variadic. 10516 if (FTI.isVariadic) { 10517 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 10518 D.setInvalidType(); 10519 } 10520 10521 // Rebuild the function type "R" without any type qualifiers or 10522 // parameters (in case any of the errors above fired) and with 10523 // "void" as the return type, since destructors don't have return 10524 // types. 10525 if (!D.isInvalidType()) 10526 return R; 10527 10528 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>(); 10529 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 10530 EPI.Variadic = false; 10531 EPI.TypeQuals = Qualifiers(); 10532 EPI.RefQualifier = RQ_None; 10533 return Context.getFunctionType(Context.VoidTy, None, EPI); 10534 } 10535 10536 static void extendLeft(SourceRange &R, SourceRange Before) { 10537 if (Before.isInvalid()) 10538 return; 10539 R.setBegin(Before.getBegin()); 10540 if (R.getEnd().isInvalid()) 10541 R.setEnd(Before.getEnd()); 10542 } 10543 10544 static void extendRight(SourceRange &R, SourceRange After) { 10545 if (After.isInvalid()) 10546 return; 10547 if (R.getBegin().isInvalid()) 10548 R.setBegin(After.getBegin()); 10549 R.setEnd(After.getEnd()); 10550 } 10551 10552 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 10553 /// well-formednes of the conversion function declarator @p D with 10554 /// type @p R. If there are any errors in the declarator, this routine 10555 /// will emit diagnostics and return true. Otherwise, it will return 10556 /// false. Either way, the type @p R will be updated to reflect a 10557 /// well-formed type for the conversion operator. 10558 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 10559 StorageClass& SC) { 10560 // C++ [class.conv.fct]p1: 10561 // Neither parameter types nor return type can be specified. The 10562 // type of a conversion function (8.3.5) is "function taking no 10563 // parameter returning conversion-type-id." 10564 if (SC == SC_Static) { 10565 if (!D.isInvalidType()) 10566 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 10567 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10568 << D.getName().getSourceRange(); 10569 D.setInvalidType(); 10570 SC = SC_None; 10571 } 10572 10573 TypeSourceInfo *ConvTSI = nullptr; 10574 QualType ConvType = 10575 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); 10576 10577 const DeclSpec &DS = D.getDeclSpec(); 10578 if (DS.hasTypeSpecifier() && !D.isInvalidType()) { 10579 // Conversion functions don't have return types, but the parser will 10580 // happily parse something like: 10581 // 10582 // class X { 10583 // float operator bool(); 10584 // }; 10585 // 10586 // The return type will be changed later anyway. 10587 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 10588 << SourceRange(DS.getTypeSpecTypeLoc()) 10589 << SourceRange(D.getIdentifierLoc()); 10590 D.setInvalidType(); 10591 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) { 10592 // It's also plausible that the user writes type qualifiers in the wrong 10593 // place, such as: 10594 // struct S { const operator int(); }; 10595 // FIXME: we could provide a fixit to move the qualifiers onto the 10596 // conversion type. 10597 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 10598 << SourceRange(D.getIdentifierLoc()) << 0; 10599 D.setInvalidType(); 10600 } 10601 10602 const auto *Proto = R->castAs<FunctionProtoType>(); 10603 10604 // Make sure we don't have any parameters. 10605 if (Proto->getNumParams() > 0) { 10606 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 10607 10608 // Delete the parameters. 10609 D.getFunctionTypeInfo().freeParams(); 10610 D.setInvalidType(); 10611 } else if (Proto->isVariadic()) { 10612 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 10613 D.setInvalidType(); 10614 } 10615 10616 // Diagnose "&operator bool()" and other such nonsense. This 10617 // is actually a gcc extension which we don't support. 10618 if (Proto->getReturnType() != ConvType) { 10619 bool NeedsTypedef = false; 10620 SourceRange Before, After; 10621 10622 // Walk the chunks and extract information on them for our diagnostic. 10623 bool PastFunctionChunk = false; 10624 for (auto &Chunk : D.type_objects()) { 10625 switch (Chunk.Kind) { 10626 case DeclaratorChunk::Function: 10627 if (!PastFunctionChunk) { 10628 if (Chunk.Fun.HasTrailingReturnType) { 10629 TypeSourceInfo *TRT = nullptr; 10630 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); 10631 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); 10632 } 10633 PastFunctionChunk = true; 10634 break; 10635 } 10636 LLVM_FALLTHROUGH; 10637 case DeclaratorChunk::Array: 10638 NeedsTypedef = true; 10639 extendRight(After, Chunk.getSourceRange()); 10640 break; 10641 10642 case DeclaratorChunk::Pointer: 10643 case DeclaratorChunk::BlockPointer: 10644 case DeclaratorChunk::Reference: 10645 case DeclaratorChunk::MemberPointer: 10646 case DeclaratorChunk::Pipe: 10647 extendLeft(Before, Chunk.getSourceRange()); 10648 break; 10649 10650 case DeclaratorChunk::Paren: 10651 extendLeft(Before, Chunk.Loc); 10652 extendRight(After, Chunk.EndLoc); 10653 break; 10654 } 10655 } 10656 10657 SourceLocation Loc = Before.isValid() ? Before.getBegin() : 10658 After.isValid() ? After.getBegin() : 10659 D.getIdentifierLoc(); 10660 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); 10661 DB << Before << After; 10662 10663 if (!NeedsTypedef) { 10664 DB << /*don't need a typedef*/0; 10665 10666 // If we can provide a correct fix-it hint, do so. 10667 if (After.isInvalid() && ConvTSI) { 10668 SourceLocation InsertLoc = 10669 getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc()); 10670 DB << FixItHint::CreateInsertion(InsertLoc, " ") 10671 << FixItHint::CreateInsertionFromRange( 10672 InsertLoc, CharSourceRange::getTokenRange(Before)) 10673 << FixItHint::CreateRemoval(Before); 10674 } 10675 } else if (!Proto->getReturnType()->isDependentType()) { 10676 DB << /*typedef*/1 << Proto->getReturnType(); 10677 } else if (getLangOpts().CPlusPlus11) { 10678 DB << /*alias template*/2 << Proto->getReturnType(); 10679 } else { 10680 DB << /*might not be fixable*/3; 10681 } 10682 10683 // Recover by incorporating the other type chunks into the result type. 10684 // Note, this does *not* change the name of the function. This is compatible 10685 // with the GCC extension: 10686 // struct S { &operator int(); } s; 10687 // int &r = s.operator int(); // ok in GCC 10688 // S::operator int&() {} // error in GCC, function name is 'operator int'. 10689 ConvType = Proto->getReturnType(); 10690 } 10691 10692 // C++ [class.conv.fct]p4: 10693 // The conversion-type-id shall not represent a function type nor 10694 // an array type. 10695 if (ConvType->isArrayType()) { 10696 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 10697 ConvType = Context.getPointerType(ConvType); 10698 D.setInvalidType(); 10699 } else if (ConvType->isFunctionType()) { 10700 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 10701 ConvType = Context.getPointerType(ConvType); 10702 D.setInvalidType(); 10703 } 10704 10705 // Rebuild the function type "R" without any parameters (in case any 10706 // of the errors above fired) and with the conversion type as the 10707 // return type. 10708 if (D.isInvalidType()) 10709 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 10710 10711 // C++0x explicit conversion operators. 10712 if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20) 10713 Diag(DS.getExplicitSpecLoc(), 10714 getLangOpts().CPlusPlus11 10715 ? diag::warn_cxx98_compat_explicit_conversion_functions 10716 : diag::ext_explicit_conversion_functions) 10717 << SourceRange(DS.getExplicitSpecRange()); 10718 } 10719 10720 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 10721 /// the declaration of the given C++ conversion function. This routine 10722 /// is responsible for recording the conversion function in the C++ 10723 /// class, if possible. 10724 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 10725 assert(Conversion && "Expected to receive a conversion function declaration"); 10726 10727 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 10728 10729 // Make sure we aren't redeclaring the conversion function. 10730 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 10731 // C++ [class.conv.fct]p1: 10732 // [...] A conversion function is never used to convert a 10733 // (possibly cv-qualified) object to the (possibly cv-qualified) 10734 // same object type (or a reference to it), to a (possibly 10735 // cv-qualified) base class of that type (or a reference to it), 10736 // or to (possibly cv-qualified) void. 10737 QualType ClassType 10738 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 10739 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 10740 ConvType = ConvTypeRef->getPointeeType(); 10741 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 10742 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 10743 /* Suppress diagnostics for instantiations. */; 10744 else if (Conversion->size_overridden_methods() != 0) 10745 /* Suppress diagnostics for overriding virtual function in a base class. */; 10746 else if (ConvType->isRecordType()) { 10747 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 10748 if (ConvType == ClassType) 10749 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 10750 << ClassType; 10751 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType)) 10752 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 10753 << ClassType << ConvType; 10754 } else if (ConvType->isVoidType()) { 10755 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 10756 << ClassType << ConvType; 10757 } 10758 10759 if (FunctionTemplateDecl *ConversionTemplate 10760 = Conversion->getDescribedFunctionTemplate()) 10761 return ConversionTemplate; 10762 10763 return Conversion; 10764 } 10765 10766 namespace { 10767 /// Utility class to accumulate and print a diagnostic listing the invalid 10768 /// specifier(s) on a declaration. 10769 struct BadSpecifierDiagnoser { 10770 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID) 10771 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {} 10772 ~BadSpecifierDiagnoser() { 10773 Diagnostic << Specifiers; 10774 } 10775 10776 template<typename T> void check(SourceLocation SpecLoc, T Spec) { 10777 return check(SpecLoc, DeclSpec::getSpecifierName(Spec)); 10778 } 10779 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) { 10780 return check(SpecLoc, 10781 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy())); 10782 } 10783 void check(SourceLocation SpecLoc, const char *Spec) { 10784 if (SpecLoc.isInvalid()) return; 10785 Diagnostic << SourceRange(SpecLoc, SpecLoc); 10786 if (!Specifiers.empty()) Specifiers += " "; 10787 Specifiers += Spec; 10788 } 10789 10790 Sema &S; 10791 Sema::SemaDiagnosticBuilder Diagnostic; 10792 std::string Specifiers; 10793 }; 10794 } 10795 10796 /// Check the validity of a declarator that we parsed for a deduction-guide. 10797 /// These aren't actually declarators in the grammar, so we need to check that 10798 /// the user didn't specify any pieces that are not part of the deduction-guide 10799 /// grammar. 10800 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R, 10801 StorageClass &SC) { 10802 TemplateName GuidedTemplate = D.getName().TemplateName.get().get(); 10803 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl(); 10804 assert(GuidedTemplateDecl && "missing template decl for deduction guide"); 10805 10806 // C++ [temp.deduct.guide]p3: 10807 // A deduction-gide shall be declared in the same scope as the 10808 // corresponding class template. 10809 if (!CurContext->getRedeclContext()->Equals( 10810 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) { 10811 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope) 10812 << GuidedTemplateDecl; 10813 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here); 10814 } 10815 10816 auto &DS = D.getMutableDeclSpec(); 10817 // We leave 'friend' and 'virtual' to be rejected in the normal way. 10818 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() || 10819 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() || 10820 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) { 10821 BadSpecifierDiagnoser Diagnoser( 10822 *this, D.getIdentifierLoc(), 10823 diag::err_deduction_guide_invalid_specifier); 10824 10825 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec()); 10826 DS.ClearStorageClassSpecs(); 10827 SC = SC_None; 10828 10829 // 'explicit' is permitted. 10830 Diagnoser.check(DS.getInlineSpecLoc(), "inline"); 10831 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn"); 10832 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr"); 10833 DS.ClearConstexprSpec(); 10834 10835 Diagnoser.check(DS.getConstSpecLoc(), "const"); 10836 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict"); 10837 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile"); 10838 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic"); 10839 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned"); 10840 DS.ClearTypeQualifiers(); 10841 10842 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex()); 10843 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign()); 10844 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth()); 10845 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType()); 10846 DS.ClearTypeSpecType(); 10847 } 10848 10849 if (D.isInvalidType()) 10850 return; 10851 10852 // Check the declarator is simple enough. 10853 bool FoundFunction = false; 10854 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) { 10855 if (Chunk.Kind == DeclaratorChunk::Paren) 10856 continue; 10857 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) { 10858 Diag(D.getDeclSpec().getBeginLoc(), 10859 diag::err_deduction_guide_with_complex_decl) 10860 << D.getSourceRange(); 10861 break; 10862 } 10863 if (!Chunk.Fun.hasTrailingReturnType()) { 10864 Diag(D.getName().getBeginLoc(), 10865 diag::err_deduction_guide_no_trailing_return_type); 10866 break; 10867 } 10868 10869 // Check that the return type is written as a specialization of 10870 // the template specified as the deduction-guide's name. 10871 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType(); 10872 TypeSourceInfo *TSI = nullptr; 10873 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI); 10874 assert(TSI && "deduction guide has valid type but invalid return type?"); 10875 bool AcceptableReturnType = false; 10876 bool MightInstantiateToSpecialization = false; 10877 if (auto RetTST = 10878 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) { 10879 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName(); 10880 bool TemplateMatches = 10881 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate); 10882 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches) 10883 AcceptableReturnType = true; 10884 else { 10885 // This could still instantiate to the right type, unless we know it 10886 // names the wrong class template. 10887 auto *TD = SpecifiedName.getAsTemplateDecl(); 10888 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) && 10889 !TemplateMatches); 10890 } 10891 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) { 10892 MightInstantiateToSpecialization = true; 10893 } 10894 10895 if (!AcceptableReturnType) { 10896 Diag(TSI->getTypeLoc().getBeginLoc(), 10897 diag::err_deduction_guide_bad_trailing_return_type) 10898 << GuidedTemplate << TSI->getType() 10899 << MightInstantiateToSpecialization 10900 << TSI->getTypeLoc().getSourceRange(); 10901 } 10902 10903 // Keep going to check that we don't have any inner declarator pieces (we 10904 // could still have a function returning a pointer to a function). 10905 FoundFunction = true; 10906 } 10907 10908 if (D.isFunctionDefinition()) 10909 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function); 10910 } 10911 10912 //===----------------------------------------------------------------------===// 10913 // Namespace Handling 10914 //===----------------------------------------------------------------------===// 10915 10916 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is 10917 /// reopened. 10918 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 10919 SourceLocation Loc, 10920 IdentifierInfo *II, bool *IsInline, 10921 NamespaceDecl *PrevNS) { 10922 assert(*IsInline != PrevNS->isInline()); 10923 10924 if (PrevNS->isInline()) 10925 // The user probably just forgot the 'inline', so suggest that it 10926 // be added back. 10927 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 10928 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 10929 else 10930 S.Diag(Loc, diag::err_inline_namespace_mismatch); 10931 10932 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 10933 *IsInline = PrevNS->isInline(); 10934 } 10935 10936 /// ActOnStartNamespaceDef - This is called at the start of a namespace 10937 /// definition. 10938 Decl *Sema::ActOnStartNamespaceDef( 10939 Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc, 10940 SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace, 10941 const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) { 10942 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 10943 // For anonymous namespace, take the location of the left brace. 10944 SourceLocation Loc = II ? IdentLoc : LBrace; 10945 bool IsInline = InlineLoc.isValid(); 10946 bool IsInvalid = false; 10947 bool IsStd = false; 10948 bool AddToKnown = false; 10949 Scope *DeclRegionScope = NamespcScope->getParent(); 10950 10951 NamespaceDecl *PrevNS = nullptr; 10952 if (II) { 10953 // C++ [namespace.def]p2: 10954 // The identifier in an original-namespace-definition shall not 10955 // have been previously defined in the declarative region in 10956 // which the original-namespace-definition appears. The 10957 // identifier in an original-namespace-definition is the name of 10958 // the namespace. Subsequently in that declarative region, it is 10959 // treated as an original-namespace-name. 10960 // 10961 // Since namespace names are unique in their scope, and we don't 10962 // look through using directives, just look for any ordinary names 10963 // as if by qualified name lookup. 10964 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, 10965 ForExternalRedeclaration); 10966 LookupQualifiedName(R, CurContext->getRedeclContext()); 10967 NamedDecl *PrevDecl = 10968 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr; 10969 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 10970 10971 if (PrevNS) { 10972 // This is an extended namespace definition. 10973 if (IsInline != PrevNS->isInline()) 10974 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 10975 &IsInline, PrevNS); 10976 } else if (PrevDecl) { 10977 // This is an invalid name redefinition. 10978 Diag(Loc, diag::err_redefinition_different_kind) 10979 << II; 10980 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 10981 IsInvalid = true; 10982 // Continue on to push Namespc as current DeclContext and return it. 10983 } else if (II->isStr("std") && 10984 CurContext->getRedeclContext()->isTranslationUnit()) { 10985 // This is the first "real" definition of the namespace "std", so update 10986 // our cache of the "std" namespace to point at this definition. 10987 PrevNS = getStdNamespace(); 10988 IsStd = true; 10989 AddToKnown = !IsInline; 10990 } else { 10991 // We've seen this namespace for the first time. 10992 AddToKnown = !IsInline; 10993 } 10994 } else { 10995 // Anonymous namespaces. 10996 10997 // Determine whether the parent already has an anonymous namespace. 10998 DeclContext *Parent = CurContext->getRedeclContext(); 10999 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 11000 PrevNS = TU->getAnonymousNamespace(); 11001 } else { 11002 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 11003 PrevNS = ND->getAnonymousNamespace(); 11004 } 11005 11006 if (PrevNS && IsInline != PrevNS->isInline()) 11007 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 11008 &IsInline, PrevNS); 11009 } 11010 11011 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 11012 StartLoc, Loc, II, PrevNS); 11013 if (IsInvalid) 11014 Namespc->setInvalidDecl(); 11015 11016 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 11017 AddPragmaAttributes(DeclRegionScope, Namespc); 11018 11019 // FIXME: Should we be merging attributes? 11020 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 11021 PushNamespaceVisibilityAttr(Attr, Loc); 11022 11023 if (IsStd) 11024 StdNamespace = Namespc; 11025 if (AddToKnown) 11026 KnownNamespaces[Namespc] = false; 11027 11028 if (II) { 11029 PushOnScopeChains(Namespc, DeclRegionScope); 11030 } else { 11031 // Link the anonymous namespace into its parent. 11032 DeclContext *Parent = CurContext->getRedeclContext(); 11033 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 11034 TU->setAnonymousNamespace(Namespc); 11035 } else { 11036 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 11037 } 11038 11039 CurContext->addDecl(Namespc); 11040 11041 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 11042 // behaves as if it were replaced by 11043 // namespace unique { /* empty body */ } 11044 // using namespace unique; 11045 // namespace unique { namespace-body } 11046 // where all occurrences of 'unique' in a translation unit are 11047 // replaced by the same identifier and this identifier differs 11048 // from all other identifiers in the entire program. 11049 11050 // We just create the namespace with an empty name and then add an 11051 // implicit using declaration, just like the standard suggests. 11052 // 11053 // CodeGen enforces the "universally unique" aspect by giving all 11054 // declarations semantically contained within an anonymous 11055 // namespace internal linkage. 11056 11057 if (!PrevNS) { 11058 UD = UsingDirectiveDecl::Create(Context, Parent, 11059 /* 'using' */ LBrace, 11060 /* 'namespace' */ SourceLocation(), 11061 /* qualifier */ NestedNameSpecifierLoc(), 11062 /* identifier */ SourceLocation(), 11063 Namespc, 11064 /* Ancestor */ Parent); 11065 UD->setImplicit(); 11066 Parent->addDecl(UD); 11067 } 11068 } 11069 11070 ActOnDocumentableDecl(Namespc); 11071 11072 // Although we could have an invalid decl (i.e. the namespace name is a 11073 // redefinition), push it as current DeclContext and try to continue parsing. 11074 // FIXME: We should be able to push Namespc here, so that the each DeclContext 11075 // for the namespace has the declarations that showed up in that particular 11076 // namespace definition. 11077 PushDeclContext(NamespcScope, Namespc); 11078 return Namespc; 11079 } 11080 11081 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 11082 /// is a namespace alias, returns the namespace it points to. 11083 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 11084 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 11085 return AD->getNamespace(); 11086 return dyn_cast_or_null<NamespaceDecl>(D); 11087 } 11088 11089 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 11090 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 11091 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 11092 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 11093 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 11094 Namespc->setRBraceLoc(RBrace); 11095 PopDeclContext(); 11096 if (Namespc->hasAttr<VisibilityAttr>()) 11097 PopPragmaVisibility(true, RBrace); 11098 // If this namespace contains an export-declaration, export it now. 11099 if (DeferredExportedNamespaces.erase(Namespc)) 11100 Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported); 11101 } 11102 11103 CXXRecordDecl *Sema::getStdBadAlloc() const { 11104 return cast_or_null<CXXRecordDecl>( 11105 StdBadAlloc.get(Context.getExternalSource())); 11106 } 11107 11108 EnumDecl *Sema::getStdAlignValT() const { 11109 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource())); 11110 } 11111 11112 NamespaceDecl *Sema::getStdNamespace() const { 11113 return cast_or_null<NamespaceDecl>( 11114 StdNamespace.get(Context.getExternalSource())); 11115 } 11116 11117 NamespaceDecl *Sema::lookupStdExperimentalNamespace() { 11118 if (!StdExperimentalNamespaceCache) { 11119 if (auto Std = getStdNamespace()) { 11120 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"), 11121 SourceLocation(), LookupNamespaceName); 11122 if (!LookupQualifiedName(Result, Std) || 11123 !(StdExperimentalNamespaceCache = 11124 Result.getAsSingle<NamespaceDecl>())) 11125 Result.suppressDiagnostics(); 11126 } 11127 } 11128 return StdExperimentalNamespaceCache; 11129 } 11130 11131 namespace { 11132 11133 enum UnsupportedSTLSelect { 11134 USS_InvalidMember, 11135 USS_MissingMember, 11136 USS_NonTrivial, 11137 USS_Other 11138 }; 11139 11140 struct InvalidSTLDiagnoser { 11141 Sema &S; 11142 SourceLocation Loc; 11143 QualType TyForDiags; 11144 11145 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "", 11146 const VarDecl *VD = nullptr) { 11147 { 11148 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported) 11149 << TyForDiags << ((int)Sel); 11150 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) { 11151 assert(!Name.empty()); 11152 D << Name; 11153 } 11154 } 11155 if (Sel == USS_InvalidMember) { 11156 S.Diag(VD->getLocation(), diag::note_var_declared_here) 11157 << VD << VD->getSourceRange(); 11158 } 11159 return QualType(); 11160 } 11161 }; 11162 } // namespace 11163 11164 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind, 11165 SourceLocation Loc, 11166 ComparisonCategoryUsage Usage) { 11167 assert(getLangOpts().CPlusPlus && 11168 "Looking for comparison category type outside of C++."); 11169 11170 // Use an elaborated type for diagnostics which has a name containing the 11171 // prepended 'std' namespace but not any inline namespace names. 11172 auto TyForDiags = [&](ComparisonCategoryInfo *Info) { 11173 auto *NNS = 11174 NestedNameSpecifier::Create(Context, nullptr, getStdNamespace()); 11175 return Context.getElaboratedType(ETK_None, NNS, Info->getType()); 11176 }; 11177 11178 // Check if we've already successfully checked the comparison category type 11179 // before. If so, skip checking it again. 11180 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind); 11181 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) { 11182 // The only thing we need to check is that the type has a reachable 11183 // definition in the current context. 11184 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type)) 11185 return QualType(); 11186 11187 return Info->getType(); 11188 } 11189 11190 // If lookup failed 11191 if (!Info) { 11192 std::string NameForDiags = "std::"; 11193 NameForDiags += ComparisonCategories::getCategoryString(Kind); 11194 Diag(Loc, diag::err_implied_comparison_category_type_not_found) 11195 << NameForDiags << (int)Usage; 11196 return QualType(); 11197 } 11198 11199 assert(Info->Kind == Kind); 11200 assert(Info->Record); 11201 11202 // Update the Record decl in case we encountered a forward declaration on our 11203 // first pass. FIXME: This is a bit of a hack. 11204 if (Info->Record->hasDefinition()) 11205 Info->Record = Info->Record->getDefinition(); 11206 11207 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type)) 11208 return QualType(); 11209 11210 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)}; 11211 11212 if (!Info->Record->isTriviallyCopyable()) 11213 return UnsupportedSTLError(USS_NonTrivial); 11214 11215 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) { 11216 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl(); 11217 // Tolerate empty base classes. 11218 if (Base->isEmpty()) 11219 continue; 11220 // Reject STL implementations which have at least one non-empty base. 11221 return UnsupportedSTLError(); 11222 } 11223 11224 // Check that the STL has implemented the types using a single integer field. 11225 // This expectation allows better codegen for builtin operators. We require: 11226 // (1) The class has exactly one field. 11227 // (2) The field is an integral or enumeration type. 11228 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end(); 11229 if (std::distance(FIt, FEnd) != 1 || 11230 !FIt->getType()->isIntegralOrEnumerationType()) { 11231 return UnsupportedSTLError(); 11232 } 11233 11234 // Build each of the require values and store them in Info. 11235 for (ComparisonCategoryResult CCR : 11236 ComparisonCategories::getPossibleResultsForType(Kind)) { 11237 StringRef MemName = ComparisonCategories::getResultString(CCR); 11238 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR); 11239 11240 if (!ValInfo) 11241 return UnsupportedSTLError(USS_MissingMember, MemName); 11242 11243 VarDecl *VD = ValInfo->VD; 11244 assert(VD && "should not be null!"); 11245 11246 // Attempt to diagnose reasons why the STL definition of this type 11247 // might be foobar, including it failing to be a constant expression. 11248 // TODO Handle more ways the lookup or result can be invalid. 11249 if (!VD->isStaticDataMember() || 11250 !VD->isUsableInConstantExpressions(Context)) 11251 return UnsupportedSTLError(USS_InvalidMember, MemName, VD); 11252 11253 // Attempt to evaluate the var decl as a constant expression and extract 11254 // the value of its first field as a ICE. If this fails, the STL 11255 // implementation is not supported. 11256 if (!ValInfo->hasValidIntValue()) 11257 return UnsupportedSTLError(); 11258 11259 MarkVariableReferenced(Loc, VD); 11260 } 11261 11262 // We've successfully built the required types and expressions. Update 11263 // the cache and return the newly cached value. 11264 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true; 11265 return Info->getType(); 11266 } 11267 11268 /// Retrieve the special "std" namespace, which may require us to 11269 /// implicitly define the namespace. 11270 NamespaceDecl *Sema::getOrCreateStdNamespace() { 11271 if (!StdNamespace) { 11272 // The "std" namespace has not yet been defined, so build one implicitly. 11273 StdNamespace = NamespaceDecl::Create(Context, 11274 Context.getTranslationUnitDecl(), 11275 /*Inline=*/false, 11276 SourceLocation(), SourceLocation(), 11277 &PP.getIdentifierTable().get("std"), 11278 /*PrevDecl=*/nullptr); 11279 getStdNamespace()->setImplicit(true); 11280 } 11281 11282 return getStdNamespace(); 11283 } 11284 11285 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 11286 assert(getLangOpts().CPlusPlus && 11287 "Looking for std::initializer_list outside of C++."); 11288 11289 // We're looking for implicit instantiations of 11290 // template <typename E> class std::initializer_list. 11291 11292 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 11293 return false; 11294 11295 ClassTemplateDecl *Template = nullptr; 11296 const TemplateArgument *Arguments = nullptr; 11297 11298 if (const RecordType *RT = Ty->getAs<RecordType>()) { 11299 11300 ClassTemplateSpecializationDecl *Specialization = 11301 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 11302 if (!Specialization) 11303 return false; 11304 11305 Template = Specialization->getSpecializedTemplate(); 11306 Arguments = Specialization->getTemplateArgs().data(); 11307 } else if (const TemplateSpecializationType *TST = 11308 Ty->getAs<TemplateSpecializationType>()) { 11309 Template = dyn_cast_or_null<ClassTemplateDecl>( 11310 TST->getTemplateName().getAsTemplateDecl()); 11311 Arguments = TST->getArgs(); 11312 } 11313 if (!Template) 11314 return false; 11315 11316 if (!StdInitializerList) { 11317 // Haven't recognized std::initializer_list yet, maybe this is it. 11318 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 11319 if (TemplateClass->getIdentifier() != 11320 &PP.getIdentifierTable().get("initializer_list") || 11321 !getStdNamespace()->InEnclosingNamespaceSetOf( 11322 TemplateClass->getDeclContext())) 11323 return false; 11324 // This is a template called std::initializer_list, but is it the right 11325 // template? 11326 TemplateParameterList *Params = Template->getTemplateParameters(); 11327 if (Params->getMinRequiredArguments() != 1) 11328 return false; 11329 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 11330 return false; 11331 11332 // It's the right template. 11333 StdInitializerList = Template; 11334 } 11335 11336 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) 11337 return false; 11338 11339 // This is an instance of std::initializer_list. Find the argument type. 11340 if (Element) 11341 *Element = Arguments[0].getAsType(); 11342 return true; 11343 } 11344 11345 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 11346 NamespaceDecl *Std = S.getStdNamespace(); 11347 if (!Std) { 11348 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 11349 return nullptr; 11350 } 11351 11352 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 11353 Loc, Sema::LookupOrdinaryName); 11354 if (!S.LookupQualifiedName(Result, Std)) { 11355 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 11356 return nullptr; 11357 } 11358 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 11359 if (!Template) { 11360 Result.suppressDiagnostics(); 11361 // We found something weird. Complain about the first thing we found. 11362 NamedDecl *Found = *Result.begin(); 11363 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 11364 return nullptr; 11365 } 11366 11367 // We found some template called std::initializer_list. Now verify that it's 11368 // correct. 11369 TemplateParameterList *Params = Template->getTemplateParameters(); 11370 if (Params->getMinRequiredArguments() != 1 || 11371 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 11372 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 11373 return nullptr; 11374 } 11375 11376 return Template; 11377 } 11378 11379 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 11380 if (!StdInitializerList) { 11381 StdInitializerList = LookupStdInitializerList(*this, Loc); 11382 if (!StdInitializerList) 11383 return QualType(); 11384 } 11385 11386 TemplateArgumentListInfo Args(Loc, Loc); 11387 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 11388 Context.getTrivialTypeSourceInfo(Element, 11389 Loc))); 11390 return Context.getCanonicalType( 11391 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 11392 } 11393 11394 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) { 11395 // C++ [dcl.init.list]p2: 11396 // A constructor is an initializer-list constructor if its first parameter 11397 // is of type std::initializer_list<E> or reference to possibly cv-qualified 11398 // std::initializer_list<E> for some type E, and either there are no other 11399 // parameters or else all other parameters have default arguments. 11400 if (!Ctor->hasOneParamOrDefaultArgs()) 11401 return false; 11402 11403 QualType ArgType = Ctor->getParamDecl(0)->getType(); 11404 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 11405 ArgType = RT->getPointeeType().getUnqualifiedType(); 11406 11407 return isStdInitializerList(ArgType, nullptr); 11408 } 11409 11410 /// Determine whether a using statement is in a context where it will be 11411 /// apply in all contexts. 11412 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 11413 switch (CurContext->getDeclKind()) { 11414 case Decl::TranslationUnit: 11415 return true; 11416 case Decl::LinkageSpec: 11417 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 11418 default: 11419 return false; 11420 } 11421 } 11422 11423 namespace { 11424 11425 // Callback to only accept typo corrections that are namespaces. 11426 class NamespaceValidatorCCC final : public CorrectionCandidateCallback { 11427 public: 11428 bool ValidateCandidate(const TypoCorrection &candidate) override { 11429 if (NamedDecl *ND = candidate.getCorrectionDecl()) 11430 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 11431 return false; 11432 } 11433 11434 std::unique_ptr<CorrectionCandidateCallback> clone() override { 11435 return std::make_unique<NamespaceValidatorCCC>(*this); 11436 } 11437 }; 11438 11439 } 11440 11441 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 11442 CXXScopeSpec &SS, 11443 SourceLocation IdentLoc, 11444 IdentifierInfo *Ident) { 11445 R.clear(); 11446 NamespaceValidatorCCC CCC{}; 11447 if (TypoCorrection Corrected = 11448 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC, 11449 Sema::CTK_ErrorRecovery)) { 11450 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 11451 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 11452 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 11453 Ident->getName().equals(CorrectedStr); 11454 S.diagnoseTypo(Corrected, 11455 S.PDiag(diag::err_using_directive_member_suggest) 11456 << Ident << DC << DroppedSpecifier << SS.getRange(), 11457 S.PDiag(diag::note_namespace_defined_here)); 11458 } else { 11459 S.diagnoseTypo(Corrected, 11460 S.PDiag(diag::err_using_directive_suggest) << Ident, 11461 S.PDiag(diag::note_namespace_defined_here)); 11462 } 11463 R.addDecl(Corrected.getFoundDecl()); 11464 return true; 11465 } 11466 return false; 11467 } 11468 11469 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc, 11470 SourceLocation NamespcLoc, CXXScopeSpec &SS, 11471 SourceLocation IdentLoc, 11472 IdentifierInfo *NamespcName, 11473 const ParsedAttributesView &AttrList) { 11474 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 11475 assert(NamespcName && "Invalid NamespcName."); 11476 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 11477 11478 // This can only happen along a recovery path. 11479 while (S->isTemplateParamScope()) 11480 S = S->getParent(); 11481 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 11482 11483 UsingDirectiveDecl *UDir = nullptr; 11484 NestedNameSpecifier *Qualifier = nullptr; 11485 if (SS.isSet()) 11486 Qualifier = SS.getScopeRep(); 11487 11488 // Lookup namespace name. 11489 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 11490 LookupParsedName(R, S, &SS); 11491 if (R.isAmbiguous()) 11492 return nullptr; 11493 11494 if (R.empty()) { 11495 R.clear(); 11496 // Allow "using namespace std;" or "using namespace ::std;" even if 11497 // "std" hasn't been defined yet, for GCC compatibility. 11498 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 11499 NamespcName->isStr("std")) { 11500 Diag(IdentLoc, diag::ext_using_undefined_std); 11501 R.addDecl(getOrCreateStdNamespace()); 11502 R.resolveKind(); 11503 } 11504 // Otherwise, attempt typo correction. 11505 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 11506 } 11507 11508 if (!R.empty()) { 11509 NamedDecl *Named = R.getRepresentativeDecl(); 11510 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>(); 11511 assert(NS && "expected namespace decl"); 11512 11513 // The use of a nested name specifier may trigger deprecation warnings. 11514 DiagnoseUseOfDecl(Named, IdentLoc); 11515 11516 // C++ [namespace.udir]p1: 11517 // A using-directive specifies that the names in the nominated 11518 // namespace can be used in the scope in which the 11519 // using-directive appears after the using-directive. During 11520 // unqualified name lookup (3.4.1), the names appear as if they 11521 // were declared in the nearest enclosing namespace which 11522 // contains both the using-directive and the nominated 11523 // namespace. [Note: in this context, "contains" means "contains 11524 // directly or indirectly". ] 11525 11526 // Find enclosing context containing both using-directive and 11527 // nominated namespace. 11528 DeclContext *CommonAncestor = NS; 11529 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 11530 CommonAncestor = CommonAncestor->getParent(); 11531 11532 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 11533 SS.getWithLocInContext(Context), 11534 IdentLoc, Named, CommonAncestor); 11535 11536 if (IsUsingDirectiveInToplevelContext(CurContext) && 11537 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 11538 Diag(IdentLoc, diag::warn_using_directive_in_header); 11539 } 11540 11541 PushUsingDirective(S, UDir); 11542 } else { 11543 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 11544 } 11545 11546 if (UDir) 11547 ProcessDeclAttributeList(S, UDir, AttrList); 11548 11549 return UDir; 11550 } 11551 11552 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 11553 // If the scope has an associated entity and the using directive is at 11554 // namespace or translation unit scope, add the UsingDirectiveDecl into 11555 // its lookup structure so qualified name lookup can find it. 11556 DeclContext *Ctx = S->getEntity(); 11557 if (Ctx && !Ctx->isFunctionOrMethod()) 11558 Ctx->addDecl(UDir); 11559 else 11560 // Otherwise, it is at block scope. The using-directives will affect lookup 11561 // only to the end of the scope. 11562 S->PushUsingDirective(UDir); 11563 } 11564 11565 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS, 11566 SourceLocation UsingLoc, 11567 SourceLocation TypenameLoc, CXXScopeSpec &SS, 11568 UnqualifiedId &Name, 11569 SourceLocation EllipsisLoc, 11570 const ParsedAttributesView &AttrList) { 11571 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 11572 11573 if (SS.isEmpty()) { 11574 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname); 11575 return nullptr; 11576 } 11577 11578 switch (Name.getKind()) { 11579 case UnqualifiedIdKind::IK_ImplicitSelfParam: 11580 case UnqualifiedIdKind::IK_Identifier: 11581 case UnqualifiedIdKind::IK_OperatorFunctionId: 11582 case UnqualifiedIdKind::IK_LiteralOperatorId: 11583 case UnqualifiedIdKind::IK_ConversionFunctionId: 11584 break; 11585 11586 case UnqualifiedIdKind::IK_ConstructorName: 11587 case UnqualifiedIdKind::IK_ConstructorTemplateId: 11588 // C++11 inheriting constructors. 11589 Diag(Name.getBeginLoc(), 11590 getLangOpts().CPlusPlus11 11591 ? diag::warn_cxx98_compat_using_decl_constructor 11592 : diag::err_using_decl_constructor) 11593 << SS.getRange(); 11594 11595 if (getLangOpts().CPlusPlus11) break; 11596 11597 return nullptr; 11598 11599 case UnqualifiedIdKind::IK_DestructorName: 11600 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange(); 11601 return nullptr; 11602 11603 case UnqualifiedIdKind::IK_TemplateId: 11604 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id) 11605 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 11606 return nullptr; 11607 11608 case UnqualifiedIdKind::IK_DeductionGuideName: 11609 llvm_unreachable("cannot parse qualified deduction guide name"); 11610 } 11611 11612 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 11613 DeclarationName TargetName = TargetNameInfo.getName(); 11614 if (!TargetName) 11615 return nullptr; 11616 11617 // Warn about access declarations. 11618 if (UsingLoc.isInvalid()) { 11619 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11 11620 ? diag::err_access_decl 11621 : diag::warn_access_decl_deprecated) 11622 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 11623 } 11624 11625 if (EllipsisLoc.isInvalid()) { 11626 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 11627 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 11628 return nullptr; 11629 } else { 11630 if (!SS.getScopeRep()->containsUnexpandedParameterPack() && 11631 !TargetNameInfo.containsUnexpandedParameterPack()) { 11632 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 11633 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc()); 11634 EllipsisLoc = SourceLocation(); 11635 } 11636 } 11637 11638 NamedDecl *UD = 11639 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc, 11640 SS, TargetNameInfo, EllipsisLoc, AttrList, 11641 /*IsInstantiation*/ false, 11642 AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists)); 11643 if (UD) 11644 PushOnScopeChains(UD, S, /*AddToContext*/ false); 11645 11646 return UD; 11647 } 11648 11649 Decl *Sema::ActOnUsingEnumDeclaration(Scope *S, AccessSpecifier AS, 11650 SourceLocation UsingLoc, 11651 SourceLocation EnumLoc, 11652 const DeclSpec &DS) { 11653 switch (DS.getTypeSpecType()) { 11654 case DeclSpec::TST_error: 11655 // This will already have been diagnosed 11656 return nullptr; 11657 11658 case DeclSpec::TST_enum: 11659 break; 11660 11661 case DeclSpec::TST_typename: 11662 Diag(DS.getTypeSpecTypeLoc(), diag::err_using_enum_is_dependent); 11663 return nullptr; 11664 11665 default: 11666 llvm_unreachable("unexpected DeclSpec type"); 11667 } 11668 11669 // As with enum-decls, we ignore attributes for now. 11670 auto *Enum = cast<EnumDecl>(DS.getRepAsDecl()); 11671 if (auto *Def = Enum->getDefinition()) 11672 Enum = Def; 11673 11674 auto *UD = BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc, 11675 DS.getTypeSpecTypeNameLoc(), Enum); 11676 if (UD) 11677 PushOnScopeChains(UD, S, /*AddToContext*/ false); 11678 11679 return UD; 11680 } 11681 11682 /// Determine whether a using declaration considers the given 11683 /// declarations as "equivalent", e.g., if they are redeclarations of 11684 /// the same entity or are both typedefs of the same type. 11685 static bool 11686 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 11687 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 11688 return true; 11689 11690 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 11691 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 11692 return Context.hasSameType(TD1->getUnderlyingType(), 11693 TD2->getUnderlyingType()); 11694 11695 // Two using_if_exists using-declarations are equivalent if both are 11696 // unresolved. 11697 if (isa<UnresolvedUsingIfExistsDecl>(D1) && 11698 isa<UnresolvedUsingIfExistsDecl>(D2)) 11699 return true; 11700 11701 return false; 11702 } 11703 11704 11705 /// Determines whether to create a using shadow decl for a particular 11706 /// decl, given the set of decls existing prior to this using lookup. 11707 bool Sema::CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Orig, 11708 const LookupResult &Previous, 11709 UsingShadowDecl *&PrevShadow) { 11710 // Diagnose finding a decl which is not from a base class of the 11711 // current class. We do this now because there are cases where this 11712 // function will silently decide not to build a shadow decl, which 11713 // will pre-empt further diagnostics. 11714 // 11715 // We don't need to do this in C++11 because we do the check once on 11716 // the qualifier. 11717 // 11718 // FIXME: diagnose the following if we care enough: 11719 // struct A { int foo; }; 11720 // struct B : A { using A::foo; }; 11721 // template <class T> struct C : A {}; 11722 // template <class T> struct D : C<T> { using B::foo; } // <--- 11723 // This is invalid (during instantiation) in C++03 because B::foo 11724 // resolves to the using decl in B, which is not a base class of D<T>. 11725 // We can't diagnose it immediately because C<T> is an unknown 11726 // specialization. The UsingShadowDecl in D<T> then points directly 11727 // to A::foo, which will look well-formed when we instantiate. 11728 // The right solution is to not collapse the shadow-decl chain. 11729 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) 11730 if (auto *Using = dyn_cast<UsingDecl>(BUD)) { 11731 DeclContext *OrigDC = Orig->getDeclContext(); 11732 11733 // Handle enums and anonymous structs. 11734 if (isa<EnumDecl>(OrigDC)) 11735 OrigDC = OrigDC->getParent(); 11736 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 11737 while (OrigRec->isAnonymousStructOrUnion()) 11738 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 11739 11740 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 11741 if (OrigDC == CurContext) { 11742 Diag(Using->getLocation(), 11743 diag::err_using_decl_nested_name_specifier_is_current_class) 11744 << Using->getQualifierLoc().getSourceRange(); 11745 Diag(Orig->getLocation(), diag::note_using_decl_target); 11746 Using->setInvalidDecl(); 11747 return true; 11748 } 11749 11750 Diag(Using->getQualifierLoc().getBeginLoc(), 11751 diag::err_using_decl_nested_name_specifier_is_not_base_class) 11752 << Using->getQualifier() << cast<CXXRecordDecl>(CurContext) 11753 << Using->getQualifierLoc().getSourceRange(); 11754 Diag(Orig->getLocation(), diag::note_using_decl_target); 11755 Using->setInvalidDecl(); 11756 return true; 11757 } 11758 } 11759 11760 if (Previous.empty()) return false; 11761 11762 NamedDecl *Target = Orig; 11763 if (isa<UsingShadowDecl>(Target)) 11764 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 11765 11766 // If the target happens to be one of the previous declarations, we 11767 // don't have a conflict. 11768 // 11769 // FIXME: but we might be increasing its access, in which case we 11770 // should redeclare it. 11771 NamedDecl *NonTag = nullptr, *Tag = nullptr; 11772 bool FoundEquivalentDecl = false; 11773 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 11774 I != E; ++I) { 11775 NamedDecl *D = (*I)->getUnderlyingDecl(); 11776 // We can have UsingDecls in our Previous results because we use the same 11777 // LookupResult for checking whether the UsingDecl itself is a valid 11778 // redeclaration. 11779 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D) || isa<UsingEnumDecl>(D)) 11780 continue; 11781 11782 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 11783 // C++ [class.mem]p19: 11784 // If T is the name of a class, then [every named member other than 11785 // a non-static data member] shall have a name different from T 11786 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) && 11787 !isa<IndirectFieldDecl>(Target) && 11788 !isa<UnresolvedUsingValueDecl>(Target) && 11789 DiagnoseClassNameShadow( 11790 CurContext, 11791 DeclarationNameInfo(BUD->getDeclName(), BUD->getLocation()))) 11792 return true; 11793 } 11794 11795 if (IsEquivalentForUsingDecl(Context, D, Target)) { 11796 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 11797 PrevShadow = Shadow; 11798 FoundEquivalentDecl = true; 11799 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) { 11800 // We don't conflict with an existing using shadow decl of an equivalent 11801 // declaration, but we're not a redeclaration of it. 11802 FoundEquivalentDecl = true; 11803 } 11804 11805 if (isVisible(D)) 11806 (isa<TagDecl>(D) ? Tag : NonTag) = D; 11807 } 11808 11809 if (FoundEquivalentDecl) 11810 return false; 11811 11812 // Always emit a diagnostic for a mismatch between an unresolved 11813 // using_if_exists and a resolved using declaration in either direction. 11814 if (isa<UnresolvedUsingIfExistsDecl>(Target) != 11815 (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) { 11816 if (!NonTag && !Tag) 11817 return false; 11818 Diag(BUD->getLocation(), diag::err_using_decl_conflict); 11819 Diag(Target->getLocation(), diag::note_using_decl_target); 11820 Diag((NonTag ? NonTag : Tag)->getLocation(), 11821 diag::note_using_decl_conflict); 11822 BUD->setInvalidDecl(); 11823 return true; 11824 } 11825 11826 if (FunctionDecl *FD = Target->getAsFunction()) { 11827 NamedDecl *OldDecl = nullptr; 11828 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 11829 /*IsForUsingDecl*/ true)) { 11830 case Ovl_Overload: 11831 return false; 11832 11833 case Ovl_NonFunction: 11834 Diag(BUD->getLocation(), diag::err_using_decl_conflict); 11835 break; 11836 11837 // We found a decl with the exact signature. 11838 case Ovl_Match: 11839 // If we're in a record, we want to hide the target, so we 11840 // return true (without a diagnostic) to tell the caller not to 11841 // build a shadow decl. 11842 if (CurContext->isRecord()) 11843 return true; 11844 11845 // If we're not in a record, this is an error. 11846 Diag(BUD->getLocation(), diag::err_using_decl_conflict); 11847 break; 11848 } 11849 11850 Diag(Target->getLocation(), diag::note_using_decl_target); 11851 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 11852 BUD->setInvalidDecl(); 11853 return true; 11854 } 11855 11856 // Target is not a function. 11857 11858 if (isa<TagDecl>(Target)) { 11859 // No conflict between a tag and a non-tag. 11860 if (!Tag) return false; 11861 11862 Diag(BUD->getLocation(), diag::err_using_decl_conflict); 11863 Diag(Target->getLocation(), diag::note_using_decl_target); 11864 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 11865 BUD->setInvalidDecl(); 11866 return true; 11867 } 11868 11869 // No conflict between a tag and a non-tag. 11870 if (!NonTag) return false; 11871 11872 Diag(BUD->getLocation(), diag::err_using_decl_conflict); 11873 Diag(Target->getLocation(), diag::note_using_decl_target); 11874 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 11875 BUD->setInvalidDecl(); 11876 return true; 11877 } 11878 11879 /// Determine whether a direct base class is a virtual base class. 11880 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) { 11881 if (!Derived->getNumVBases()) 11882 return false; 11883 for (auto &B : Derived->bases()) 11884 if (B.getType()->getAsCXXRecordDecl() == Base) 11885 return B.isVirtual(); 11886 llvm_unreachable("not a direct base class"); 11887 } 11888 11889 /// Builds a shadow declaration corresponding to a 'using' declaration. 11890 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD, 11891 NamedDecl *Orig, 11892 UsingShadowDecl *PrevDecl) { 11893 // If we resolved to another shadow declaration, just coalesce them. 11894 NamedDecl *Target = Orig; 11895 if (isa<UsingShadowDecl>(Target)) { 11896 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 11897 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 11898 } 11899 11900 NamedDecl *NonTemplateTarget = Target; 11901 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target)) 11902 NonTemplateTarget = TargetTD->getTemplatedDecl(); 11903 11904 UsingShadowDecl *Shadow; 11905 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) { 11906 UsingDecl *Using = cast<UsingDecl>(BUD); 11907 bool IsVirtualBase = 11908 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext), 11909 Using->getQualifier()->getAsRecordDecl()); 11910 Shadow = ConstructorUsingShadowDecl::Create( 11911 Context, CurContext, Using->getLocation(), Using, Orig, IsVirtualBase); 11912 } else { 11913 Shadow = UsingShadowDecl::Create(Context, CurContext, BUD->getLocation(), 11914 Target->getDeclName(), BUD, Target); 11915 } 11916 BUD->addShadowDecl(Shadow); 11917 11918 Shadow->setAccess(BUD->getAccess()); 11919 if (Orig->isInvalidDecl() || BUD->isInvalidDecl()) 11920 Shadow->setInvalidDecl(); 11921 11922 Shadow->setPreviousDecl(PrevDecl); 11923 11924 if (S) 11925 PushOnScopeChains(Shadow, S); 11926 else 11927 CurContext->addDecl(Shadow); 11928 11929 11930 return Shadow; 11931 } 11932 11933 /// Hides a using shadow declaration. This is required by the current 11934 /// using-decl implementation when a resolvable using declaration in a 11935 /// class is followed by a declaration which would hide or override 11936 /// one or more of the using decl's targets; for example: 11937 /// 11938 /// struct Base { void foo(int); }; 11939 /// struct Derived : Base { 11940 /// using Base::foo; 11941 /// void foo(int); 11942 /// }; 11943 /// 11944 /// The governing language is C++03 [namespace.udecl]p12: 11945 /// 11946 /// When a using-declaration brings names from a base class into a 11947 /// derived class scope, member functions in the derived class 11948 /// override and/or hide member functions with the same name and 11949 /// parameter types in a base class (rather than conflicting). 11950 /// 11951 /// There are two ways to implement this: 11952 /// (1) optimistically create shadow decls when they're not hidden 11953 /// by existing declarations, or 11954 /// (2) don't create any shadow decls (or at least don't make them 11955 /// visible) until we've fully parsed/instantiated the class. 11956 /// The problem with (1) is that we might have to retroactively remove 11957 /// a shadow decl, which requires several O(n) operations because the 11958 /// decl structures are (very reasonably) not designed for removal. 11959 /// (2) avoids this but is very fiddly and phase-dependent. 11960 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 11961 if (Shadow->getDeclName().getNameKind() == 11962 DeclarationName::CXXConversionFunctionName) 11963 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 11964 11965 // Remove it from the DeclContext... 11966 Shadow->getDeclContext()->removeDecl(Shadow); 11967 11968 // ...and the scope, if applicable... 11969 if (S) { 11970 S->RemoveDecl(Shadow); 11971 IdResolver.RemoveDecl(Shadow); 11972 } 11973 11974 // ...and the using decl. 11975 Shadow->getIntroducer()->removeShadowDecl(Shadow); 11976 11977 // TODO: complain somehow if Shadow was used. It shouldn't 11978 // be possible for this to happen, because...? 11979 } 11980 11981 /// Find the base specifier for a base class with the given type. 11982 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 11983 QualType DesiredBase, 11984 bool &AnyDependentBases) { 11985 // Check whether the named type is a direct base class. 11986 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified() 11987 .getUnqualifiedType(); 11988 for (auto &Base : Derived->bases()) { 11989 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 11990 if (CanonicalDesiredBase == BaseType) 11991 return &Base; 11992 if (BaseType->isDependentType()) 11993 AnyDependentBases = true; 11994 } 11995 return nullptr; 11996 } 11997 11998 namespace { 11999 class UsingValidatorCCC final : public CorrectionCandidateCallback { 12000 public: 12001 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 12002 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 12003 : HasTypenameKeyword(HasTypenameKeyword), 12004 IsInstantiation(IsInstantiation), OldNNS(NNS), 12005 RequireMemberOf(RequireMemberOf) {} 12006 12007 bool ValidateCandidate(const TypoCorrection &Candidate) override { 12008 NamedDecl *ND = Candidate.getCorrectionDecl(); 12009 12010 // Keywords are not valid here. 12011 if (!ND || isa<NamespaceDecl>(ND)) 12012 return false; 12013 12014 // Completely unqualified names are invalid for a 'using' declaration. 12015 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 12016 return false; 12017 12018 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would 12019 // reject. 12020 12021 if (RequireMemberOf) { 12022 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 12023 if (FoundRecord && FoundRecord->isInjectedClassName()) { 12024 // No-one ever wants a using-declaration to name an injected-class-name 12025 // of a base class, unless they're declaring an inheriting constructor. 12026 ASTContext &Ctx = ND->getASTContext(); 12027 if (!Ctx.getLangOpts().CPlusPlus11) 12028 return false; 12029 QualType FoundType = Ctx.getRecordType(FoundRecord); 12030 12031 // Check that the injected-class-name is named as a member of its own 12032 // type; we don't want to suggest 'using Derived::Base;', since that 12033 // means something else. 12034 NestedNameSpecifier *Specifier = 12035 Candidate.WillReplaceSpecifier() 12036 ? Candidate.getCorrectionSpecifier() 12037 : OldNNS; 12038 if (!Specifier->getAsType() || 12039 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 12040 return false; 12041 12042 // Check that this inheriting constructor declaration actually names a 12043 // direct base class of the current class. 12044 bool AnyDependentBases = false; 12045 if (!findDirectBaseWithType(RequireMemberOf, 12046 Ctx.getRecordType(FoundRecord), 12047 AnyDependentBases) && 12048 !AnyDependentBases) 12049 return false; 12050 } else { 12051 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 12052 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 12053 return false; 12054 12055 // FIXME: Check that the base class member is accessible? 12056 } 12057 } else { 12058 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 12059 if (FoundRecord && FoundRecord->isInjectedClassName()) 12060 return false; 12061 } 12062 12063 if (isa<TypeDecl>(ND)) 12064 return HasTypenameKeyword || !IsInstantiation; 12065 12066 return !HasTypenameKeyword; 12067 } 12068 12069 std::unique_ptr<CorrectionCandidateCallback> clone() override { 12070 return std::make_unique<UsingValidatorCCC>(*this); 12071 } 12072 12073 private: 12074 bool HasTypenameKeyword; 12075 bool IsInstantiation; 12076 NestedNameSpecifier *OldNNS; 12077 CXXRecordDecl *RequireMemberOf; 12078 }; 12079 } // end anonymous namespace 12080 12081 /// Remove decls we can't actually see from a lookup being used to declare 12082 /// shadow using decls. 12083 /// 12084 /// \param S - The scope of the potential shadow decl 12085 /// \param Previous - The lookup of a potential shadow decl's name. 12086 void Sema::FilterUsingLookup(Scope *S, LookupResult &Previous) { 12087 // It is really dumb that we have to do this. 12088 LookupResult::Filter F = Previous.makeFilter(); 12089 while (F.hasNext()) { 12090 NamedDecl *D = F.next(); 12091 if (!isDeclInScope(D, CurContext, S)) 12092 F.erase(); 12093 // If we found a local extern declaration that's not ordinarily visible, 12094 // and this declaration is being added to a non-block scope, ignore it. 12095 // We're only checking for scope conflicts here, not also for violations 12096 // of the linkage rules. 12097 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 12098 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 12099 F.erase(); 12100 } 12101 F.done(); 12102 } 12103 12104 /// Builds a using declaration. 12105 /// 12106 /// \param IsInstantiation - Whether this call arises from an 12107 /// instantiation of an unresolved using declaration. We treat 12108 /// the lookup differently for these declarations. 12109 NamedDecl *Sema::BuildUsingDeclaration( 12110 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, 12111 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, 12112 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, 12113 const ParsedAttributesView &AttrList, bool IsInstantiation, 12114 bool IsUsingIfExists) { 12115 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 12116 SourceLocation IdentLoc = NameInfo.getLoc(); 12117 assert(IdentLoc.isValid() && "Invalid TargetName location."); 12118 12119 // FIXME: We ignore attributes for now. 12120 12121 // For an inheriting constructor declaration, the name of the using 12122 // declaration is the name of a constructor in this class, not in the 12123 // base class. 12124 DeclarationNameInfo UsingName = NameInfo; 12125 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName) 12126 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext)) 12127 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 12128 Context.getCanonicalType(Context.getRecordType(RD)))); 12129 12130 // Do the redeclaration lookup in the current scope. 12131 LookupResult Previous(*this, UsingName, LookupUsingDeclName, 12132 ForVisibleRedeclaration); 12133 Previous.setHideTags(false); 12134 if (S) { 12135 LookupName(Previous, S); 12136 12137 FilterUsingLookup(S, Previous); 12138 } else { 12139 assert(IsInstantiation && "no scope in non-instantiation"); 12140 if (CurContext->isRecord()) 12141 LookupQualifiedName(Previous, CurContext); 12142 else { 12143 // No redeclaration check is needed here; in non-member contexts we 12144 // diagnosed all possible conflicts with other using-declarations when 12145 // building the template: 12146 // 12147 // For a dependent non-type using declaration, the only valid case is 12148 // if we instantiate to a single enumerator. We check for conflicts 12149 // between shadow declarations we introduce, and we check in the template 12150 // definition for conflicts between a non-type using declaration and any 12151 // other declaration, which together covers all cases. 12152 // 12153 // A dependent typename using declaration will never successfully 12154 // instantiate, since it will always name a class member, so we reject 12155 // that in the template definition. 12156 } 12157 } 12158 12159 // Check for invalid redeclarations. 12160 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 12161 SS, IdentLoc, Previous)) 12162 return nullptr; 12163 12164 // 'using_if_exists' doesn't make sense on an inherited constructor. 12165 if (IsUsingIfExists && UsingName.getName().getNameKind() == 12166 DeclarationName::CXXConstructorName) { 12167 Diag(UsingLoc, diag::err_using_if_exists_on_ctor); 12168 return nullptr; 12169 } 12170 12171 DeclContext *LookupContext = computeDeclContext(SS); 12172 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 12173 if (!LookupContext || EllipsisLoc.isValid()) { 12174 NamedDecl *D; 12175 // Dependent scope, or an unexpanded pack 12176 if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, 12177 SS, NameInfo, IdentLoc)) 12178 return nullptr; 12179 12180 if (HasTypenameKeyword) { 12181 // FIXME: not all declaration name kinds are legal here 12182 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 12183 UsingLoc, TypenameLoc, 12184 QualifierLoc, 12185 IdentLoc, NameInfo.getName(), 12186 EllipsisLoc); 12187 } else { 12188 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 12189 QualifierLoc, NameInfo, EllipsisLoc); 12190 } 12191 D->setAccess(AS); 12192 CurContext->addDecl(D); 12193 ProcessDeclAttributeList(S, D, AttrList); 12194 return D; 12195 } 12196 12197 auto Build = [&](bool Invalid) { 12198 UsingDecl *UD = 12199 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 12200 UsingName, HasTypenameKeyword); 12201 UD->setAccess(AS); 12202 CurContext->addDecl(UD); 12203 ProcessDeclAttributeList(S, UD, AttrList); 12204 UD->setInvalidDecl(Invalid); 12205 return UD; 12206 }; 12207 auto BuildInvalid = [&]{ return Build(true); }; 12208 auto BuildValid = [&]{ return Build(false); }; 12209 12210 if (RequireCompleteDeclContext(SS, LookupContext)) 12211 return BuildInvalid(); 12212 12213 // Look up the target name. 12214 LookupResult R(*this, NameInfo, LookupOrdinaryName); 12215 12216 // Unlike most lookups, we don't always want to hide tag 12217 // declarations: tag names are visible through the using declaration 12218 // even if hidden by ordinary names, *except* in a dependent context 12219 // where it's important for the sanity of two-phase lookup. 12220 if (!IsInstantiation) 12221 R.setHideTags(false); 12222 12223 // For the purposes of this lookup, we have a base object type 12224 // equal to that of the current context. 12225 if (CurContext->isRecord()) { 12226 R.setBaseObjectType( 12227 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 12228 } 12229 12230 LookupQualifiedName(R, LookupContext); 12231 12232 // Validate the context, now we have a lookup 12233 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo, 12234 IdentLoc, &R)) 12235 return nullptr; 12236 12237 if (R.empty() && IsUsingIfExists) 12238 R.addDecl(UnresolvedUsingIfExistsDecl::Create(Context, CurContext, UsingLoc, 12239 UsingName.getName()), 12240 AS_public); 12241 12242 // Try to correct typos if possible. If constructor name lookup finds no 12243 // results, that means the named class has no explicit constructors, and we 12244 // suppressed declaring implicit ones (probably because it's dependent or 12245 // invalid). 12246 if (R.empty() && 12247 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { 12248 // HACK 2017-01-08: Work around an issue with libstdc++'s detection of 12249 // ::gets. Sometimes it believes that glibc provides a ::gets in cases where 12250 // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later. 12251 auto *II = NameInfo.getName().getAsIdentifierInfo(); 12252 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") && 12253 CurContext->isStdNamespace() && 12254 isa<TranslationUnitDecl>(LookupContext) && 12255 getSourceManager().isInSystemHeader(UsingLoc)) 12256 return nullptr; 12257 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 12258 dyn_cast<CXXRecordDecl>(CurContext)); 12259 if (TypoCorrection Corrected = 12260 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 12261 CTK_ErrorRecovery)) { 12262 // We reject candidates where DroppedSpecifier == true, hence the 12263 // literal '0' below. 12264 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 12265 << NameInfo.getName() << LookupContext << 0 12266 << SS.getRange()); 12267 12268 // If we picked a correction with no attached Decl we can't do anything 12269 // useful with it, bail out. 12270 NamedDecl *ND = Corrected.getCorrectionDecl(); 12271 if (!ND) 12272 return BuildInvalid(); 12273 12274 // If we corrected to an inheriting constructor, handle it as one. 12275 auto *RD = dyn_cast<CXXRecordDecl>(ND); 12276 if (RD && RD->isInjectedClassName()) { 12277 // The parent of the injected class name is the class itself. 12278 RD = cast<CXXRecordDecl>(RD->getParent()); 12279 12280 // Fix up the information we'll use to build the using declaration. 12281 if (Corrected.WillReplaceSpecifier()) { 12282 NestedNameSpecifierLocBuilder Builder; 12283 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 12284 QualifierLoc.getSourceRange()); 12285 QualifierLoc = Builder.getWithLocInContext(Context); 12286 } 12287 12288 // In this case, the name we introduce is the name of a derived class 12289 // constructor. 12290 auto *CurClass = cast<CXXRecordDecl>(CurContext); 12291 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 12292 Context.getCanonicalType(Context.getRecordType(CurClass)))); 12293 UsingName.setNamedTypeInfo(nullptr); 12294 for (auto *Ctor : LookupConstructors(RD)) 12295 R.addDecl(Ctor); 12296 R.resolveKind(); 12297 } else { 12298 // FIXME: Pick up all the declarations if we found an overloaded 12299 // function. 12300 UsingName.setName(ND->getDeclName()); 12301 R.addDecl(ND); 12302 } 12303 } else { 12304 Diag(IdentLoc, diag::err_no_member) 12305 << NameInfo.getName() << LookupContext << SS.getRange(); 12306 return BuildInvalid(); 12307 } 12308 } 12309 12310 if (R.isAmbiguous()) 12311 return BuildInvalid(); 12312 12313 if (HasTypenameKeyword) { 12314 // If we asked for a typename and got a non-type decl, error out. 12315 if (!R.getAsSingle<TypeDecl>() && 12316 !R.getAsSingle<UnresolvedUsingIfExistsDecl>()) { 12317 Diag(IdentLoc, diag::err_using_typename_non_type); 12318 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 12319 Diag((*I)->getUnderlyingDecl()->getLocation(), 12320 diag::note_using_decl_target); 12321 return BuildInvalid(); 12322 } 12323 } else { 12324 // If we asked for a non-typename and we got a type, error out, 12325 // but only if this is an instantiation of an unresolved using 12326 // decl. Otherwise just silently find the type name. 12327 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 12328 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 12329 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 12330 return BuildInvalid(); 12331 } 12332 } 12333 12334 // C++14 [namespace.udecl]p6: 12335 // A using-declaration shall not name a namespace. 12336 if (R.getAsSingle<NamespaceDecl>()) { 12337 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 12338 << SS.getRange(); 12339 return BuildInvalid(); 12340 } 12341 12342 UsingDecl *UD = BuildValid(); 12343 12344 // Some additional rules apply to inheriting constructors. 12345 if (UsingName.getName().getNameKind() == 12346 DeclarationName::CXXConstructorName) { 12347 // Suppress access diagnostics; the access check is instead performed at the 12348 // point of use for an inheriting constructor. 12349 R.suppressDiagnostics(); 12350 if (CheckInheritingConstructorUsingDecl(UD)) 12351 return UD; 12352 } 12353 12354 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 12355 UsingShadowDecl *PrevDecl = nullptr; 12356 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 12357 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 12358 } 12359 12360 return UD; 12361 } 12362 12363 NamedDecl *Sema::BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS, 12364 SourceLocation UsingLoc, 12365 SourceLocation EnumLoc, 12366 SourceLocation NameLoc, 12367 EnumDecl *ED) { 12368 bool Invalid = false; 12369 12370 if (CurContext->getRedeclContext()->isRecord()) { 12371 /// In class scope, check if this is a duplicate, for better a diagnostic. 12372 DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc); 12373 LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName, 12374 ForVisibleRedeclaration); 12375 12376 LookupName(Previous, S); 12377 12378 for (NamedDecl *D : Previous) 12379 if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D)) 12380 if (UED->getEnumDecl() == ED) { 12381 Diag(UsingLoc, diag::err_using_enum_decl_redeclaration) 12382 << SourceRange(EnumLoc, NameLoc); 12383 Diag(D->getLocation(), diag::note_using_enum_decl) << 1; 12384 Invalid = true; 12385 break; 12386 } 12387 } 12388 12389 if (RequireCompleteEnumDecl(ED, NameLoc)) 12390 Invalid = true; 12391 12392 UsingEnumDecl *UD = UsingEnumDecl::Create(Context, CurContext, UsingLoc, 12393 EnumLoc, NameLoc, ED); 12394 UD->setAccess(AS); 12395 CurContext->addDecl(UD); 12396 12397 if (Invalid) { 12398 UD->setInvalidDecl(); 12399 return UD; 12400 } 12401 12402 // Create the shadow decls for each enumerator 12403 for (EnumConstantDecl *EC : ED->enumerators()) { 12404 UsingShadowDecl *PrevDecl = nullptr; 12405 DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation()); 12406 LookupResult Previous(*this, DNI, LookupOrdinaryName, 12407 ForVisibleRedeclaration); 12408 LookupName(Previous, S); 12409 FilterUsingLookup(S, Previous); 12410 12411 if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl)) 12412 BuildUsingShadowDecl(S, UD, EC, PrevDecl); 12413 } 12414 12415 return UD; 12416 } 12417 12418 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom, 12419 ArrayRef<NamedDecl *> Expansions) { 12420 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || 12421 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || 12422 isa<UsingPackDecl>(InstantiatedFrom)); 12423 12424 auto *UPD = 12425 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions); 12426 UPD->setAccess(InstantiatedFrom->getAccess()); 12427 CurContext->addDecl(UPD); 12428 return UPD; 12429 } 12430 12431 /// Additional checks for a using declaration referring to a constructor name. 12432 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 12433 assert(!UD->hasTypename() && "expecting a constructor name"); 12434 12435 const Type *SourceType = UD->getQualifier()->getAsType(); 12436 assert(SourceType && 12437 "Using decl naming constructor doesn't have type in scope spec."); 12438 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 12439 12440 // Check whether the named type is a direct base class. 12441 bool AnyDependentBases = false; 12442 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 12443 AnyDependentBases); 12444 if (!Base && !AnyDependentBases) { 12445 Diag(UD->getUsingLoc(), 12446 diag::err_using_decl_constructor_not_in_direct_base) 12447 << UD->getNameInfo().getSourceRange() 12448 << QualType(SourceType, 0) << TargetClass; 12449 UD->setInvalidDecl(); 12450 return true; 12451 } 12452 12453 if (Base) 12454 Base->setInheritConstructors(); 12455 12456 return false; 12457 } 12458 12459 /// Checks that the given using declaration is not an invalid 12460 /// redeclaration. Note that this is checking only for the using decl 12461 /// itself, not for any ill-formedness among the UsingShadowDecls. 12462 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 12463 bool HasTypenameKeyword, 12464 const CXXScopeSpec &SS, 12465 SourceLocation NameLoc, 12466 const LookupResult &Prev) { 12467 NestedNameSpecifier *Qual = SS.getScopeRep(); 12468 12469 // C++03 [namespace.udecl]p8: 12470 // C++0x [namespace.udecl]p10: 12471 // A using-declaration is a declaration and can therefore be used 12472 // repeatedly where (and only where) multiple declarations are 12473 // allowed. 12474 // 12475 // That's in non-member contexts. 12476 if (!CurContext->getRedeclContext()->isRecord()) { 12477 // A dependent qualifier outside a class can only ever resolve to an 12478 // enumeration type. Therefore it conflicts with any other non-type 12479 // declaration in the same scope. 12480 // FIXME: How should we check for dependent type-type conflicts at block 12481 // scope? 12482 if (Qual->isDependent() && !HasTypenameKeyword) { 12483 for (auto *D : Prev) { 12484 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) { 12485 bool OldCouldBeEnumerator = 12486 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D); 12487 Diag(NameLoc, 12488 OldCouldBeEnumerator ? diag::err_redefinition 12489 : diag::err_redefinition_different_kind) 12490 << Prev.getLookupName(); 12491 Diag(D->getLocation(), diag::note_previous_definition); 12492 return true; 12493 } 12494 } 12495 } 12496 return false; 12497 } 12498 12499 const NestedNameSpecifier *CNNS = 12500 Context.getCanonicalNestedNameSpecifier(Qual); 12501 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 12502 NamedDecl *D = *I; 12503 12504 bool DTypename; 12505 NestedNameSpecifier *DQual; 12506 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 12507 DTypename = UD->hasTypename(); 12508 DQual = UD->getQualifier(); 12509 } else if (UnresolvedUsingValueDecl *UD 12510 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 12511 DTypename = false; 12512 DQual = UD->getQualifier(); 12513 } else if (UnresolvedUsingTypenameDecl *UD 12514 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 12515 DTypename = true; 12516 DQual = UD->getQualifier(); 12517 } else continue; 12518 12519 // using decls differ if one says 'typename' and the other doesn't. 12520 // FIXME: non-dependent using decls? 12521 if (HasTypenameKeyword != DTypename) continue; 12522 12523 // using decls differ if they name different scopes (but note that 12524 // template instantiation can cause this check to trigger when it 12525 // didn't before instantiation). 12526 if (CNNS != Context.getCanonicalNestedNameSpecifier(DQual)) 12527 continue; 12528 12529 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 12530 Diag(D->getLocation(), diag::note_using_decl) << 1; 12531 return true; 12532 } 12533 12534 return false; 12535 } 12536 12537 /// Checks that the given nested-name qualifier used in a using decl 12538 /// in the current context is appropriately related to the current 12539 /// scope. If an error is found, diagnoses it and returns true. 12540 /// R is nullptr, if the caller has not (yet) done a lookup, otherwise it's the 12541 /// result of that lookup. UD is likewise nullptr, except when we have an 12542 /// already-populated UsingDecl whose shadow decls contain the same information 12543 /// (i.e. we're instantiating a UsingDecl with non-dependent scope). 12544 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename, 12545 const CXXScopeSpec &SS, 12546 const DeclarationNameInfo &NameInfo, 12547 SourceLocation NameLoc, 12548 const LookupResult *R, const UsingDecl *UD) { 12549 DeclContext *NamedContext = computeDeclContext(SS); 12550 assert(bool(NamedContext) == (R || UD) && !(R && UD) && 12551 "resolvable context must have exactly one set of decls"); 12552 12553 // C++ 20 permits using an enumerator that does not have a class-hierarchy 12554 // relationship. 12555 bool Cxx20Enumerator = false; 12556 if (NamedContext) { 12557 EnumConstantDecl *EC = nullptr; 12558 if (R) 12559 EC = R->getAsSingle<EnumConstantDecl>(); 12560 else if (UD && UD->shadow_size() == 1) 12561 EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl()); 12562 if (EC) 12563 Cxx20Enumerator = getLangOpts().CPlusPlus20; 12564 12565 if (auto *ED = dyn_cast<EnumDecl>(NamedContext)) { 12566 // C++14 [namespace.udecl]p7: 12567 // A using-declaration shall not name a scoped enumerator. 12568 // C++20 p1099 permits enumerators. 12569 if (EC && R && ED->isScoped()) 12570 Diag(SS.getBeginLoc(), 12571 getLangOpts().CPlusPlus20 12572 ? diag::warn_cxx17_compat_using_decl_scoped_enumerator 12573 : diag::ext_using_decl_scoped_enumerator) 12574 << SS.getRange(); 12575 12576 // We want to consider the scope of the enumerator 12577 NamedContext = ED->getDeclContext(); 12578 } 12579 } 12580 12581 if (!CurContext->isRecord()) { 12582 // C++03 [namespace.udecl]p3: 12583 // C++0x [namespace.udecl]p8: 12584 // A using-declaration for a class member shall be a member-declaration. 12585 // C++20 [namespace.udecl]p7 12586 // ... other than an enumerator ... 12587 12588 // If we weren't able to compute a valid scope, it might validly be a 12589 // dependent class or enumeration scope. If we have a 'typename' keyword, 12590 // the scope must resolve to a class type. 12591 if (NamedContext ? !NamedContext->getRedeclContext()->isRecord() 12592 : !HasTypename) 12593 return false; // OK 12594 12595 Diag(NameLoc, 12596 Cxx20Enumerator 12597 ? diag::warn_cxx17_compat_using_decl_class_member_enumerator 12598 : diag::err_using_decl_can_not_refer_to_class_member) 12599 << SS.getRange(); 12600 12601 if (Cxx20Enumerator) 12602 return false; // OK 12603 12604 auto *RD = NamedContext 12605 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext()) 12606 : nullptr; 12607 if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) { 12608 // See if there's a helpful fixit 12609 12610 if (!R) { 12611 // We will have already diagnosed the problem on the template 12612 // definition, Maybe we should do so again? 12613 } else if (R->getAsSingle<TypeDecl>()) { 12614 if (getLangOpts().CPlusPlus11) { 12615 // Convert 'using X::Y;' to 'using Y = X::Y;'. 12616 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 12617 << 0 // alias declaration 12618 << FixItHint::CreateInsertion(SS.getBeginLoc(), 12619 NameInfo.getName().getAsString() + 12620 " = "); 12621 } else { 12622 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 12623 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc()); 12624 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 12625 << 1 // typedef declaration 12626 << FixItHint::CreateReplacement(UsingLoc, "typedef") 12627 << FixItHint::CreateInsertion( 12628 InsertLoc, " " + NameInfo.getName().getAsString()); 12629 } 12630 } else if (R->getAsSingle<VarDecl>()) { 12631 // Don't provide a fixit outside C++11 mode; we don't want to suggest 12632 // repeating the type of the static data member here. 12633 FixItHint FixIt; 12634 if (getLangOpts().CPlusPlus11) { 12635 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 12636 FixIt = FixItHint::CreateReplacement( 12637 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 12638 } 12639 12640 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 12641 << 2 // reference declaration 12642 << FixIt; 12643 } else if (R->getAsSingle<EnumConstantDecl>()) { 12644 // Don't provide a fixit outside C++11 mode; we don't want to suggest 12645 // repeating the type of the enumeration here, and we can't do so if 12646 // the type is anonymous. 12647 FixItHint FixIt; 12648 if (getLangOpts().CPlusPlus11) { 12649 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 12650 FixIt = FixItHint::CreateReplacement( 12651 UsingLoc, 12652 "constexpr auto " + NameInfo.getName().getAsString() + " = "); 12653 } 12654 12655 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 12656 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable 12657 << FixIt; 12658 } 12659 } 12660 12661 return true; // Fail 12662 } 12663 12664 // If the named context is dependent, we can't decide much. 12665 if (!NamedContext) { 12666 // FIXME: in C++0x, we can diagnose if we can prove that the 12667 // nested-name-specifier does not refer to a base class, which is 12668 // still possible in some cases. 12669 12670 // Otherwise we have to conservatively report that things might be 12671 // okay. 12672 return false; 12673 } 12674 12675 // The current scope is a record. 12676 if (!NamedContext->isRecord()) { 12677 // Ideally this would point at the last name in the specifier, 12678 // but we don't have that level of source info. 12679 Diag(SS.getBeginLoc(), 12680 Cxx20Enumerator 12681 ? diag::warn_cxx17_compat_using_decl_non_member_enumerator 12682 : diag::err_using_decl_nested_name_specifier_is_not_class) 12683 << SS.getScopeRep() << SS.getRange(); 12684 12685 if (Cxx20Enumerator) 12686 return false; // OK 12687 12688 return true; 12689 } 12690 12691 if (!NamedContext->isDependentContext() && 12692 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 12693 return true; 12694 12695 if (getLangOpts().CPlusPlus11) { 12696 // C++11 [namespace.udecl]p3: 12697 // In a using-declaration used as a member-declaration, the 12698 // nested-name-specifier shall name a base class of the class 12699 // being defined. 12700 12701 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 12702 cast<CXXRecordDecl>(NamedContext))) { 12703 12704 if (Cxx20Enumerator) { 12705 Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator) 12706 << SS.getRange(); 12707 return false; 12708 } 12709 12710 if (CurContext == NamedContext) { 12711 Diag(SS.getBeginLoc(), 12712 diag::err_using_decl_nested_name_specifier_is_current_class) 12713 << SS.getRange(); 12714 return !getLangOpts().CPlusPlus20; 12715 } 12716 12717 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) { 12718 Diag(SS.getBeginLoc(), 12719 diag::err_using_decl_nested_name_specifier_is_not_base_class) 12720 << SS.getScopeRep() << cast<CXXRecordDecl>(CurContext) 12721 << SS.getRange(); 12722 } 12723 return true; 12724 } 12725 12726 return false; 12727 } 12728 12729 // C++03 [namespace.udecl]p4: 12730 // A using-declaration used as a member-declaration shall refer 12731 // to a member of a base class of the class being defined [etc.]. 12732 12733 // Salient point: SS doesn't have to name a base class as long as 12734 // lookup only finds members from base classes. Therefore we can 12735 // diagnose here only if we can prove that that can't happen, 12736 // i.e. if the class hierarchies provably don't intersect. 12737 12738 // TODO: it would be nice if "definitely valid" results were cached 12739 // in the UsingDecl and UsingShadowDecl so that these checks didn't 12740 // need to be repeated. 12741 12742 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases; 12743 auto Collect = [&Bases](const CXXRecordDecl *Base) { 12744 Bases.insert(Base); 12745 return true; 12746 }; 12747 12748 // Collect all bases. Return false if we find a dependent base. 12749 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect)) 12750 return false; 12751 12752 // Returns true if the base is dependent or is one of the accumulated base 12753 // classes. 12754 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) { 12755 return !Bases.count(Base); 12756 }; 12757 12758 // Return false if the class has a dependent base or if it or one 12759 // of its bases is present in the base set of the current context. 12760 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) || 12761 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase)) 12762 return false; 12763 12764 Diag(SS.getRange().getBegin(), 12765 diag::err_using_decl_nested_name_specifier_is_not_base_class) 12766 << SS.getScopeRep() 12767 << cast<CXXRecordDecl>(CurContext) 12768 << SS.getRange(); 12769 12770 return true; 12771 } 12772 12773 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS, 12774 MultiTemplateParamsArg TemplateParamLists, 12775 SourceLocation UsingLoc, UnqualifiedId &Name, 12776 const ParsedAttributesView &AttrList, 12777 TypeResult Type, Decl *DeclFromDeclSpec) { 12778 // Skip up to the relevant declaration scope. 12779 while (S->isTemplateParamScope()) 12780 S = S->getParent(); 12781 assert((S->getFlags() & Scope::DeclScope) && 12782 "got alias-declaration outside of declaration scope"); 12783 12784 if (Type.isInvalid()) 12785 return nullptr; 12786 12787 bool Invalid = false; 12788 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 12789 TypeSourceInfo *TInfo = nullptr; 12790 GetTypeFromParser(Type.get(), &TInfo); 12791 12792 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 12793 return nullptr; 12794 12795 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 12796 UPPC_DeclarationType)) { 12797 Invalid = true; 12798 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 12799 TInfo->getTypeLoc().getBeginLoc()); 12800 } 12801 12802 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 12803 TemplateParamLists.size() 12804 ? forRedeclarationInCurContext() 12805 : ForVisibleRedeclaration); 12806 LookupName(Previous, S); 12807 12808 // Warn about shadowing the name of a template parameter. 12809 if (Previous.isSingleResult() && 12810 Previous.getFoundDecl()->isTemplateParameter()) { 12811 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 12812 Previous.clear(); 12813 } 12814 12815 assert(Name.Kind == UnqualifiedIdKind::IK_Identifier && 12816 "name in alias declaration must be an identifier"); 12817 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 12818 Name.StartLocation, 12819 Name.Identifier, TInfo); 12820 12821 NewTD->setAccess(AS); 12822 12823 if (Invalid) 12824 NewTD->setInvalidDecl(); 12825 12826 ProcessDeclAttributeList(S, NewTD, AttrList); 12827 AddPragmaAttributes(S, NewTD); 12828 12829 CheckTypedefForVariablyModifiedType(S, NewTD); 12830 Invalid |= NewTD->isInvalidDecl(); 12831 12832 bool Redeclaration = false; 12833 12834 NamedDecl *NewND; 12835 if (TemplateParamLists.size()) { 12836 TypeAliasTemplateDecl *OldDecl = nullptr; 12837 TemplateParameterList *OldTemplateParams = nullptr; 12838 12839 if (TemplateParamLists.size() != 1) { 12840 Diag(UsingLoc, diag::err_alias_template_extra_headers) 12841 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 12842 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 12843 } 12844 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 12845 12846 // Check that we can declare a template here. 12847 if (CheckTemplateDeclScope(S, TemplateParams)) 12848 return nullptr; 12849 12850 // Only consider previous declarations in the same scope. 12851 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 12852 /*ExplicitInstantiationOrSpecialization*/false); 12853 if (!Previous.empty()) { 12854 Redeclaration = true; 12855 12856 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 12857 if (!OldDecl && !Invalid) { 12858 Diag(UsingLoc, diag::err_redefinition_different_kind) 12859 << Name.Identifier; 12860 12861 NamedDecl *OldD = Previous.getRepresentativeDecl(); 12862 if (OldD->getLocation().isValid()) 12863 Diag(OldD->getLocation(), diag::note_previous_definition); 12864 12865 Invalid = true; 12866 } 12867 12868 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 12869 if (TemplateParameterListsAreEqual(TemplateParams, 12870 OldDecl->getTemplateParameters(), 12871 /*Complain=*/true, 12872 TPL_TemplateMatch)) 12873 OldTemplateParams = 12874 OldDecl->getMostRecentDecl()->getTemplateParameters(); 12875 else 12876 Invalid = true; 12877 12878 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 12879 if (!Invalid && 12880 !Context.hasSameType(OldTD->getUnderlyingType(), 12881 NewTD->getUnderlyingType())) { 12882 // FIXME: The C++0x standard does not clearly say this is ill-formed, 12883 // but we can't reasonably accept it. 12884 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 12885 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 12886 if (OldTD->getLocation().isValid()) 12887 Diag(OldTD->getLocation(), diag::note_previous_definition); 12888 Invalid = true; 12889 } 12890 } 12891 } 12892 12893 // Merge any previous default template arguments into our parameters, 12894 // and check the parameter list. 12895 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 12896 TPC_TypeAliasTemplate)) 12897 return nullptr; 12898 12899 TypeAliasTemplateDecl *NewDecl = 12900 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 12901 Name.Identifier, TemplateParams, 12902 NewTD); 12903 NewTD->setDescribedAliasTemplate(NewDecl); 12904 12905 NewDecl->setAccess(AS); 12906 12907 if (Invalid) 12908 NewDecl->setInvalidDecl(); 12909 else if (OldDecl) { 12910 NewDecl->setPreviousDecl(OldDecl); 12911 CheckRedeclarationModuleOwnership(NewDecl, OldDecl); 12912 } 12913 12914 NewND = NewDecl; 12915 } else { 12916 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { 12917 setTagNameForLinkagePurposes(TD, NewTD); 12918 handleTagNumbering(TD, S); 12919 } 12920 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 12921 NewND = NewTD; 12922 } 12923 12924 PushOnScopeChains(NewND, S); 12925 ActOnDocumentableDecl(NewND); 12926 return NewND; 12927 } 12928 12929 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 12930 SourceLocation AliasLoc, 12931 IdentifierInfo *Alias, CXXScopeSpec &SS, 12932 SourceLocation IdentLoc, 12933 IdentifierInfo *Ident) { 12934 12935 // Lookup the namespace name. 12936 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 12937 LookupParsedName(R, S, &SS); 12938 12939 if (R.isAmbiguous()) 12940 return nullptr; 12941 12942 if (R.empty()) { 12943 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 12944 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 12945 return nullptr; 12946 } 12947 } 12948 assert(!R.isAmbiguous() && !R.empty()); 12949 NamedDecl *ND = R.getRepresentativeDecl(); 12950 12951 // Check if we have a previous declaration with the same name. 12952 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName, 12953 ForVisibleRedeclaration); 12954 LookupName(PrevR, S); 12955 12956 // Check we're not shadowing a template parameter. 12957 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) { 12958 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl()); 12959 PrevR.clear(); 12960 } 12961 12962 // Filter out any other lookup result from an enclosing scope. 12963 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false, 12964 /*AllowInlineNamespace*/false); 12965 12966 // Find the previous declaration and check that we can redeclare it. 12967 NamespaceAliasDecl *Prev = nullptr; 12968 if (PrevR.isSingleResult()) { 12969 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl(); 12970 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 12971 // We already have an alias with the same name that points to the same 12972 // namespace; check that it matches. 12973 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) { 12974 Prev = AD; 12975 } else if (isVisible(PrevDecl)) { 12976 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 12977 << Alias; 12978 Diag(AD->getLocation(), diag::note_previous_namespace_alias) 12979 << AD->getNamespace(); 12980 return nullptr; 12981 } 12982 } else if (isVisible(PrevDecl)) { 12983 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl()) 12984 ? diag::err_redefinition 12985 : diag::err_redefinition_different_kind; 12986 Diag(AliasLoc, DiagID) << Alias; 12987 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 12988 return nullptr; 12989 } 12990 } 12991 12992 // The use of a nested name specifier may trigger deprecation warnings. 12993 DiagnoseUseOfDecl(ND, IdentLoc); 12994 12995 NamespaceAliasDecl *AliasDecl = 12996 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 12997 Alias, SS.getWithLocInContext(Context), 12998 IdentLoc, ND); 12999 if (Prev) 13000 AliasDecl->setPreviousDecl(Prev); 13001 13002 PushOnScopeChains(AliasDecl, S); 13003 return AliasDecl; 13004 } 13005 13006 namespace { 13007 struct SpecialMemberExceptionSpecInfo 13008 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> { 13009 SourceLocation Loc; 13010 Sema::ImplicitExceptionSpecification ExceptSpec; 13011 13012 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD, 13013 Sema::CXXSpecialMember CSM, 13014 Sema::InheritedConstructorInfo *ICI, 13015 SourceLocation Loc) 13016 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {} 13017 13018 bool visitBase(CXXBaseSpecifier *Base); 13019 bool visitField(FieldDecl *FD); 13020 13021 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 13022 unsigned Quals); 13023 13024 void visitSubobjectCall(Subobject Subobj, 13025 Sema::SpecialMemberOverloadResult SMOR); 13026 }; 13027 } 13028 13029 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) { 13030 auto *RT = Base->getType()->getAs<RecordType>(); 13031 if (!RT) 13032 return false; 13033 13034 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl()); 13035 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 13036 if (auto *BaseCtor = SMOR.getMethod()) { 13037 visitSubobjectCall(Base, BaseCtor); 13038 return false; 13039 } 13040 13041 visitClassSubobject(BaseClass, Base, 0); 13042 return false; 13043 } 13044 13045 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) { 13046 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) { 13047 Expr *E = FD->getInClassInitializer(); 13048 if (!E) 13049 // FIXME: It's a little wasteful to build and throw away a 13050 // CXXDefaultInitExpr here. 13051 // FIXME: We should have a single context note pointing at Loc, and 13052 // this location should be MD->getLocation() instead, since that's 13053 // the location where we actually use the default init expression. 13054 E = S.BuildCXXDefaultInitExpr(Loc, FD).get(); 13055 if (E) 13056 ExceptSpec.CalledExpr(E); 13057 } else if (auto *RT = S.Context.getBaseElementType(FD->getType()) 13058 ->getAs<RecordType>()) { 13059 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD, 13060 FD->getType().getCVRQualifiers()); 13061 } 13062 return false; 13063 } 13064 13065 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class, 13066 Subobject Subobj, 13067 unsigned Quals) { 13068 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 13069 bool IsMutable = Field && Field->isMutable(); 13070 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable)); 13071 } 13072 13073 void SpecialMemberExceptionSpecInfo::visitSubobjectCall( 13074 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) { 13075 // Note, if lookup fails, it doesn't matter what exception specification we 13076 // choose because the special member will be deleted. 13077 if (CXXMethodDecl *MD = SMOR.getMethod()) 13078 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD); 13079 } 13080 13081 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) { 13082 llvm::APSInt Result; 13083 ExprResult Converted = CheckConvertedConstantExpression( 13084 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool); 13085 ExplicitSpec.setExpr(Converted.get()); 13086 if (Converted.isUsable() && !Converted.get()->isValueDependent()) { 13087 ExplicitSpec.setKind(Result.getBoolValue() 13088 ? ExplicitSpecKind::ResolvedTrue 13089 : ExplicitSpecKind::ResolvedFalse); 13090 return true; 13091 } 13092 ExplicitSpec.setKind(ExplicitSpecKind::Unresolved); 13093 return false; 13094 } 13095 13096 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) { 13097 ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved); 13098 if (!ExplicitExpr->isTypeDependent()) 13099 tryResolveExplicitSpecifier(ES); 13100 return ES; 13101 } 13102 13103 static Sema::ImplicitExceptionSpecification 13104 ComputeDefaultedSpecialMemberExceptionSpec( 13105 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 13106 Sema::InheritedConstructorInfo *ICI) { 13107 ComputingExceptionSpec CES(S, MD, Loc); 13108 13109 CXXRecordDecl *ClassDecl = MD->getParent(); 13110 13111 // C++ [except.spec]p14: 13112 // An implicitly declared special member function (Clause 12) shall have an 13113 // exception-specification. [...] 13114 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation()); 13115 if (ClassDecl->isInvalidDecl()) 13116 return Info.ExceptSpec; 13117 13118 // FIXME: If this diagnostic fires, we're probably missing a check for 13119 // attempting to resolve an exception specification before it's known 13120 // at a higher level. 13121 if (S.RequireCompleteType(MD->getLocation(), 13122 S.Context.getRecordType(ClassDecl), 13123 diag::err_exception_spec_incomplete_type)) 13124 return Info.ExceptSpec; 13125 13126 // C++1z [except.spec]p7: 13127 // [Look for exceptions thrown by] a constructor selected [...] to 13128 // initialize a potentially constructed subobject, 13129 // C++1z [except.spec]p8: 13130 // The exception specification for an implicitly-declared destructor, or a 13131 // destructor without a noexcept-specifier, is potentially-throwing if and 13132 // only if any of the destructors for any of its potentially constructed 13133 // subojects is potentially throwing. 13134 // FIXME: We respect the first rule but ignore the "potentially constructed" 13135 // in the second rule to resolve a core issue (no number yet) that would have 13136 // us reject: 13137 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; }; 13138 // struct B : A {}; 13139 // struct C : B { void f(); }; 13140 // ... due to giving B::~B() a non-throwing exception specification. 13141 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases 13142 : Info.VisitAllBases); 13143 13144 return Info.ExceptSpec; 13145 } 13146 13147 namespace { 13148 /// RAII object to register a special member as being currently declared. 13149 struct DeclaringSpecialMember { 13150 Sema &S; 13151 Sema::SpecialMemberDecl D; 13152 Sema::ContextRAII SavedContext; 13153 bool WasAlreadyBeingDeclared; 13154 13155 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 13156 : S(S), D(RD, CSM), SavedContext(S, RD) { 13157 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 13158 if (WasAlreadyBeingDeclared) 13159 // This almost never happens, but if it does, ensure that our cache 13160 // doesn't contain a stale result. 13161 S.SpecialMemberCache.clear(); 13162 else { 13163 // Register a note to be produced if we encounter an error while 13164 // declaring the special member. 13165 Sema::CodeSynthesisContext Ctx; 13166 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember; 13167 // FIXME: We don't have a location to use here. Using the class's 13168 // location maintains the fiction that we declare all special members 13169 // with the class, but (1) it's not clear that lying about that helps our 13170 // users understand what's going on, and (2) there may be outer contexts 13171 // on the stack (some of which are relevant) and printing them exposes 13172 // our lies. 13173 Ctx.PointOfInstantiation = RD->getLocation(); 13174 Ctx.Entity = RD; 13175 Ctx.SpecialMember = CSM; 13176 S.pushCodeSynthesisContext(Ctx); 13177 } 13178 } 13179 ~DeclaringSpecialMember() { 13180 if (!WasAlreadyBeingDeclared) { 13181 S.SpecialMembersBeingDeclared.erase(D); 13182 S.popCodeSynthesisContext(); 13183 } 13184 } 13185 13186 /// Are we already trying to declare this special member? 13187 bool isAlreadyBeingDeclared() const { 13188 return WasAlreadyBeingDeclared; 13189 } 13190 }; 13191 } 13192 13193 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) { 13194 // Look up any existing declarations, but don't trigger declaration of all 13195 // implicit special members with this name. 13196 DeclarationName Name = FD->getDeclName(); 13197 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName, 13198 ForExternalRedeclaration); 13199 for (auto *D : FD->getParent()->lookup(Name)) 13200 if (auto *Acceptable = R.getAcceptableDecl(D)) 13201 R.addDecl(Acceptable); 13202 R.resolveKind(); 13203 R.suppressDiagnostics(); 13204 13205 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false); 13206 } 13207 13208 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem, 13209 QualType ResultTy, 13210 ArrayRef<QualType> Args) { 13211 // Build an exception specification pointing back at this constructor. 13212 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem); 13213 13214 LangAS AS = getDefaultCXXMethodAddrSpace(); 13215 if (AS != LangAS::Default) { 13216 EPI.TypeQuals.addAddressSpace(AS); 13217 } 13218 13219 auto QT = Context.getFunctionType(ResultTy, Args, EPI); 13220 SpecialMem->setType(QT); 13221 13222 // During template instantiation of implicit special member functions we need 13223 // a reliable TypeSourceInfo for the function prototype in order to allow 13224 // functions to be substituted. 13225 if (inTemplateInstantiation() && 13226 cast<CXXRecordDecl>(SpecialMem->getParent())->isLambda()) { 13227 TypeSourceInfo *TSI = 13228 Context.getTrivialTypeSourceInfo(SpecialMem->getType()); 13229 SpecialMem->setTypeSourceInfo(TSI); 13230 } 13231 } 13232 13233 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 13234 CXXRecordDecl *ClassDecl) { 13235 // C++ [class.ctor]p5: 13236 // A default constructor for a class X is a constructor of class X 13237 // that can be called without an argument. If there is no 13238 // user-declared constructor for class X, a default constructor is 13239 // implicitly declared. An implicitly-declared default constructor 13240 // is an inline public member of its class. 13241 assert(ClassDecl->needsImplicitDefaultConstructor() && 13242 "Should not build implicit default constructor!"); 13243 13244 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 13245 if (DSM.isAlreadyBeingDeclared()) 13246 return nullptr; 13247 13248 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 13249 CXXDefaultConstructor, 13250 false); 13251 13252 // Create the actual constructor declaration. 13253 CanQualType ClassType 13254 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 13255 SourceLocation ClassLoc = ClassDecl->getLocation(); 13256 DeclarationName Name 13257 = Context.DeclarationNames.getCXXConstructorName(ClassType); 13258 DeclarationNameInfo NameInfo(Name, ClassLoc); 13259 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 13260 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(), 13261 /*TInfo=*/nullptr, ExplicitSpecifier(), 13262 getCurFPFeatures().isFPConstrained(), 13263 /*isInline=*/true, /*isImplicitlyDeclared=*/true, 13264 Constexpr ? ConstexprSpecKind::Constexpr 13265 : ConstexprSpecKind::Unspecified); 13266 DefaultCon->setAccess(AS_public); 13267 DefaultCon->setDefaulted(); 13268 13269 if (getLangOpts().CUDA) { 13270 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 13271 DefaultCon, 13272 /* ConstRHS */ false, 13273 /* Diagnose */ false); 13274 } 13275 13276 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None); 13277 13278 // We don't need to use SpecialMemberIsTrivial here; triviality for default 13279 // constructors is easy to compute. 13280 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 13281 13282 // Note that we have declared this constructor. 13283 ++getASTContext().NumImplicitDefaultConstructorsDeclared; 13284 13285 Scope *S = getScopeForContext(ClassDecl); 13286 CheckImplicitSpecialMemberDeclaration(S, DefaultCon); 13287 13288 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 13289 SetDeclDeleted(DefaultCon, ClassLoc); 13290 13291 if (S) 13292 PushOnScopeChains(DefaultCon, S, false); 13293 ClassDecl->addDecl(DefaultCon); 13294 13295 return DefaultCon; 13296 } 13297 13298 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 13299 CXXConstructorDecl *Constructor) { 13300 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 13301 !Constructor->doesThisDeclarationHaveABody() && 13302 !Constructor->isDeleted()) && 13303 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 13304 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 13305 return; 13306 13307 CXXRecordDecl *ClassDecl = Constructor->getParent(); 13308 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 13309 13310 SynthesizedFunctionScope Scope(*this, Constructor); 13311 13312 // The exception specification is needed because we are defining the 13313 // function. 13314 ResolveExceptionSpec(CurrentLocation, 13315 Constructor->getType()->castAs<FunctionProtoType>()); 13316 MarkVTableUsed(CurrentLocation, ClassDecl); 13317 13318 // Add a context note for diagnostics produced after this point. 13319 Scope.addContextNote(CurrentLocation); 13320 13321 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) { 13322 Constructor->setInvalidDecl(); 13323 return; 13324 } 13325 13326 SourceLocation Loc = Constructor->getEndLoc().isValid() 13327 ? Constructor->getEndLoc() 13328 : Constructor->getLocation(); 13329 Constructor->setBody(new (Context) CompoundStmt(Loc)); 13330 Constructor->markUsed(Context); 13331 13332 if (ASTMutationListener *L = getASTMutationListener()) { 13333 L->CompletedImplicitDefinition(Constructor); 13334 } 13335 13336 DiagnoseUninitializedFields(*this, Constructor); 13337 } 13338 13339 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 13340 // Perform any delayed checks on exception specifications. 13341 CheckDelayedMemberExceptionSpecs(); 13342 } 13343 13344 /// Find or create the fake constructor we synthesize to model constructing an 13345 /// object of a derived class via a constructor of a base class. 13346 CXXConstructorDecl * 13347 Sema::findInheritingConstructor(SourceLocation Loc, 13348 CXXConstructorDecl *BaseCtor, 13349 ConstructorUsingShadowDecl *Shadow) { 13350 CXXRecordDecl *Derived = Shadow->getParent(); 13351 SourceLocation UsingLoc = Shadow->getLocation(); 13352 13353 // FIXME: Add a new kind of DeclarationName for an inherited constructor. 13354 // For now we use the name of the base class constructor as a member of the 13355 // derived class to indicate a (fake) inherited constructor name. 13356 DeclarationName Name = BaseCtor->getDeclName(); 13357 13358 // Check to see if we already have a fake constructor for this inherited 13359 // constructor call. 13360 for (NamedDecl *Ctor : Derived->lookup(Name)) 13361 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor) 13362 ->getInheritedConstructor() 13363 .getConstructor(), 13364 BaseCtor)) 13365 return cast<CXXConstructorDecl>(Ctor); 13366 13367 DeclarationNameInfo NameInfo(Name, UsingLoc); 13368 TypeSourceInfo *TInfo = 13369 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc); 13370 FunctionProtoTypeLoc ProtoLoc = 13371 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 13372 13373 // Check the inherited constructor is valid and find the list of base classes 13374 // from which it was inherited. 13375 InheritedConstructorInfo ICI(*this, Loc, Shadow); 13376 13377 bool Constexpr = 13378 BaseCtor->isConstexpr() && 13379 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor, 13380 false, BaseCtor, &ICI); 13381 13382 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 13383 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo, 13384 BaseCtor->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(), 13385 /*isInline=*/true, 13386 /*isImplicitlyDeclared=*/true, 13387 Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified, 13388 InheritedConstructor(Shadow, BaseCtor), 13389 BaseCtor->getTrailingRequiresClause()); 13390 if (Shadow->isInvalidDecl()) 13391 DerivedCtor->setInvalidDecl(); 13392 13393 // Build an unevaluated exception specification for this fake constructor. 13394 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>(); 13395 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 13396 EPI.ExceptionSpec.Type = EST_Unevaluated; 13397 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 13398 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 13399 FPT->getParamTypes(), EPI)); 13400 13401 // Build the parameter declarations. 13402 SmallVector<ParmVarDecl *, 16> ParamDecls; 13403 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 13404 TypeSourceInfo *TInfo = 13405 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 13406 ParmVarDecl *PD = ParmVarDecl::Create( 13407 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 13408 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr); 13409 PD->setScopeInfo(0, I); 13410 PD->setImplicit(); 13411 // Ensure attributes are propagated onto parameters (this matters for 13412 // format, pass_object_size, ...). 13413 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I)); 13414 ParamDecls.push_back(PD); 13415 ProtoLoc.setParam(I, PD); 13416 } 13417 13418 // Set up the new constructor. 13419 assert(!BaseCtor->isDeleted() && "should not use deleted constructor"); 13420 DerivedCtor->setAccess(BaseCtor->getAccess()); 13421 DerivedCtor->setParams(ParamDecls); 13422 Derived->addDecl(DerivedCtor); 13423 13424 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI)) 13425 SetDeclDeleted(DerivedCtor, UsingLoc); 13426 13427 return DerivedCtor; 13428 } 13429 13430 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) { 13431 InheritedConstructorInfo ICI(*this, Ctor->getLocation(), 13432 Ctor->getInheritedConstructor().getShadowDecl()); 13433 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI, 13434 /*Diagnose*/true); 13435 } 13436 13437 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 13438 CXXConstructorDecl *Constructor) { 13439 CXXRecordDecl *ClassDecl = Constructor->getParent(); 13440 assert(Constructor->getInheritedConstructor() && 13441 !Constructor->doesThisDeclarationHaveABody() && 13442 !Constructor->isDeleted()); 13443 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 13444 return; 13445 13446 // Initializations are performed "as if by a defaulted default constructor", 13447 // so enter the appropriate scope. 13448 SynthesizedFunctionScope Scope(*this, Constructor); 13449 13450 // The exception specification is needed because we are defining the 13451 // function. 13452 ResolveExceptionSpec(CurrentLocation, 13453 Constructor->getType()->castAs<FunctionProtoType>()); 13454 MarkVTableUsed(CurrentLocation, ClassDecl); 13455 13456 // Add a context note for diagnostics produced after this point. 13457 Scope.addContextNote(CurrentLocation); 13458 13459 ConstructorUsingShadowDecl *Shadow = 13460 Constructor->getInheritedConstructor().getShadowDecl(); 13461 CXXConstructorDecl *InheritedCtor = 13462 Constructor->getInheritedConstructor().getConstructor(); 13463 13464 // [class.inhctor.init]p1: 13465 // initialization proceeds as if a defaulted default constructor is used to 13466 // initialize the D object and each base class subobject from which the 13467 // constructor was inherited 13468 13469 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow); 13470 CXXRecordDecl *RD = Shadow->getParent(); 13471 SourceLocation InitLoc = Shadow->getLocation(); 13472 13473 // Build explicit initializers for all base classes from which the 13474 // constructor was inherited. 13475 SmallVector<CXXCtorInitializer*, 8> Inits; 13476 for (bool VBase : {false, true}) { 13477 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) { 13478 if (B.isVirtual() != VBase) 13479 continue; 13480 13481 auto *BaseRD = B.getType()->getAsCXXRecordDecl(); 13482 if (!BaseRD) 13483 continue; 13484 13485 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor); 13486 if (!BaseCtor.first) 13487 continue; 13488 13489 MarkFunctionReferenced(CurrentLocation, BaseCtor.first); 13490 ExprResult Init = new (Context) CXXInheritedCtorInitExpr( 13491 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second); 13492 13493 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc); 13494 Inits.push_back(new (Context) CXXCtorInitializer( 13495 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc, 13496 SourceLocation())); 13497 } 13498 } 13499 13500 // We now proceed as if for a defaulted default constructor, with the relevant 13501 // initializers replaced. 13502 13503 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) { 13504 Constructor->setInvalidDecl(); 13505 return; 13506 } 13507 13508 Constructor->setBody(new (Context) CompoundStmt(InitLoc)); 13509 Constructor->markUsed(Context); 13510 13511 if (ASTMutationListener *L = getASTMutationListener()) { 13512 L->CompletedImplicitDefinition(Constructor); 13513 } 13514 13515 DiagnoseUninitializedFields(*this, Constructor); 13516 } 13517 13518 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 13519 // C++ [class.dtor]p2: 13520 // If a class has no user-declared destructor, a destructor is 13521 // declared implicitly. An implicitly-declared destructor is an 13522 // inline public member of its class. 13523 assert(ClassDecl->needsImplicitDestructor()); 13524 13525 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 13526 if (DSM.isAlreadyBeingDeclared()) 13527 return nullptr; 13528 13529 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 13530 CXXDestructor, 13531 false); 13532 13533 // Create the actual destructor declaration. 13534 CanQualType ClassType 13535 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 13536 SourceLocation ClassLoc = ClassDecl->getLocation(); 13537 DeclarationName Name 13538 = Context.DeclarationNames.getCXXDestructorName(ClassType); 13539 DeclarationNameInfo NameInfo(Name, ClassLoc); 13540 CXXDestructorDecl *Destructor = CXXDestructorDecl::Create( 13541 Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr, 13542 getCurFPFeatures().isFPConstrained(), 13543 /*isInline=*/true, 13544 /*isImplicitlyDeclared=*/true, 13545 Constexpr ? ConstexprSpecKind::Constexpr 13546 : ConstexprSpecKind::Unspecified); 13547 Destructor->setAccess(AS_public); 13548 Destructor->setDefaulted(); 13549 13550 if (getLangOpts().CUDA) { 13551 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 13552 Destructor, 13553 /* ConstRHS */ false, 13554 /* Diagnose */ false); 13555 } 13556 13557 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None); 13558 13559 // We don't need to use SpecialMemberIsTrivial here; triviality for 13560 // destructors is easy to compute. 13561 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 13562 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() || 13563 ClassDecl->hasTrivialDestructorForCall()); 13564 13565 // Note that we have declared this destructor. 13566 ++getASTContext().NumImplicitDestructorsDeclared; 13567 13568 Scope *S = getScopeForContext(ClassDecl); 13569 CheckImplicitSpecialMemberDeclaration(S, Destructor); 13570 13571 // We can't check whether an implicit destructor is deleted before we complete 13572 // the definition of the class, because its validity depends on the alignment 13573 // of the class. We'll check this from ActOnFields once the class is complete. 13574 if (ClassDecl->isCompleteDefinition() && 13575 ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 13576 SetDeclDeleted(Destructor, ClassLoc); 13577 13578 // Introduce this destructor into its scope. 13579 if (S) 13580 PushOnScopeChains(Destructor, S, false); 13581 ClassDecl->addDecl(Destructor); 13582 13583 return Destructor; 13584 } 13585 13586 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 13587 CXXDestructorDecl *Destructor) { 13588 assert((Destructor->isDefaulted() && 13589 !Destructor->doesThisDeclarationHaveABody() && 13590 !Destructor->isDeleted()) && 13591 "DefineImplicitDestructor - call it for implicit default dtor"); 13592 if (Destructor->willHaveBody() || Destructor->isInvalidDecl()) 13593 return; 13594 13595 CXXRecordDecl *ClassDecl = Destructor->getParent(); 13596 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 13597 13598 SynthesizedFunctionScope Scope(*this, Destructor); 13599 13600 // The exception specification is needed because we are defining the 13601 // function. 13602 ResolveExceptionSpec(CurrentLocation, 13603 Destructor->getType()->castAs<FunctionProtoType>()); 13604 MarkVTableUsed(CurrentLocation, ClassDecl); 13605 13606 // Add a context note for diagnostics produced after this point. 13607 Scope.addContextNote(CurrentLocation); 13608 13609 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 13610 Destructor->getParent()); 13611 13612 if (CheckDestructor(Destructor)) { 13613 Destructor->setInvalidDecl(); 13614 return; 13615 } 13616 13617 SourceLocation Loc = Destructor->getEndLoc().isValid() 13618 ? Destructor->getEndLoc() 13619 : Destructor->getLocation(); 13620 Destructor->setBody(new (Context) CompoundStmt(Loc)); 13621 Destructor->markUsed(Context); 13622 13623 if (ASTMutationListener *L = getASTMutationListener()) { 13624 L->CompletedImplicitDefinition(Destructor); 13625 } 13626 } 13627 13628 void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation, 13629 CXXDestructorDecl *Destructor) { 13630 if (Destructor->isInvalidDecl()) 13631 return; 13632 13633 CXXRecordDecl *ClassDecl = Destructor->getParent(); 13634 assert(Context.getTargetInfo().getCXXABI().isMicrosoft() && 13635 "implicit complete dtors unneeded outside MS ABI"); 13636 assert(ClassDecl->getNumVBases() > 0 && 13637 "complete dtor only exists for classes with vbases"); 13638 13639 SynthesizedFunctionScope Scope(*this, Destructor); 13640 13641 // Add a context note for diagnostics produced after this point. 13642 Scope.addContextNote(CurrentLocation); 13643 13644 MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl); 13645 } 13646 13647 /// Perform any semantic analysis which needs to be delayed until all 13648 /// pending class member declarations have been parsed. 13649 void Sema::ActOnFinishCXXMemberDecls() { 13650 // If the context is an invalid C++ class, just suppress these checks. 13651 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 13652 if (Record->isInvalidDecl()) { 13653 DelayedOverridingExceptionSpecChecks.clear(); 13654 DelayedEquivalentExceptionSpecChecks.clear(); 13655 return; 13656 } 13657 checkForMultipleExportedDefaultConstructors(*this, Record); 13658 } 13659 } 13660 13661 void Sema::ActOnFinishCXXNonNestedClass() { 13662 referenceDLLExportedClassMethods(); 13663 13664 if (!DelayedDllExportMemberFunctions.empty()) { 13665 SmallVector<CXXMethodDecl*, 4> WorkList; 13666 std::swap(DelayedDllExportMemberFunctions, WorkList); 13667 for (CXXMethodDecl *M : WorkList) { 13668 DefineDefaultedFunction(*this, M, M->getLocation()); 13669 13670 // Pass the method to the consumer to get emitted. This is not necessary 13671 // for explicit instantiation definitions, as they will get emitted 13672 // anyway. 13673 if (M->getParent()->getTemplateSpecializationKind() != 13674 TSK_ExplicitInstantiationDefinition) 13675 ActOnFinishInlineFunctionDef(M); 13676 } 13677 } 13678 } 13679 13680 void Sema::referenceDLLExportedClassMethods() { 13681 if (!DelayedDllExportClasses.empty()) { 13682 // Calling ReferenceDllExportedMembers might cause the current function to 13683 // be called again, so use a local copy of DelayedDllExportClasses. 13684 SmallVector<CXXRecordDecl *, 4> WorkList; 13685 std::swap(DelayedDllExportClasses, WorkList); 13686 for (CXXRecordDecl *Class : WorkList) 13687 ReferenceDllExportedMembers(*this, Class); 13688 } 13689 } 13690 13691 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) { 13692 assert(getLangOpts().CPlusPlus11 && 13693 "adjusting dtor exception specs was introduced in c++11"); 13694 13695 if (Destructor->isDependentContext()) 13696 return; 13697 13698 // C++11 [class.dtor]p3: 13699 // A declaration of a destructor that does not have an exception- 13700 // specification is implicitly considered to have the same exception- 13701 // specification as an implicit declaration. 13702 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>(); 13703 if (DtorType->hasExceptionSpec()) 13704 return; 13705 13706 // Replace the destructor's type, building off the existing one. Fortunately, 13707 // the only thing of interest in the destructor type is its extended info. 13708 // The return and arguments are fixed. 13709 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 13710 EPI.ExceptionSpec.Type = EST_Unevaluated; 13711 EPI.ExceptionSpec.SourceDecl = Destructor; 13712 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 13713 13714 // FIXME: If the destructor has a body that could throw, and the newly created 13715 // spec doesn't allow exceptions, we should emit a warning, because this 13716 // change in behavior can break conforming C++03 programs at runtime. 13717 // However, we don't have a body or an exception specification yet, so it 13718 // needs to be done somewhere else. 13719 } 13720 13721 namespace { 13722 /// An abstract base class for all helper classes used in building the 13723 // copy/move operators. These classes serve as factory functions and help us 13724 // avoid using the same Expr* in the AST twice. 13725 class ExprBuilder { 13726 ExprBuilder(const ExprBuilder&) = delete; 13727 ExprBuilder &operator=(const ExprBuilder&) = delete; 13728 13729 protected: 13730 static Expr *assertNotNull(Expr *E) { 13731 assert(E && "Expression construction must not fail."); 13732 return E; 13733 } 13734 13735 public: 13736 ExprBuilder() {} 13737 virtual ~ExprBuilder() {} 13738 13739 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 13740 }; 13741 13742 class RefBuilder: public ExprBuilder { 13743 VarDecl *Var; 13744 QualType VarType; 13745 13746 public: 13747 Expr *build(Sema &S, SourceLocation Loc) const override { 13748 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc)); 13749 } 13750 13751 RefBuilder(VarDecl *Var, QualType VarType) 13752 : Var(Var), VarType(VarType) {} 13753 }; 13754 13755 class ThisBuilder: public ExprBuilder { 13756 public: 13757 Expr *build(Sema &S, SourceLocation Loc) const override { 13758 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 13759 } 13760 }; 13761 13762 class CastBuilder: public ExprBuilder { 13763 const ExprBuilder &Builder; 13764 QualType Type; 13765 ExprValueKind Kind; 13766 const CXXCastPath &Path; 13767 13768 public: 13769 Expr *build(Sema &S, SourceLocation Loc) const override { 13770 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 13771 CK_UncheckedDerivedToBase, Kind, 13772 &Path).get()); 13773 } 13774 13775 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 13776 const CXXCastPath &Path) 13777 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 13778 }; 13779 13780 class DerefBuilder: public ExprBuilder { 13781 const ExprBuilder &Builder; 13782 13783 public: 13784 Expr *build(Sema &S, SourceLocation Loc) const override { 13785 return assertNotNull( 13786 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 13787 } 13788 13789 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13790 }; 13791 13792 class MemberBuilder: public ExprBuilder { 13793 const ExprBuilder &Builder; 13794 QualType Type; 13795 CXXScopeSpec SS; 13796 bool IsArrow; 13797 LookupResult &MemberLookup; 13798 13799 public: 13800 Expr *build(Sema &S, SourceLocation Loc) const override { 13801 return assertNotNull(S.BuildMemberReferenceExpr( 13802 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 13803 nullptr, MemberLookup, nullptr, nullptr).get()); 13804 } 13805 13806 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 13807 LookupResult &MemberLookup) 13808 : Builder(Builder), Type(Type), IsArrow(IsArrow), 13809 MemberLookup(MemberLookup) {} 13810 }; 13811 13812 class MoveCastBuilder: public ExprBuilder { 13813 const ExprBuilder &Builder; 13814 13815 public: 13816 Expr *build(Sema &S, SourceLocation Loc) const override { 13817 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 13818 } 13819 13820 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13821 }; 13822 13823 class LvalueConvBuilder: public ExprBuilder { 13824 const ExprBuilder &Builder; 13825 13826 public: 13827 Expr *build(Sema &S, SourceLocation Loc) const override { 13828 return assertNotNull( 13829 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 13830 } 13831 13832 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13833 }; 13834 13835 class SubscriptBuilder: public ExprBuilder { 13836 const ExprBuilder &Base; 13837 const ExprBuilder &Index; 13838 13839 public: 13840 Expr *build(Sema &S, SourceLocation Loc) const override { 13841 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 13842 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 13843 } 13844 13845 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 13846 : Base(Base), Index(Index) {} 13847 }; 13848 13849 } // end anonymous namespace 13850 13851 /// When generating a defaulted copy or move assignment operator, if a field 13852 /// should be copied with __builtin_memcpy rather than via explicit assignments, 13853 /// do so. This optimization only applies for arrays of scalars, and for arrays 13854 /// of class type where the selected copy/move-assignment operator is trivial. 13855 static StmtResult 13856 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 13857 const ExprBuilder &ToB, const ExprBuilder &FromB) { 13858 // Compute the size of the memory buffer to be copied. 13859 QualType SizeType = S.Context.getSizeType(); 13860 llvm::APInt Size(S.Context.getTypeSize(SizeType), 13861 S.Context.getTypeSizeInChars(T).getQuantity()); 13862 13863 // Take the address of the field references for "from" and "to". We 13864 // directly construct UnaryOperators here because semantic analysis 13865 // does not permit us to take the address of an xvalue. 13866 Expr *From = FromB.build(S, Loc); 13867 From = UnaryOperator::Create( 13868 S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()), 13869 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides()); 13870 Expr *To = ToB.build(S, Loc); 13871 To = UnaryOperator::Create( 13872 S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()), 13873 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides()); 13874 13875 const Type *E = T->getBaseElementTypeUnsafe(); 13876 bool NeedsCollectableMemCpy = 13877 E->isRecordType() && 13878 E->castAs<RecordType>()->getDecl()->hasObjectMember(); 13879 13880 // Create a reference to the __builtin_objc_memmove_collectable function 13881 StringRef MemCpyName = NeedsCollectableMemCpy ? 13882 "__builtin_objc_memmove_collectable" : 13883 "__builtin_memcpy"; 13884 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 13885 Sema::LookupOrdinaryName); 13886 S.LookupName(R, S.TUScope, true); 13887 13888 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 13889 if (!MemCpy) 13890 // Something went horribly wrong earlier, and we will have complained 13891 // about it. 13892 return StmtError(); 13893 13894 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 13895 VK_PRValue, Loc, nullptr); 13896 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 13897 13898 Expr *CallArgs[] = { 13899 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 13900 }; 13901 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 13902 Loc, CallArgs, Loc); 13903 13904 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 13905 return Call.getAs<Stmt>(); 13906 } 13907 13908 /// Builds a statement that copies/moves the given entity from \p From to 13909 /// \c To. 13910 /// 13911 /// This routine is used to copy/move the members of a class with an 13912 /// implicitly-declared copy/move assignment operator. When the entities being 13913 /// copied are arrays, this routine builds for loops to copy them. 13914 /// 13915 /// \param S The Sema object used for type-checking. 13916 /// 13917 /// \param Loc The location where the implicit copy/move is being generated. 13918 /// 13919 /// \param T The type of the expressions being copied/moved. Both expressions 13920 /// must have this type. 13921 /// 13922 /// \param To The expression we are copying/moving to. 13923 /// 13924 /// \param From The expression we are copying/moving from. 13925 /// 13926 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 13927 /// Otherwise, it's a non-static member subobject. 13928 /// 13929 /// \param Copying Whether we're copying or moving. 13930 /// 13931 /// \param Depth Internal parameter recording the depth of the recursion. 13932 /// 13933 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 13934 /// if a memcpy should be used instead. 13935 static StmtResult 13936 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 13937 const ExprBuilder &To, const ExprBuilder &From, 13938 bool CopyingBaseSubobject, bool Copying, 13939 unsigned Depth = 0) { 13940 // C++11 [class.copy]p28: 13941 // Each subobject is assigned in the manner appropriate to its type: 13942 // 13943 // - if the subobject is of class type, as if by a call to operator= with 13944 // the subobject as the object expression and the corresponding 13945 // subobject of x as a single function argument (as if by explicit 13946 // qualification; that is, ignoring any possible virtual overriding 13947 // functions in more derived classes); 13948 // 13949 // C++03 [class.copy]p13: 13950 // - if the subobject is of class type, the copy assignment operator for 13951 // the class is used (as if by explicit qualification; that is, 13952 // ignoring any possible virtual overriding functions in more derived 13953 // classes); 13954 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 13955 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 13956 13957 // Look for operator=. 13958 DeclarationName Name 13959 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 13960 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 13961 S.LookupQualifiedName(OpLookup, ClassDecl, false); 13962 13963 // Prior to C++11, filter out any result that isn't a copy/move-assignment 13964 // operator. 13965 if (!S.getLangOpts().CPlusPlus11) { 13966 LookupResult::Filter F = OpLookup.makeFilter(); 13967 while (F.hasNext()) { 13968 NamedDecl *D = F.next(); 13969 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 13970 if (Method->isCopyAssignmentOperator() || 13971 (!Copying && Method->isMoveAssignmentOperator())) 13972 continue; 13973 13974 F.erase(); 13975 } 13976 F.done(); 13977 } 13978 13979 // Suppress the protected check (C++ [class.protected]) for each of the 13980 // assignment operators we found. This strange dance is required when 13981 // we're assigning via a base classes's copy-assignment operator. To 13982 // ensure that we're getting the right base class subobject (without 13983 // ambiguities), we need to cast "this" to that subobject type; to 13984 // ensure that we don't go through the virtual call mechanism, we need 13985 // to qualify the operator= name with the base class (see below). However, 13986 // this means that if the base class has a protected copy assignment 13987 // operator, the protected member access check will fail. So, we 13988 // rewrite "protected" access to "public" access in this case, since we 13989 // know by construction that we're calling from a derived class. 13990 if (CopyingBaseSubobject) { 13991 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 13992 L != LEnd; ++L) { 13993 if (L.getAccess() == AS_protected) 13994 L.setAccess(AS_public); 13995 } 13996 } 13997 13998 // Create the nested-name-specifier that will be used to qualify the 13999 // reference to operator=; this is required to suppress the virtual 14000 // call mechanism. 14001 CXXScopeSpec SS; 14002 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 14003 SS.MakeTrivial(S.Context, 14004 NestedNameSpecifier::Create(S.Context, nullptr, false, 14005 CanonicalT), 14006 Loc); 14007 14008 // Create the reference to operator=. 14009 ExprResult OpEqualRef 14010 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false, 14011 SS, /*TemplateKWLoc=*/SourceLocation(), 14012 /*FirstQualifierInScope=*/nullptr, 14013 OpLookup, 14014 /*TemplateArgs=*/nullptr, /*S*/nullptr, 14015 /*SuppressQualifierCheck=*/true); 14016 if (OpEqualRef.isInvalid()) 14017 return StmtError(); 14018 14019 // Build the call to the assignment operator. 14020 14021 Expr *FromInst = From.build(S, Loc); 14022 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 14023 OpEqualRef.getAs<Expr>(), 14024 Loc, FromInst, Loc); 14025 if (Call.isInvalid()) 14026 return StmtError(); 14027 14028 // If we built a call to a trivial 'operator=' while copying an array, 14029 // bail out. We'll replace the whole shebang with a memcpy. 14030 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 14031 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 14032 return StmtResult((Stmt*)nullptr); 14033 14034 // Convert to an expression-statement, and clean up any produced 14035 // temporaries. 14036 return S.ActOnExprStmt(Call); 14037 } 14038 14039 // - if the subobject is of scalar type, the built-in assignment 14040 // operator is used. 14041 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 14042 if (!ArrayTy) { 14043 ExprResult Assignment = S.CreateBuiltinBinOp( 14044 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 14045 if (Assignment.isInvalid()) 14046 return StmtError(); 14047 return S.ActOnExprStmt(Assignment); 14048 } 14049 14050 // - if the subobject is an array, each element is assigned, in the 14051 // manner appropriate to the element type; 14052 14053 // Construct a loop over the array bounds, e.g., 14054 // 14055 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 14056 // 14057 // that will copy each of the array elements. 14058 QualType SizeType = S.Context.getSizeType(); 14059 14060 // Create the iteration variable. 14061 IdentifierInfo *IterationVarName = nullptr; 14062 { 14063 SmallString<8> Str; 14064 llvm::raw_svector_ostream OS(Str); 14065 OS << "__i" << Depth; 14066 IterationVarName = &S.Context.Idents.get(OS.str()); 14067 } 14068 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 14069 IterationVarName, SizeType, 14070 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 14071 SC_None); 14072 14073 // Initialize the iteration variable to zero. 14074 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 14075 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 14076 14077 // Creates a reference to the iteration variable. 14078 RefBuilder IterationVarRef(IterationVar, SizeType); 14079 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 14080 14081 // Create the DeclStmt that holds the iteration variable. 14082 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 14083 14084 // Subscript the "from" and "to" expressions with the iteration variable. 14085 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 14086 MoveCastBuilder FromIndexMove(FromIndexCopy); 14087 const ExprBuilder *FromIndex; 14088 if (Copying) 14089 FromIndex = &FromIndexCopy; 14090 else 14091 FromIndex = &FromIndexMove; 14092 14093 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 14094 14095 // Build the copy/move for an individual element of the array. 14096 StmtResult Copy = 14097 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 14098 ToIndex, *FromIndex, CopyingBaseSubobject, 14099 Copying, Depth + 1); 14100 // Bail out if copying fails or if we determined that we should use memcpy. 14101 if (Copy.isInvalid() || !Copy.get()) 14102 return Copy; 14103 14104 // Create the comparison against the array bound. 14105 llvm::APInt Upper 14106 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 14107 Expr *Comparison = BinaryOperator::Create( 14108 S.Context, IterationVarRefRVal.build(S, Loc), 14109 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE, 14110 S.Context.BoolTy, VK_PRValue, OK_Ordinary, Loc, 14111 S.CurFPFeatureOverrides()); 14112 14113 // Create the pre-increment of the iteration variable. We can determine 14114 // whether the increment will overflow based on the value of the array 14115 // bound. 14116 Expr *Increment = UnaryOperator::Create( 14117 S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue, 14118 OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides()); 14119 14120 // Construct the loop that copies all elements of this array. 14121 return S.ActOnForStmt( 14122 Loc, Loc, InitStmt, 14123 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean), 14124 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get()); 14125 } 14126 14127 static StmtResult 14128 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 14129 const ExprBuilder &To, const ExprBuilder &From, 14130 bool CopyingBaseSubobject, bool Copying) { 14131 // Maybe we should use a memcpy? 14132 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 14133 T.isTriviallyCopyableType(S.Context)) 14134 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 14135 14136 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 14137 CopyingBaseSubobject, 14138 Copying, 0)); 14139 14140 // If we ended up picking a trivial assignment operator for an array of a 14141 // non-trivially-copyable class type, just emit a memcpy. 14142 if (!Result.isInvalid() && !Result.get()) 14143 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 14144 14145 return Result; 14146 } 14147 14148 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 14149 // Note: The following rules are largely analoguous to the copy 14150 // constructor rules. Note that virtual bases are not taken into account 14151 // for determining the argument type of the operator. Note also that 14152 // operators taking an object instead of a reference are allowed. 14153 assert(ClassDecl->needsImplicitCopyAssignment()); 14154 14155 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 14156 if (DSM.isAlreadyBeingDeclared()) 14157 return nullptr; 14158 14159 QualType ArgType = Context.getTypeDeclType(ClassDecl); 14160 LangAS AS = getDefaultCXXMethodAddrSpace(); 14161 if (AS != LangAS::Default) 14162 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 14163 QualType RetType = Context.getLValueReferenceType(ArgType); 14164 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 14165 if (Const) 14166 ArgType = ArgType.withConst(); 14167 14168 ArgType = Context.getLValueReferenceType(ArgType); 14169 14170 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14171 CXXCopyAssignment, 14172 Const); 14173 14174 // An implicitly-declared copy assignment operator is an inline public 14175 // member of its class. 14176 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 14177 SourceLocation ClassLoc = ClassDecl->getLocation(); 14178 DeclarationNameInfo NameInfo(Name, ClassLoc); 14179 CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create( 14180 Context, ClassDecl, ClassLoc, NameInfo, QualType(), 14181 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 14182 getCurFPFeatures().isFPConstrained(), 14183 /*isInline=*/true, 14184 Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified, 14185 SourceLocation()); 14186 CopyAssignment->setAccess(AS_public); 14187 CopyAssignment->setDefaulted(); 14188 CopyAssignment->setImplicit(); 14189 14190 if (getLangOpts().CUDA) { 14191 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 14192 CopyAssignment, 14193 /* ConstRHS */ Const, 14194 /* Diagnose */ false); 14195 } 14196 14197 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType); 14198 14199 // Add the parameter to the operator. 14200 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 14201 ClassLoc, ClassLoc, 14202 /*Id=*/nullptr, ArgType, 14203 /*TInfo=*/nullptr, SC_None, 14204 nullptr); 14205 CopyAssignment->setParams(FromParam); 14206 14207 CopyAssignment->setTrivial( 14208 ClassDecl->needsOverloadResolutionForCopyAssignment() 14209 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 14210 : ClassDecl->hasTrivialCopyAssignment()); 14211 14212 // Note that we have added this copy-assignment operator. 14213 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared; 14214 14215 Scope *S = getScopeForContext(ClassDecl); 14216 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment); 14217 14218 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) { 14219 ClassDecl->setImplicitCopyAssignmentIsDeleted(); 14220 SetDeclDeleted(CopyAssignment, ClassLoc); 14221 } 14222 14223 if (S) 14224 PushOnScopeChains(CopyAssignment, S, false); 14225 ClassDecl->addDecl(CopyAssignment); 14226 14227 return CopyAssignment; 14228 } 14229 14230 /// Diagnose an implicit copy operation for a class which is odr-used, but 14231 /// which is deprecated because the class has a user-declared copy constructor, 14232 /// copy assignment operator, or destructor. 14233 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) { 14234 assert(CopyOp->isImplicit()); 14235 14236 CXXRecordDecl *RD = CopyOp->getParent(); 14237 CXXMethodDecl *UserDeclaredOperation = nullptr; 14238 14239 // In Microsoft mode, assignment operations don't affect constructors and 14240 // vice versa. 14241 if (RD->hasUserDeclaredDestructor()) { 14242 UserDeclaredOperation = RD->getDestructor(); 14243 } else if (!isa<CXXConstructorDecl>(CopyOp) && 14244 RD->hasUserDeclaredCopyConstructor() && 14245 !S.getLangOpts().MSVCCompat) { 14246 // Find any user-declared copy constructor. 14247 for (auto *I : RD->ctors()) { 14248 if (I->isCopyConstructor()) { 14249 UserDeclaredOperation = I; 14250 break; 14251 } 14252 } 14253 assert(UserDeclaredOperation); 14254 } else if (isa<CXXConstructorDecl>(CopyOp) && 14255 RD->hasUserDeclaredCopyAssignment() && 14256 !S.getLangOpts().MSVCCompat) { 14257 // Find any user-declared move assignment operator. 14258 for (auto *I : RD->methods()) { 14259 if (I->isCopyAssignmentOperator()) { 14260 UserDeclaredOperation = I; 14261 break; 14262 } 14263 } 14264 assert(UserDeclaredOperation); 14265 } 14266 14267 if (UserDeclaredOperation) { 14268 bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided(); 14269 bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation); 14270 bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp); 14271 unsigned DiagID = 14272 (UDOIsUserProvided && UDOIsDestructor) 14273 ? diag::warn_deprecated_copy_with_user_provided_dtor 14274 : (UDOIsUserProvided && !UDOIsDestructor) 14275 ? diag::warn_deprecated_copy_with_user_provided_copy 14276 : (!UDOIsUserProvided && UDOIsDestructor) 14277 ? diag::warn_deprecated_copy_with_dtor 14278 : diag::warn_deprecated_copy; 14279 S.Diag(UserDeclaredOperation->getLocation(), DiagID) 14280 << RD << IsCopyAssignment; 14281 } 14282 } 14283 14284 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 14285 CXXMethodDecl *CopyAssignOperator) { 14286 assert((CopyAssignOperator->isDefaulted() && 14287 CopyAssignOperator->isOverloadedOperator() && 14288 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 14289 !CopyAssignOperator->doesThisDeclarationHaveABody() && 14290 !CopyAssignOperator->isDeleted()) && 14291 "DefineImplicitCopyAssignment called for wrong function"); 14292 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl()) 14293 return; 14294 14295 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 14296 if (ClassDecl->isInvalidDecl()) { 14297 CopyAssignOperator->setInvalidDecl(); 14298 return; 14299 } 14300 14301 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 14302 14303 // The exception specification is needed because we are defining the 14304 // function. 14305 ResolveExceptionSpec(CurrentLocation, 14306 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 14307 14308 // Add a context note for diagnostics produced after this point. 14309 Scope.addContextNote(CurrentLocation); 14310 14311 // C++11 [class.copy]p18: 14312 // The [definition of an implicitly declared copy assignment operator] is 14313 // deprecated if the class has a user-declared copy constructor or a 14314 // user-declared destructor. 14315 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 14316 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator); 14317 14318 // C++0x [class.copy]p30: 14319 // The implicitly-defined or explicitly-defaulted copy assignment operator 14320 // for a non-union class X performs memberwise copy assignment of its 14321 // subobjects. The direct base classes of X are assigned first, in the 14322 // order of their declaration in the base-specifier-list, and then the 14323 // immediate non-static data members of X are assigned, in the order in 14324 // which they were declared in the class definition. 14325 14326 // The statements that form the synthesized function body. 14327 SmallVector<Stmt*, 8> Statements; 14328 14329 // The parameter for the "other" object, which we are copying from. 14330 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 14331 Qualifiers OtherQuals = Other->getType().getQualifiers(); 14332 QualType OtherRefType = Other->getType(); 14333 if (const LValueReferenceType *OtherRef 14334 = OtherRefType->getAs<LValueReferenceType>()) { 14335 OtherRefType = OtherRef->getPointeeType(); 14336 OtherQuals = OtherRefType.getQualifiers(); 14337 } 14338 14339 // Our location for everything implicitly-generated. 14340 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid() 14341 ? CopyAssignOperator->getEndLoc() 14342 : CopyAssignOperator->getLocation(); 14343 14344 // Builds a DeclRefExpr for the "other" object. 14345 RefBuilder OtherRef(Other, OtherRefType); 14346 14347 // Builds the "this" pointer. 14348 ThisBuilder This; 14349 14350 // Assign base classes. 14351 bool Invalid = false; 14352 for (auto &Base : ClassDecl->bases()) { 14353 // Form the assignment: 14354 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 14355 QualType BaseType = Base.getType().getUnqualifiedType(); 14356 if (!BaseType->isRecordType()) { 14357 Invalid = true; 14358 continue; 14359 } 14360 14361 CXXCastPath BasePath; 14362 BasePath.push_back(&Base); 14363 14364 // Construct the "from" expression, which is an implicit cast to the 14365 // appropriately-qualified base type. 14366 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 14367 VK_LValue, BasePath); 14368 14369 // Dereference "this". 14370 DerefBuilder DerefThis(This); 14371 CastBuilder To(DerefThis, 14372 Context.getQualifiedType( 14373 BaseType, CopyAssignOperator->getMethodQualifiers()), 14374 VK_LValue, BasePath); 14375 14376 // Build the copy. 14377 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 14378 To, From, 14379 /*CopyingBaseSubobject=*/true, 14380 /*Copying=*/true); 14381 if (Copy.isInvalid()) { 14382 CopyAssignOperator->setInvalidDecl(); 14383 return; 14384 } 14385 14386 // Success! Record the copy. 14387 Statements.push_back(Copy.getAs<Expr>()); 14388 } 14389 14390 // Assign non-static members. 14391 for (auto *Field : ClassDecl->fields()) { 14392 // FIXME: We should form some kind of AST representation for the implied 14393 // memcpy in a union copy operation. 14394 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 14395 continue; 14396 14397 if (Field->isInvalidDecl()) { 14398 Invalid = true; 14399 continue; 14400 } 14401 14402 // Check for members of reference type; we can't copy those. 14403 if (Field->getType()->isReferenceType()) { 14404 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14405 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 14406 Diag(Field->getLocation(), diag::note_declared_at); 14407 Invalid = true; 14408 continue; 14409 } 14410 14411 // Check for members of const-qualified, non-class type. 14412 QualType BaseType = Context.getBaseElementType(Field->getType()); 14413 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 14414 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14415 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 14416 Diag(Field->getLocation(), diag::note_declared_at); 14417 Invalid = true; 14418 continue; 14419 } 14420 14421 // Suppress assigning zero-width bitfields. 14422 if (Field->isZeroLengthBitField(Context)) 14423 continue; 14424 14425 QualType FieldType = Field->getType().getNonReferenceType(); 14426 if (FieldType->isIncompleteArrayType()) { 14427 assert(ClassDecl->hasFlexibleArrayMember() && 14428 "Incomplete array type is not valid"); 14429 continue; 14430 } 14431 14432 // Build references to the field in the object we're copying from and to. 14433 CXXScopeSpec SS; // Intentionally empty 14434 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 14435 LookupMemberName); 14436 MemberLookup.addDecl(Field); 14437 MemberLookup.resolveKind(); 14438 14439 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 14440 14441 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 14442 14443 // Build the copy of this field. 14444 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 14445 To, From, 14446 /*CopyingBaseSubobject=*/false, 14447 /*Copying=*/true); 14448 if (Copy.isInvalid()) { 14449 CopyAssignOperator->setInvalidDecl(); 14450 return; 14451 } 14452 14453 // Success! Record the copy. 14454 Statements.push_back(Copy.getAs<Stmt>()); 14455 } 14456 14457 if (!Invalid) { 14458 // Add a "return *this;" 14459 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 14460 14461 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 14462 if (Return.isInvalid()) 14463 Invalid = true; 14464 else 14465 Statements.push_back(Return.getAs<Stmt>()); 14466 } 14467 14468 if (Invalid) { 14469 CopyAssignOperator->setInvalidDecl(); 14470 return; 14471 } 14472 14473 StmtResult Body; 14474 { 14475 CompoundScopeRAII CompoundScope(*this); 14476 Body = ActOnCompoundStmt(Loc, Loc, Statements, 14477 /*isStmtExpr=*/false); 14478 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 14479 } 14480 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 14481 CopyAssignOperator->markUsed(Context); 14482 14483 if (ASTMutationListener *L = getASTMutationListener()) { 14484 L->CompletedImplicitDefinition(CopyAssignOperator); 14485 } 14486 } 14487 14488 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 14489 assert(ClassDecl->needsImplicitMoveAssignment()); 14490 14491 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 14492 if (DSM.isAlreadyBeingDeclared()) 14493 return nullptr; 14494 14495 // Note: The following rules are largely analoguous to the move 14496 // constructor rules. 14497 14498 QualType ArgType = Context.getTypeDeclType(ClassDecl); 14499 LangAS AS = getDefaultCXXMethodAddrSpace(); 14500 if (AS != LangAS::Default) 14501 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 14502 QualType RetType = Context.getLValueReferenceType(ArgType); 14503 ArgType = Context.getRValueReferenceType(ArgType); 14504 14505 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14506 CXXMoveAssignment, 14507 false); 14508 14509 // An implicitly-declared move assignment operator is an inline public 14510 // member of its class. 14511 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 14512 SourceLocation ClassLoc = ClassDecl->getLocation(); 14513 DeclarationNameInfo NameInfo(Name, ClassLoc); 14514 CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create( 14515 Context, ClassDecl, ClassLoc, NameInfo, QualType(), 14516 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 14517 getCurFPFeatures().isFPConstrained(), 14518 /*isInline=*/true, 14519 Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified, 14520 SourceLocation()); 14521 MoveAssignment->setAccess(AS_public); 14522 MoveAssignment->setDefaulted(); 14523 MoveAssignment->setImplicit(); 14524 14525 if (getLangOpts().CUDA) { 14526 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 14527 MoveAssignment, 14528 /* ConstRHS */ false, 14529 /* Diagnose */ false); 14530 } 14531 14532 setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType); 14533 14534 // Add the parameter to the operator. 14535 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 14536 ClassLoc, ClassLoc, 14537 /*Id=*/nullptr, ArgType, 14538 /*TInfo=*/nullptr, SC_None, 14539 nullptr); 14540 MoveAssignment->setParams(FromParam); 14541 14542 MoveAssignment->setTrivial( 14543 ClassDecl->needsOverloadResolutionForMoveAssignment() 14544 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 14545 : ClassDecl->hasTrivialMoveAssignment()); 14546 14547 // Note that we have added this copy-assignment operator. 14548 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared; 14549 14550 Scope *S = getScopeForContext(ClassDecl); 14551 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment); 14552 14553 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 14554 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 14555 SetDeclDeleted(MoveAssignment, ClassLoc); 14556 } 14557 14558 if (S) 14559 PushOnScopeChains(MoveAssignment, S, false); 14560 ClassDecl->addDecl(MoveAssignment); 14561 14562 return MoveAssignment; 14563 } 14564 14565 /// Check if we're implicitly defining a move assignment operator for a class 14566 /// with virtual bases. Such a move assignment might move-assign the virtual 14567 /// base multiple times. 14568 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 14569 SourceLocation CurrentLocation) { 14570 assert(!Class->isDependentContext() && "should not define dependent move"); 14571 14572 // Only a virtual base could get implicitly move-assigned multiple times. 14573 // Only a non-trivial move assignment can observe this. We only want to 14574 // diagnose if we implicitly define an assignment operator that assigns 14575 // two base classes, both of which move-assign the same virtual base. 14576 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 14577 Class->getNumBases() < 2) 14578 return; 14579 14580 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 14581 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 14582 VBaseMap VBases; 14583 14584 for (auto &BI : Class->bases()) { 14585 Worklist.push_back(&BI); 14586 while (!Worklist.empty()) { 14587 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 14588 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 14589 14590 // If the base has no non-trivial move assignment operators, 14591 // we don't care about moves from it. 14592 if (!Base->hasNonTrivialMoveAssignment()) 14593 continue; 14594 14595 // If there's nothing virtual here, skip it. 14596 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 14597 continue; 14598 14599 // If we're not actually going to call a move assignment for this base, 14600 // or the selected move assignment is trivial, skip it. 14601 Sema::SpecialMemberOverloadResult SMOR = 14602 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 14603 /*ConstArg*/false, /*VolatileArg*/false, 14604 /*RValueThis*/true, /*ConstThis*/false, 14605 /*VolatileThis*/false); 14606 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() || 14607 !SMOR.getMethod()->isMoveAssignmentOperator()) 14608 continue; 14609 14610 if (BaseSpec->isVirtual()) { 14611 // We're going to move-assign this virtual base, and its move 14612 // assignment operator is not trivial. If this can happen for 14613 // multiple distinct direct bases of Class, diagnose it. (If it 14614 // only happens in one base, we'll diagnose it when synthesizing 14615 // that base class's move assignment operator.) 14616 CXXBaseSpecifier *&Existing = 14617 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 14618 .first->second; 14619 if (Existing && Existing != &BI) { 14620 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 14621 << Class << Base; 14622 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here) 14623 << (Base->getCanonicalDecl() == 14624 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 14625 << Base << Existing->getType() << Existing->getSourceRange(); 14626 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here) 14627 << (Base->getCanonicalDecl() == 14628 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 14629 << Base << BI.getType() << BaseSpec->getSourceRange(); 14630 14631 // Only diagnose each vbase once. 14632 Existing = nullptr; 14633 } 14634 } else { 14635 // Only walk over bases that have defaulted move assignment operators. 14636 // We assume that any user-provided move assignment operator handles 14637 // the multiple-moves-of-vbase case itself somehow. 14638 if (!SMOR.getMethod()->isDefaulted()) 14639 continue; 14640 14641 // We're going to move the base classes of Base. Add them to the list. 14642 for (auto &BI : Base->bases()) 14643 Worklist.push_back(&BI); 14644 } 14645 } 14646 } 14647 } 14648 14649 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 14650 CXXMethodDecl *MoveAssignOperator) { 14651 assert((MoveAssignOperator->isDefaulted() && 14652 MoveAssignOperator->isOverloadedOperator() && 14653 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 14654 !MoveAssignOperator->doesThisDeclarationHaveABody() && 14655 !MoveAssignOperator->isDeleted()) && 14656 "DefineImplicitMoveAssignment called for wrong function"); 14657 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl()) 14658 return; 14659 14660 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 14661 if (ClassDecl->isInvalidDecl()) { 14662 MoveAssignOperator->setInvalidDecl(); 14663 return; 14664 } 14665 14666 // C++0x [class.copy]p28: 14667 // The implicitly-defined or move assignment operator for a non-union class 14668 // X performs memberwise move assignment of its subobjects. The direct base 14669 // classes of X are assigned first, in the order of their declaration in the 14670 // base-specifier-list, and then the immediate non-static data members of X 14671 // are assigned, in the order in which they were declared in the class 14672 // definition. 14673 14674 // Issue a warning if our implicit move assignment operator will move 14675 // from a virtual base more than once. 14676 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 14677 14678 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 14679 14680 // The exception specification is needed because we are defining the 14681 // function. 14682 ResolveExceptionSpec(CurrentLocation, 14683 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 14684 14685 // Add a context note for diagnostics produced after this point. 14686 Scope.addContextNote(CurrentLocation); 14687 14688 // The statements that form the synthesized function body. 14689 SmallVector<Stmt*, 8> Statements; 14690 14691 // The parameter for the "other" object, which we are move from. 14692 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 14693 QualType OtherRefType = 14694 Other->getType()->castAs<RValueReferenceType>()->getPointeeType(); 14695 14696 // Our location for everything implicitly-generated. 14697 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid() 14698 ? MoveAssignOperator->getEndLoc() 14699 : MoveAssignOperator->getLocation(); 14700 14701 // Builds a reference to the "other" object. 14702 RefBuilder OtherRef(Other, OtherRefType); 14703 // Cast to rvalue. 14704 MoveCastBuilder MoveOther(OtherRef); 14705 14706 // Builds the "this" pointer. 14707 ThisBuilder This; 14708 14709 // Assign base classes. 14710 bool Invalid = false; 14711 for (auto &Base : ClassDecl->bases()) { 14712 // C++11 [class.copy]p28: 14713 // It is unspecified whether subobjects representing virtual base classes 14714 // are assigned more than once by the implicitly-defined copy assignment 14715 // operator. 14716 // FIXME: Do not assign to a vbase that will be assigned by some other base 14717 // class. For a move-assignment, this can result in the vbase being moved 14718 // multiple times. 14719 14720 // Form the assignment: 14721 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 14722 QualType BaseType = Base.getType().getUnqualifiedType(); 14723 if (!BaseType->isRecordType()) { 14724 Invalid = true; 14725 continue; 14726 } 14727 14728 CXXCastPath BasePath; 14729 BasePath.push_back(&Base); 14730 14731 // Construct the "from" expression, which is an implicit cast to the 14732 // appropriately-qualified base type. 14733 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 14734 14735 // Dereference "this". 14736 DerefBuilder DerefThis(This); 14737 14738 // Implicitly cast "this" to the appropriately-qualified base type. 14739 CastBuilder To(DerefThis, 14740 Context.getQualifiedType( 14741 BaseType, MoveAssignOperator->getMethodQualifiers()), 14742 VK_LValue, BasePath); 14743 14744 // Build the move. 14745 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 14746 To, From, 14747 /*CopyingBaseSubobject=*/true, 14748 /*Copying=*/false); 14749 if (Move.isInvalid()) { 14750 MoveAssignOperator->setInvalidDecl(); 14751 return; 14752 } 14753 14754 // Success! Record the move. 14755 Statements.push_back(Move.getAs<Expr>()); 14756 } 14757 14758 // Assign non-static members. 14759 for (auto *Field : ClassDecl->fields()) { 14760 // FIXME: We should form some kind of AST representation for the implied 14761 // memcpy in a union copy operation. 14762 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 14763 continue; 14764 14765 if (Field->isInvalidDecl()) { 14766 Invalid = true; 14767 continue; 14768 } 14769 14770 // Check for members of reference type; we can't move those. 14771 if (Field->getType()->isReferenceType()) { 14772 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14773 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 14774 Diag(Field->getLocation(), diag::note_declared_at); 14775 Invalid = true; 14776 continue; 14777 } 14778 14779 // Check for members of const-qualified, non-class type. 14780 QualType BaseType = Context.getBaseElementType(Field->getType()); 14781 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 14782 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14783 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 14784 Diag(Field->getLocation(), diag::note_declared_at); 14785 Invalid = true; 14786 continue; 14787 } 14788 14789 // Suppress assigning zero-width bitfields. 14790 if (Field->isZeroLengthBitField(Context)) 14791 continue; 14792 14793 QualType FieldType = Field->getType().getNonReferenceType(); 14794 if (FieldType->isIncompleteArrayType()) { 14795 assert(ClassDecl->hasFlexibleArrayMember() && 14796 "Incomplete array type is not valid"); 14797 continue; 14798 } 14799 14800 // Build references to the field in the object we're copying from and to. 14801 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 14802 LookupMemberName); 14803 MemberLookup.addDecl(Field); 14804 MemberLookup.resolveKind(); 14805 MemberBuilder From(MoveOther, OtherRefType, 14806 /*IsArrow=*/false, MemberLookup); 14807 MemberBuilder To(This, getCurrentThisType(), 14808 /*IsArrow=*/true, MemberLookup); 14809 14810 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 14811 "Member reference with rvalue base must be rvalue except for reference " 14812 "members, which aren't allowed for move assignment."); 14813 14814 // Build the move of this field. 14815 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 14816 To, From, 14817 /*CopyingBaseSubobject=*/false, 14818 /*Copying=*/false); 14819 if (Move.isInvalid()) { 14820 MoveAssignOperator->setInvalidDecl(); 14821 return; 14822 } 14823 14824 // Success! Record the copy. 14825 Statements.push_back(Move.getAs<Stmt>()); 14826 } 14827 14828 if (!Invalid) { 14829 // Add a "return *this;" 14830 ExprResult ThisObj = 14831 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 14832 14833 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 14834 if (Return.isInvalid()) 14835 Invalid = true; 14836 else 14837 Statements.push_back(Return.getAs<Stmt>()); 14838 } 14839 14840 if (Invalid) { 14841 MoveAssignOperator->setInvalidDecl(); 14842 return; 14843 } 14844 14845 StmtResult Body; 14846 { 14847 CompoundScopeRAII CompoundScope(*this); 14848 Body = ActOnCompoundStmt(Loc, Loc, Statements, 14849 /*isStmtExpr=*/false); 14850 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 14851 } 14852 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 14853 MoveAssignOperator->markUsed(Context); 14854 14855 if (ASTMutationListener *L = getASTMutationListener()) { 14856 L->CompletedImplicitDefinition(MoveAssignOperator); 14857 } 14858 } 14859 14860 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 14861 CXXRecordDecl *ClassDecl) { 14862 // C++ [class.copy]p4: 14863 // If the class definition does not explicitly declare a copy 14864 // constructor, one is declared implicitly. 14865 assert(ClassDecl->needsImplicitCopyConstructor()); 14866 14867 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 14868 if (DSM.isAlreadyBeingDeclared()) 14869 return nullptr; 14870 14871 QualType ClassType = Context.getTypeDeclType(ClassDecl); 14872 QualType ArgType = ClassType; 14873 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 14874 if (Const) 14875 ArgType = ArgType.withConst(); 14876 14877 LangAS AS = getDefaultCXXMethodAddrSpace(); 14878 if (AS != LangAS::Default) 14879 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 14880 14881 ArgType = Context.getLValueReferenceType(ArgType); 14882 14883 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14884 CXXCopyConstructor, 14885 Const); 14886 14887 DeclarationName Name 14888 = Context.DeclarationNames.getCXXConstructorName( 14889 Context.getCanonicalType(ClassType)); 14890 SourceLocation ClassLoc = ClassDecl->getLocation(); 14891 DeclarationNameInfo NameInfo(Name, ClassLoc); 14892 14893 // An implicitly-declared copy constructor is an inline public 14894 // member of its class. 14895 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 14896 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 14897 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(), 14898 /*isInline=*/true, 14899 /*isImplicitlyDeclared=*/true, 14900 Constexpr ? ConstexprSpecKind::Constexpr 14901 : ConstexprSpecKind::Unspecified); 14902 CopyConstructor->setAccess(AS_public); 14903 CopyConstructor->setDefaulted(); 14904 14905 if (getLangOpts().CUDA) { 14906 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 14907 CopyConstructor, 14908 /* ConstRHS */ Const, 14909 /* Diagnose */ false); 14910 } 14911 14912 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType); 14913 14914 // During template instantiation of special member functions we need a 14915 // reliable TypeSourceInfo for the parameter types in order to allow functions 14916 // to be substituted. 14917 TypeSourceInfo *TSI = nullptr; 14918 if (inTemplateInstantiation() && ClassDecl->isLambda()) 14919 TSI = Context.getTrivialTypeSourceInfo(ArgType); 14920 14921 // Add the parameter to the constructor. 14922 ParmVarDecl *FromParam = 14923 ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc, 14924 /*IdentifierInfo=*/nullptr, ArgType, 14925 /*TInfo=*/TSI, SC_None, nullptr); 14926 CopyConstructor->setParams(FromParam); 14927 14928 CopyConstructor->setTrivial( 14929 ClassDecl->needsOverloadResolutionForCopyConstructor() 14930 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 14931 : ClassDecl->hasTrivialCopyConstructor()); 14932 14933 CopyConstructor->setTrivialForCall( 14934 ClassDecl->hasAttr<TrivialABIAttr>() || 14935 (ClassDecl->needsOverloadResolutionForCopyConstructor() 14936 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor, 14937 TAH_ConsiderTrivialABI) 14938 : ClassDecl->hasTrivialCopyConstructorForCall())); 14939 14940 // Note that we have declared this constructor. 14941 ++getASTContext().NumImplicitCopyConstructorsDeclared; 14942 14943 Scope *S = getScopeForContext(ClassDecl); 14944 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor); 14945 14946 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) { 14947 ClassDecl->setImplicitCopyConstructorIsDeleted(); 14948 SetDeclDeleted(CopyConstructor, ClassLoc); 14949 } 14950 14951 if (S) 14952 PushOnScopeChains(CopyConstructor, S, false); 14953 ClassDecl->addDecl(CopyConstructor); 14954 14955 return CopyConstructor; 14956 } 14957 14958 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 14959 CXXConstructorDecl *CopyConstructor) { 14960 assert((CopyConstructor->isDefaulted() && 14961 CopyConstructor->isCopyConstructor() && 14962 !CopyConstructor->doesThisDeclarationHaveABody() && 14963 !CopyConstructor->isDeleted()) && 14964 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 14965 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl()) 14966 return; 14967 14968 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 14969 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 14970 14971 SynthesizedFunctionScope Scope(*this, CopyConstructor); 14972 14973 // The exception specification is needed because we are defining the 14974 // function. 14975 ResolveExceptionSpec(CurrentLocation, 14976 CopyConstructor->getType()->castAs<FunctionProtoType>()); 14977 MarkVTableUsed(CurrentLocation, ClassDecl); 14978 14979 // Add a context note for diagnostics produced after this point. 14980 Scope.addContextNote(CurrentLocation); 14981 14982 // C++11 [class.copy]p7: 14983 // The [definition of an implicitly declared copy constructor] is 14984 // deprecated if the class has a user-declared copy assignment operator 14985 // or a user-declared destructor. 14986 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 14987 diagnoseDeprecatedCopyOperation(*this, CopyConstructor); 14988 14989 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) { 14990 CopyConstructor->setInvalidDecl(); 14991 } else { 14992 SourceLocation Loc = CopyConstructor->getEndLoc().isValid() 14993 ? CopyConstructor->getEndLoc() 14994 : CopyConstructor->getLocation(); 14995 Sema::CompoundScopeRAII CompoundScope(*this); 14996 CopyConstructor->setBody( 14997 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 14998 CopyConstructor->markUsed(Context); 14999 } 15000 15001 if (ASTMutationListener *L = getASTMutationListener()) { 15002 L->CompletedImplicitDefinition(CopyConstructor); 15003 } 15004 } 15005 15006 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 15007 CXXRecordDecl *ClassDecl) { 15008 assert(ClassDecl->needsImplicitMoveConstructor()); 15009 15010 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 15011 if (DSM.isAlreadyBeingDeclared()) 15012 return nullptr; 15013 15014 QualType ClassType = Context.getTypeDeclType(ClassDecl); 15015 15016 QualType ArgType = ClassType; 15017 LangAS AS = getDefaultCXXMethodAddrSpace(); 15018 if (AS != LangAS::Default) 15019 ArgType = Context.getAddrSpaceQualType(ClassType, AS); 15020 ArgType = Context.getRValueReferenceType(ArgType); 15021 15022 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 15023 CXXMoveConstructor, 15024 false); 15025 15026 DeclarationName Name 15027 = Context.DeclarationNames.getCXXConstructorName( 15028 Context.getCanonicalType(ClassType)); 15029 SourceLocation ClassLoc = ClassDecl->getLocation(); 15030 DeclarationNameInfo NameInfo(Name, ClassLoc); 15031 15032 // C++11 [class.copy]p11: 15033 // An implicitly-declared copy/move constructor is an inline public 15034 // member of its class. 15035 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 15036 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 15037 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(), 15038 /*isInline=*/true, 15039 /*isImplicitlyDeclared=*/true, 15040 Constexpr ? ConstexprSpecKind::Constexpr 15041 : ConstexprSpecKind::Unspecified); 15042 MoveConstructor->setAccess(AS_public); 15043 MoveConstructor->setDefaulted(); 15044 15045 if (getLangOpts().CUDA) { 15046 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 15047 MoveConstructor, 15048 /* ConstRHS */ false, 15049 /* Diagnose */ false); 15050 } 15051 15052 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType); 15053 15054 // Add the parameter to the constructor. 15055 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 15056 ClassLoc, ClassLoc, 15057 /*IdentifierInfo=*/nullptr, 15058 ArgType, /*TInfo=*/nullptr, 15059 SC_None, nullptr); 15060 MoveConstructor->setParams(FromParam); 15061 15062 MoveConstructor->setTrivial( 15063 ClassDecl->needsOverloadResolutionForMoveConstructor() 15064 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 15065 : ClassDecl->hasTrivialMoveConstructor()); 15066 15067 MoveConstructor->setTrivialForCall( 15068 ClassDecl->hasAttr<TrivialABIAttr>() || 15069 (ClassDecl->needsOverloadResolutionForMoveConstructor() 15070 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor, 15071 TAH_ConsiderTrivialABI) 15072 : ClassDecl->hasTrivialMoveConstructorForCall())); 15073 15074 // Note that we have declared this constructor. 15075 ++getASTContext().NumImplicitMoveConstructorsDeclared; 15076 15077 Scope *S = getScopeForContext(ClassDecl); 15078 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor); 15079 15080 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 15081 ClassDecl->setImplicitMoveConstructorIsDeleted(); 15082 SetDeclDeleted(MoveConstructor, ClassLoc); 15083 } 15084 15085 if (S) 15086 PushOnScopeChains(MoveConstructor, S, false); 15087 ClassDecl->addDecl(MoveConstructor); 15088 15089 return MoveConstructor; 15090 } 15091 15092 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 15093 CXXConstructorDecl *MoveConstructor) { 15094 assert((MoveConstructor->isDefaulted() && 15095 MoveConstructor->isMoveConstructor() && 15096 !MoveConstructor->doesThisDeclarationHaveABody() && 15097 !MoveConstructor->isDeleted()) && 15098 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 15099 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl()) 15100 return; 15101 15102 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 15103 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 15104 15105 SynthesizedFunctionScope Scope(*this, MoveConstructor); 15106 15107 // The exception specification is needed because we are defining the 15108 // function. 15109 ResolveExceptionSpec(CurrentLocation, 15110 MoveConstructor->getType()->castAs<FunctionProtoType>()); 15111 MarkVTableUsed(CurrentLocation, ClassDecl); 15112 15113 // Add a context note for diagnostics produced after this point. 15114 Scope.addContextNote(CurrentLocation); 15115 15116 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) { 15117 MoveConstructor->setInvalidDecl(); 15118 } else { 15119 SourceLocation Loc = MoveConstructor->getEndLoc().isValid() 15120 ? MoveConstructor->getEndLoc() 15121 : MoveConstructor->getLocation(); 15122 Sema::CompoundScopeRAII CompoundScope(*this); 15123 MoveConstructor->setBody(ActOnCompoundStmt( 15124 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 15125 MoveConstructor->markUsed(Context); 15126 } 15127 15128 if (ASTMutationListener *L = getASTMutationListener()) { 15129 L->CompletedImplicitDefinition(MoveConstructor); 15130 } 15131 } 15132 15133 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 15134 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 15135 } 15136 15137 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 15138 SourceLocation CurrentLocation, 15139 CXXConversionDecl *Conv) { 15140 SynthesizedFunctionScope Scope(*this, Conv); 15141 assert(!Conv->getReturnType()->isUndeducedType()); 15142 15143 QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType(); 15144 CallingConv CC = 15145 ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv(); 15146 15147 CXXRecordDecl *Lambda = Conv->getParent(); 15148 FunctionDecl *CallOp = Lambda->getLambdaCallOperator(); 15149 FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(CC); 15150 15151 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) { 15152 CallOp = InstantiateFunctionDeclaration( 15153 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 15154 if (!CallOp) 15155 return; 15156 15157 Invoker = InstantiateFunctionDeclaration( 15158 Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 15159 if (!Invoker) 15160 return; 15161 } 15162 15163 if (CallOp->isInvalidDecl()) 15164 return; 15165 15166 // Mark the call operator referenced (and add to pending instantiations 15167 // if necessary). 15168 // For both the conversion and static-invoker template specializations 15169 // we construct their body's in this function, so no need to add them 15170 // to the PendingInstantiations. 15171 MarkFunctionReferenced(CurrentLocation, CallOp); 15172 15173 // Fill in the __invoke function with a dummy implementation. IR generation 15174 // will fill in the actual details. Update its type in case it contained 15175 // an 'auto'. 15176 Invoker->markUsed(Context); 15177 Invoker->setReferenced(); 15178 Invoker->setType(Conv->getReturnType()->getPointeeType()); 15179 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 15180 15181 // Construct the body of the conversion function { return __invoke; }. 15182 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 15183 VK_LValue, Conv->getLocation()); 15184 assert(FunctionRef && "Can't refer to __invoke function?"); 15185 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 15186 Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(), 15187 Conv->getLocation())); 15188 Conv->markUsed(Context); 15189 Conv->setReferenced(); 15190 15191 if (ASTMutationListener *L = getASTMutationListener()) { 15192 L->CompletedImplicitDefinition(Conv); 15193 L->CompletedImplicitDefinition(Invoker); 15194 } 15195 } 15196 15197 15198 15199 void Sema::DefineImplicitLambdaToBlockPointerConversion( 15200 SourceLocation CurrentLocation, 15201 CXXConversionDecl *Conv) 15202 { 15203 assert(!Conv->getParent()->isGenericLambda()); 15204 15205 SynthesizedFunctionScope Scope(*this, Conv); 15206 15207 // Copy-initialize the lambda object as needed to capture it. 15208 Expr *This = ActOnCXXThis(CurrentLocation).get(); 15209 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 15210 15211 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 15212 Conv->getLocation(), 15213 Conv, DerefThis); 15214 15215 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 15216 // behavior. Note that only the general conversion function does this 15217 // (since it's unusable otherwise); in the case where we inline the 15218 // block literal, it has block literal lifetime semantics. 15219 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 15220 BuildBlock = ImplicitCastExpr::Create( 15221 Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject, 15222 BuildBlock.get(), nullptr, VK_PRValue, FPOptionsOverride()); 15223 15224 if (BuildBlock.isInvalid()) { 15225 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 15226 Conv->setInvalidDecl(); 15227 return; 15228 } 15229 15230 // Create the return statement that returns the block from the conversion 15231 // function. 15232 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 15233 if (Return.isInvalid()) { 15234 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 15235 Conv->setInvalidDecl(); 15236 return; 15237 } 15238 15239 // Set the body of the conversion function. 15240 Stmt *ReturnS = Return.get(); 15241 Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(), 15242 Conv->getLocation())); 15243 Conv->markUsed(Context); 15244 15245 // We're done; notify the mutation listener, if any. 15246 if (ASTMutationListener *L = getASTMutationListener()) { 15247 L->CompletedImplicitDefinition(Conv); 15248 } 15249 } 15250 15251 /// Determine whether the given list arguments contains exactly one 15252 /// "real" (non-default) argument. 15253 static bool hasOneRealArgument(MultiExprArg Args) { 15254 switch (Args.size()) { 15255 case 0: 15256 return false; 15257 15258 default: 15259 if (!Args[1]->isDefaultArgument()) 15260 return false; 15261 15262 LLVM_FALLTHROUGH; 15263 case 1: 15264 return !Args[0]->isDefaultArgument(); 15265 } 15266 15267 return false; 15268 } 15269 15270 ExprResult 15271 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 15272 NamedDecl *FoundDecl, 15273 CXXConstructorDecl *Constructor, 15274 MultiExprArg ExprArgs, 15275 bool HadMultipleCandidates, 15276 bool IsListInitialization, 15277 bool IsStdInitListInitialization, 15278 bool RequiresZeroInit, 15279 unsigned ConstructKind, 15280 SourceRange ParenRange) { 15281 bool Elidable = false; 15282 15283 // C++0x [class.copy]p34: 15284 // When certain criteria are met, an implementation is allowed to 15285 // omit the copy/move construction of a class object, even if the 15286 // copy/move constructor and/or destructor for the object have 15287 // side effects. [...] 15288 // - when a temporary class object that has not been bound to a 15289 // reference (12.2) would be copied/moved to a class object 15290 // with the same cv-unqualified type, the copy/move operation 15291 // can be omitted by constructing the temporary object 15292 // directly into the target of the omitted copy/move 15293 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor && 15294 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 15295 Expr *SubExpr = ExprArgs[0]; 15296 Elidable = SubExpr->isTemporaryObject( 15297 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 15298 } 15299 15300 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, 15301 FoundDecl, Constructor, 15302 Elidable, ExprArgs, HadMultipleCandidates, 15303 IsListInitialization, 15304 IsStdInitListInitialization, RequiresZeroInit, 15305 ConstructKind, ParenRange); 15306 } 15307 15308 ExprResult 15309 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 15310 NamedDecl *FoundDecl, 15311 CXXConstructorDecl *Constructor, 15312 bool Elidable, 15313 MultiExprArg ExprArgs, 15314 bool HadMultipleCandidates, 15315 bool IsListInitialization, 15316 bool IsStdInitListInitialization, 15317 bool RequiresZeroInit, 15318 unsigned ConstructKind, 15319 SourceRange ParenRange) { 15320 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) { 15321 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow); 15322 if (DiagnoseUseOfDecl(Constructor, ConstructLoc)) 15323 return ExprError(); 15324 } 15325 15326 return BuildCXXConstructExpr( 15327 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs, 15328 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 15329 RequiresZeroInit, ConstructKind, ParenRange); 15330 } 15331 15332 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 15333 /// including handling of its default argument expressions. 15334 ExprResult 15335 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 15336 CXXConstructorDecl *Constructor, 15337 bool Elidable, 15338 MultiExprArg ExprArgs, 15339 bool HadMultipleCandidates, 15340 bool IsListInitialization, 15341 bool IsStdInitListInitialization, 15342 bool RequiresZeroInit, 15343 unsigned ConstructKind, 15344 SourceRange ParenRange) { 15345 assert(declaresSameEntity( 15346 Constructor->getParent(), 15347 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && 15348 "given constructor for wrong type"); 15349 MarkFunctionReferenced(ConstructLoc, Constructor); 15350 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor)) 15351 return ExprError(); 15352 if (getLangOpts().SYCLIsDevice && 15353 !checkSYCLDeviceFunction(ConstructLoc, Constructor)) 15354 return ExprError(); 15355 15356 return CheckForImmediateInvocation( 15357 CXXConstructExpr::Create( 15358 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs, 15359 HadMultipleCandidates, IsListInitialization, 15360 IsStdInitListInitialization, RequiresZeroInit, 15361 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 15362 ParenRange), 15363 Constructor); 15364 } 15365 15366 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 15367 assert(Field->hasInClassInitializer()); 15368 15369 // If we already have the in-class initializer nothing needs to be done. 15370 if (Field->getInClassInitializer()) 15371 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext); 15372 15373 // If we might have already tried and failed to instantiate, don't try again. 15374 if (Field->isInvalidDecl()) 15375 return ExprError(); 15376 15377 // Maybe we haven't instantiated the in-class initializer. Go check the 15378 // pattern FieldDecl to see if it has one. 15379 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 15380 15381 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 15382 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 15383 DeclContext::lookup_result Lookup = 15384 ClassPattern->lookup(Field->getDeclName()); 15385 15386 FieldDecl *Pattern = nullptr; 15387 for (auto L : Lookup) { 15388 if (isa<FieldDecl>(L)) { 15389 Pattern = cast<FieldDecl>(L); 15390 break; 15391 } 15392 } 15393 assert(Pattern && "We must have set the Pattern!"); 15394 15395 if (!Pattern->hasInClassInitializer() || 15396 InstantiateInClassInitializer(Loc, Field, Pattern, 15397 getTemplateInstantiationArgs(Field))) { 15398 // Don't diagnose this again. 15399 Field->setInvalidDecl(); 15400 return ExprError(); 15401 } 15402 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext); 15403 } 15404 15405 // DR1351: 15406 // If the brace-or-equal-initializer of a non-static data member 15407 // invokes a defaulted default constructor of its class or of an 15408 // enclosing class in a potentially evaluated subexpression, the 15409 // program is ill-formed. 15410 // 15411 // This resolution is unworkable: the exception specification of the 15412 // default constructor can be needed in an unevaluated context, in 15413 // particular, in the operand of a noexcept-expression, and we can be 15414 // unable to compute an exception specification for an enclosed class. 15415 // 15416 // Any attempt to resolve the exception specification of a defaulted default 15417 // constructor before the initializer is lexically complete will ultimately 15418 // come here at which point we can diagnose it. 15419 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 15420 Diag(Loc, diag::err_default_member_initializer_not_yet_parsed) 15421 << OutermostClass << Field; 15422 Diag(Field->getEndLoc(), 15423 diag::note_default_member_initializer_not_yet_parsed); 15424 // Recover by marking the field invalid, unless we're in a SFINAE context. 15425 if (!isSFINAEContext()) 15426 Field->setInvalidDecl(); 15427 return ExprError(); 15428 } 15429 15430 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 15431 if (VD->isInvalidDecl()) return; 15432 // If initializing the variable failed, don't also diagnose problems with 15433 // the desctructor, they're likely related. 15434 if (VD->getInit() && VD->getInit()->containsErrors()) 15435 return; 15436 15437 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 15438 if (ClassDecl->isInvalidDecl()) return; 15439 if (ClassDecl->hasIrrelevantDestructor()) return; 15440 if (ClassDecl->isDependentContext()) return; 15441 15442 if (VD->isNoDestroy(getASTContext())) 15443 return; 15444 15445 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 15446 15447 // If this is an array, we'll require the destructor during initialization, so 15448 // we can skip over this. We still want to emit exit-time destructor warnings 15449 // though. 15450 if (!VD->getType()->isArrayType()) { 15451 MarkFunctionReferenced(VD->getLocation(), Destructor); 15452 CheckDestructorAccess(VD->getLocation(), Destructor, 15453 PDiag(diag::err_access_dtor_var) 15454 << VD->getDeclName() << VD->getType()); 15455 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 15456 } 15457 15458 if (Destructor->isTrivial()) return; 15459 15460 // If the destructor is constexpr, check whether the variable has constant 15461 // destruction now. 15462 if (Destructor->isConstexpr()) { 15463 bool HasConstantInit = false; 15464 if (VD->getInit() && !VD->getInit()->isValueDependent()) 15465 HasConstantInit = VD->evaluateValue(); 15466 SmallVector<PartialDiagnosticAt, 8> Notes; 15467 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() && 15468 HasConstantInit) { 15469 Diag(VD->getLocation(), 15470 diag::err_constexpr_var_requires_const_destruction) << VD; 15471 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 15472 Diag(Notes[I].first, Notes[I].second); 15473 } 15474 } 15475 15476 if (!VD->hasGlobalStorage()) return; 15477 15478 // Emit warning for non-trivial dtor in global scope (a real global, 15479 // class-static, function-static). 15480 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 15481 15482 // TODO: this should be re-enabled for static locals by !CXAAtExit 15483 if (!VD->isStaticLocal()) 15484 Diag(VD->getLocation(), diag::warn_global_destructor); 15485 } 15486 15487 /// Given a constructor and the set of arguments provided for the 15488 /// constructor, convert the arguments and add any required default arguments 15489 /// to form a proper call to this constructor. 15490 /// 15491 /// \returns true if an error occurred, false otherwise. 15492 bool Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 15493 QualType DeclInitType, MultiExprArg ArgsPtr, 15494 SourceLocation Loc, 15495 SmallVectorImpl<Expr *> &ConvertedArgs, 15496 bool AllowExplicit, 15497 bool IsListInitialization) { 15498 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 15499 unsigned NumArgs = ArgsPtr.size(); 15500 Expr **Args = ArgsPtr.data(); 15501 15502 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>(); 15503 unsigned NumParams = Proto->getNumParams(); 15504 15505 // If too few arguments are available, we'll fill in the rest with defaults. 15506 if (NumArgs < NumParams) 15507 ConvertedArgs.reserve(NumParams); 15508 else 15509 ConvertedArgs.reserve(NumArgs); 15510 15511 VariadicCallType CallType = 15512 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 15513 SmallVector<Expr *, 8> AllArgs; 15514 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 15515 Proto, 0, 15516 llvm::makeArrayRef(Args, NumArgs), 15517 AllArgs, 15518 CallType, AllowExplicit, 15519 IsListInitialization); 15520 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 15521 15522 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 15523 15524 CheckConstructorCall(Constructor, DeclInitType, 15525 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 15526 Proto, Loc); 15527 15528 return Invalid; 15529 } 15530 15531 static inline bool 15532 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 15533 const FunctionDecl *FnDecl) { 15534 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 15535 if (isa<NamespaceDecl>(DC)) { 15536 return SemaRef.Diag(FnDecl->getLocation(), 15537 diag::err_operator_new_delete_declared_in_namespace) 15538 << FnDecl->getDeclName(); 15539 } 15540 15541 if (isa<TranslationUnitDecl>(DC) && 15542 FnDecl->getStorageClass() == SC_Static) { 15543 return SemaRef.Diag(FnDecl->getLocation(), 15544 diag::err_operator_new_delete_declared_static) 15545 << FnDecl->getDeclName(); 15546 } 15547 15548 return false; 15549 } 15550 15551 static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef, 15552 const PointerType *PtrTy) { 15553 auto &Ctx = SemaRef.Context; 15554 Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers(); 15555 PtrQuals.removeAddressSpace(); 15556 return Ctx.getPointerType(Ctx.getCanonicalType(Ctx.getQualifiedType( 15557 PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals))); 15558 } 15559 15560 static inline bool 15561 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 15562 CanQualType ExpectedResultType, 15563 CanQualType ExpectedFirstParamType, 15564 unsigned DependentParamTypeDiag, 15565 unsigned InvalidParamTypeDiag) { 15566 QualType ResultType = 15567 FnDecl->getType()->castAs<FunctionType>()->getReturnType(); 15568 15569 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 15570 // The operator is valid on any address space for OpenCL. 15571 // Drop address space from actual and expected result types. 15572 if (const auto *PtrTy = ResultType->getAs<PointerType>()) 15573 ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 15574 15575 if (auto ExpectedPtrTy = ExpectedResultType->getAs<PointerType>()) 15576 ExpectedResultType = RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy); 15577 } 15578 15579 // Check that the result type is what we expect. 15580 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) { 15581 // Reject even if the type is dependent; an operator delete function is 15582 // required to have a non-dependent result type. 15583 return SemaRef.Diag( 15584 FnDecl->getLocation(), 15585 ResultType->isDependentType() 15586 ? diag::err_operator_new_delete_dependent_result_type 15587 : diag::err_operator_new_delete_invalid_result_type) 15588 << FnDecl->getDeclName() << ExpectedResultType; 15589 } 15590 15591 // A function template must have at least 2 parameters. 15592 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 15593 return SemaRef.Diag(FnDecl->getLocation(), 15594 diag::err_operator_new_delete_template_too_few_parameters) 15595 << FnDecl->getDeclName(); 15596 15597 // The function decl must have at least 1 parameter. 15598 if (FnDecl->getNumParams() == 0) 15599 return SemaRef.Diag(FnDecl->getLocation(), 15600 diag::err_operator_new_delete_too_few_parameters) 15601 << FnDecl->getDeclName(); 15602 15603 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 15604 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 15605 // The operator is valid on any address space for OpenCL. 15606 // Drop address space from actual and expected first parameter types. 15607 if (const auto *PtrTy = 15608 FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) 15609 FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 15610 15611 if (auto ExpectedPtrTy = ExpectedFirstParamType->getAs<PointerType>()) 15612 ExpectedFirstParamType = 15613 RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy); 15614 } 15615 15616 // Check that the first parameter type is what we expect. 15617 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 15618 ExpectedFirstParamType) { 15619 // The first parameter type is not allowed to be dependent. As a tentative 15620 // DR resolution, we allow a dependent parameter type if it is the right 15621 // type anyway, to allow destroying operator delete in class templates. 15622 return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType() 15623 ? DependentParamTypeDiag 15624 : InvalidParamTypeDiag) 15625 << FnDecl->getDeclName() << ExpectedFirstParamType; 15626 } 15627 15628 return false; 15629 } 15630 15631 static bool 15632 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 15633 // C++ [basic.stc.dynamic.allocation]p1: 15634 // A program is ill-formed if an allocation function is declared in a 15635 // namespace scope other than global scope or declared static in global 15636 // scope. 15637 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 15638 return true; 15639 15640 CanQualType SizeTy = 15641 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 15642 15643 // C++ [basic.stc.dynamic.allocation]p1: 15644 // The return type shall be void*. The first parameter shall have type 15645 // std::size_t. 15646 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 15647 SizeTy, 15648 diag::err_operator_new_dependent_param_type, 15649 diag::err_operator_new_param_type)) 15650 return true; 15651 15652 // C++ [basic.stc.dynamic.allocation]p1: 15653 // The first parameter shall not have an associated default argument. 15654 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 15655 return SemaRef.Diag(FnDecl->getLocation(), 15656 diag::err_operator_new_default_arg) 15657 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 15658 15659 return false; 15660 } 15661 15662 static bool 15663 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 15664 // C++ [basic.stc.dynamic.deallocation]p1: 15665 // A program is ill-formed if deallocation functions are declared in a 15666 // namespace scope other than global scope or declared static in global 15667 // scope. 15668 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 15669 return true; 15670 15671 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl); 15672 15673 // C++ P0722: 15674 // Within a class C, the first parameter of a destroying operator delete 15675 // shall be of type C *. The first parameter of any other deallocation 15676 // function shall be of type void *. 15677 CanQualType ExpectedFirstParamType = 15678 MD && MD->isDestroyingOperatorDelete() 15679 ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType( 15680 SemaRef.Context.getRecordType(MD->getParent()))) 15681 : SemaRef.Context.VoidPtrTy; 15682 15683 // C++ [basic.stc.dynamic.deallocation]p2: 15684 // Each deallocation function shall return void 15685 if (CheckOperatorNewDeleteTypes( 15686 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType, 15687 diag::err_operator_delete_dependent_param_type, 15688 diag::err_operator_delete_param_type)) 15689 return true; 15690 15691 // C++ P0722: 15692 // A destroying operator delete shall be a usual deallocation function. 15693 if (MD && !MD->getParent()->isDependentContext() && 15694 MD->isDestroyingOperatorDelete() && 15695 !SemaRef.isUsualDeallocationFunction(MD)) { 15696 SemaRef.Diag(MD->getLocation(), 15697 diag::err_destroying_operator_delete_not_usual); 15698 return true; 15699 } 15700 15701 return false; 15702 } 15703 15704 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 15705 /// of this overloaded operator is well-formed. If so, returns false; 15706 /// otherwise, emits appropriate diagnostics and returns true. 15707 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 15708 assert(FnDecl && FnDecl->isOverloadedOperator() && 15709 "Expected an overloaded operator declaration"); 15710 15711 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 15712 15713 // C++ [over.oper]p5: 15714 // The allocation and deallocation functions, operator new, 15715 // operator new[], operator delete and operator delete[], are 15716 // described completely in 3.7.3. The attributes and restrictions 15717 // found in the rest of this subclause do not apply to them unless 15718 // explicitly stated in 3.7.3. 15719 if (Op == OO_Delete || Op == OO_Array_Delete) 15720 return CheckOperatorDeleteDeclaration(*this, FnDecl); 15721 15722 if (Op == OO_New || Op == OO_Array_New) 15723 return CheckOperatorNewDeclaration(*this, FnDecl); 15724 15725 // C++ [over.oper]p6: 15726 // An operator function shall either be a non-static member 15727 // function or be a non-member function and have at least one 15728 // parameter whose type is a class, a reference to a class, an 15729 // enumeration, or a reference to an enumeration. 15730 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 15731 if (MethodDecl->isStatic()) 15732 return Diag(FnDecl->getLocation(), 15733 diag::err_operator_overload_static) << FnDecl->getDeclName(); 15734 } else { 15735 bool ClassOrEnumParam = false; 15736 for (auto Param : FnDecl->parameters()) { 15737 QualType ParamType = Param->getType().getNonReferenceType(); 15738 if (ParamType->isDependentType() || ParamType->isRecordType() || 15739 ParamType->isEnumeralType()) { 15740 ClassOrEnumParam = true; 15741 break; 15742 } 15743 } 15744 15745 if (!ClassOrEnumParam) 15746 return Diag(FnDecl->getLocation(), 15747 diag::err_operator_overload_needs_class_or_enum) 15748 << FnDecl->getDeclName(); 15749 } 15750 15751 // C++ [over.oper]p8: 15752 // An operator function cannot have default arguments (8.3.6), 15753 // except where explicitly stated below. 15754 // 15755 // Only the function-call operator allows default arguments 15756 // (C++ [over.call]p1). 15757 if (Op != OO_Call) { 15758 for (auto Param : FnDecl->parameters()) { 15759 if (Param->hasDefaultArg()) 15760 return Diag(Param->getLocation(), 15761 diag::err_operator_overload_default_arg) 15762 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 15763 } 15764 } 15765 15766 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 15767 { false, false, false } 15768 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 15769 , { Unary, Binary, MemberOnly } 15770 #include "clang/Basic/OperatorKinds.def" 15771 }; 15772 15773 bool CanBeUnaryOperator = OperatorUses[Op][0]; 15774 bool CanBeBinaryOperator = OperatorUses[Op][1]; 15775 bool MustBeMemberOperator = OperatorUses[Op][2]; 15776 15777 // C++ [over.oper]p8: 15778 // [...] Operator functions cannot have more or fewer parameters 15779 // than the number required for the corresponding operator, as 15780 // described in the rest of this subclause. 15781 unsigned NumParams = FnDecl->getNumParams() 15782 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 15783 if (Op != OO_Call && 15784 ((NumParams == 1 && !CanBeUnaryOperator) || 15785 (NumParams == 2 && !CanBeBinaryOperator) || 15786 (NumParams < 1) || (NumParams > 2))) { 15787 // We have the wrong number of parameters. 15788 unsigned ErrorKind; 15789 if (CanBeUnaryOperator && CanBeBinaryOperator) { 15790 ErrorKind = 2; // 2 -> unary or binary. 15791 } else if (CanBeUnaryOperator) { 15792 ErrorKind = 0; // 0 -> unary 15793 } else { 15794 assert(CanBeBinaryOperator && 15795 "All non-call overloaded operators are unary or binary!"); 15796 ErrorKind = 1; // 1 -> binary 15797 } 15798 15799 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 15800 << FnDecl->getDeclName() << NumParams << ErrorKind; 15801 } 15802 15803 // Overloaded operators other than operator() cannot be variadic. 15804 if (Op != OO_Call && 15805 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) { 15806 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 15807 << FnDecl->getDeclName(); 15808 } 15809 15810 // Some operators must be non-static member functions. 15811 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 15812 return Diag(FnDecl->getLocation(), 15813 diag::err_operator_overload_must_be_member) 15814 << FnDecl->getDeclName(); 15815 } 15816 15817 // C++ [over.inc]p1: 15818 // The user-defined function called operator++ implements the 15819 // prefix and postfix ++ operator. If this function is a member 15820 // function with no parameters, or a non-member function with one 15821 // parameter of class or enumeration type, it defines the prefix 15822 // increment operator ++ for objects of that type. If the function 15823 // is a member function with one parameter (which shall be of type 15824 // int) or a non-member function with two parameters (the second 15825 // of which shall be of type int), it defines the postfix 15826 // increment operator ++ for objects of that type. 15827 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 15828 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 15829 QualType ParamType = LastParam->getType(); 15830 15831 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 15832 !ParamType->isDependentType()) 15833 return Diag(LastParam->getLocation(), 15834 diag::err_operator_overload_post_incdec_must_be_int) 15835 << LastParam->getType() << (Op == OO_MinusMinus); 15836 } 15837 15838 return false; 15839 } 15840 15841 static bool 15842 checkLiteralOperatorTemplateParameterList(Sema &SemaRef, 15843 FunctionTemplateDecl *TpDecl) { 15844 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters(); 15845 15846 // Must have one or two template parameters. 15847 if (TemplateParams->size() == 1) { 15848 NonTypeTemplateParmDecl *PmDecl = 15849 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0)); 15850 15851 // The template parameter must be a char parameter pack. 15852 if (PmDecl && PmDecl->isTemplateParameterPack() && 15853 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy)) 15854 return false; 15855 15856 // C++20 [over.literal]p5: 15857 // A string literal operator template is a literal operator template 15858 // whose template-parameter-list comprises a single non-type 15859 // template-parameter of class type. 15860 // 15861 // As a DR resolution, we also allow placeholders for deduced class 15862 // template specializations. 15863 if (SemaRef.getLangOpts().CPlusPlus20 && 15864 !PmDecl->isTemplateParameterPack() && 15865 (PmDecl->getType()->isRecordType() || 15866 PmDecl->getType()->getAs<DeducedTemplateSpecializationType>())) 15867 return false; 15868 } else if (TemplateParams->size() == 2) { 15869 TemplateTypeParmDecl *PmType = 15870 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0)); 15871 NonTypeTemplateParmDecl *PmArgs = 15872 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1)); 15873 15874 // The second template parameter must be a parameter pack with the 15875 // first template parameter as its type. 15876 if (PmType && PmArgs && !PmType->isTemplateParameterPack() && 15877 PmArgs->isTemplateParameterPack()) { 15878 const TemplateTypeParmType *TArgs = 15879 PmArgs->getType()->getAs<TemplateTypeParmType>(); 15880 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 15881 TArgs->getIndex() == PmType->getIndex()) { 15882 if (!SemaRef.inTemplateInstantiation()) 15883 SemaRef.Diag(TpDecl->getLocation(), 15884 diag::ext_string_literal_operator_template); 15885 return false; 15886 } 15887 } 15888 } 15889 15890 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(), 15891 diag::err_literal_operator_template) 15892 << TpDecl->getTemplateParameters()->getSourceRange(); 15893 return true; 15894 } 15895 15896 /// CheckLiteralOperatorDeclaration - Check whether the declaration 15897 /// of this literal operator function is well-formed. If so, returns 15898 /// false; otherwise, emits appropriate diagnostics and returns true. 15899 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 15900 if (isa<CXXMethodDecl>(FnDecl)) { 15901 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 15902 << FnDecl->getDeclName(); 15903 return true; 15904 } 15905 15906 if (FnDecl->isExternC()) { 15907 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 15908 if (const LinkageSpecDecl *LSD = 15909 FnDecl->getDeclContext()->getExternCContext()) 15910 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here); 15911 return true; 15912 } 15913 15914 // This might be the definition of a literal operator template. 15915 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 15916 15917 // This might be a specialization of a literal operator template. 15918 if (!TpDecl) 15919 TpDecl = FnDecl->getPrimaryTemplate(); 15920 15921 // template <char...> type operator "" name() and 15922 // template <class T, T...> type operator "" name() are the only valid 15923 // template signatures, and the only valid signatures with no parameters. 15924 // 15925 // C++20 also allows template <SomeClass T> type operator "" name(). 15926 if (TpDecl) { 15927 if (FnDecl->param_size() != 0) { 15928 Diag(FnDecl->getLocation(), 15929 diag::err_literal_operator_template_with_params); 15930 return true; 15931 } 15932 15933 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl)) 15934 return true; 15935 15936 } else if (FnDecl->param_size() == 1) { 15937 const ParmVarDecl *Param = FnDecl->getParamDecl(0); 15938 15939 QualType ParamType = Param->getType().getUnqualifiedType(); 15940 15941 // Only unsigned long long int, long double, any character type, and const 15942 // char * are allowed as the only parameters. 15943 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) || 15944 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) || 15945 Context.hasSameType(ParamType, Context.CharTy) || 15946 Context.hasSameType(ParamType, Context.WideCharTy) || 15947 Context.hasSameType(ParamType, Context.Char8Ty) || 15948 Context.hasSameType(ParamType, Context.Char16Ty) || 15949 Context.hasSameType(ParamType, Context.Char32Ty)) { 15950 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) { 15951 QualType InnerType = Ptr->getPointeeType(); 15952 15953 // Pointer parameter must be a const char *. 15954 if (!(Context.hasSameType(InnerType.getUnqualifiedType(), 15955 Context.CharTy) && 15956 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) { 15957 Diag(Param->getSourceRange().getBegin(), 15958 diag::err_literal_operator_param) 15959 << ParamType << "'const char *'" << Param->getSourceRange(); 15960 return true; 15961 } 15962 15963 } else if (ParamType->isRealFloatingType()) { 15964 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 15965 << ParamType << Context.LongDoubleTy << Param->getSourceRange(); 15966 return true; 15967 15968 } else if (ParamType->isIntegerType()) { 15969 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 15970 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange(); 15971 return true; 15972 15973 } else { 15974 Diag(Param->getSourceRange().getBegin(), 15975 diag::err_literal_operator_invalid_param) 15976 << ParamType << Param->getSourceRange(); 15977 return true; 15978 } 15979 15980 } else if (FnDecl->param_size() == 2) { 15981 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 15982 15983 // First, verify that the first parameter is correct. 15984 15985 QualType FirstParamType = (*Param)->getType().getUnqualifiedType(); 15986 15987 // Two parameter function must have a pointer to const as a 15988 // first parameter; let's strip those qualifiers. 15989 const PointerType *PT = FirstParamType->getAs<PointerType>(); 15990 15991 if (!PT) { 15992 Diag((*Param)->getSourceRange().getBegin(), 15993 diag::err_literal_operator_param) 15994 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 15995 return true; 15996 } 15997 15998 QualType PointeeType = PT->getPointeeType(); 15999 // First parameter must be const 16000 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) { 16001 Diag((*Param)->getSourceRange().getBegin(), 16002 diag::err_literal_operator_param) 16003 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 16004 return true; 16005 } 16006 16007 QualType InnerType = PointeeType.getUnqualifiedType(); 16008 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and 16009 // const char32_t* are allowed as the first parameter to a two-parameter 16010 // function 16011 if (!(Context.hasSameType(InnerType, Context.CharTy) || 16012 Context.hasSameType(InnerType, Context.WideCharTy) || 16013 Context.hasSameType(InnerType, Context.Char8Ty) || 16014 Context.hasSameType(InnerType, Context.Char16Ty) || 16015 Context.hasSameType(InnerType, Context.Char32Ty))) { 16016 Diag((*Param)->getSourceRange().getBegin(), 16017 diag::err_literal_operator_param) 16018 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 16019 return true; 16020 } 16021 16022 // Move on to the second and final parameter. 16023 ++Param; 16024 16025 // The second parameter must be a std::size_t. 16026 QualType SecondParamType = (*Param)->getType().getUnqualifiedType(); 16027 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) { 16028 Diag((*Param)->getSourceRange().getBegin(), 16029 diag::err_literal_operator_param) 16030 << SecondParamType << Context.getSizeType() 16031 << (*Param)->getSourceRange(); 16032 return true; 16033 } 16034 } else { 16035 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count); 16036 return true; 16037 } 16038 16039 // Parameters are good. 16040 16041 // A parameter-declaration-clause containing a default argument is not 16042 // equivalent to any of the permitted forms. 16043 for (auto Param : FnDecl->parameters()) { 16044 if (Param->hasDefaultArg()) { 16045 Diag(Param->getDefaultArgRange().getBegin(), 16046 diag::err_literal_operator_default_argument) 16047 << Param->getDefaultArgRange(); 16048 break; 16049 } 16050 } 16051 16052 StringRef LiteralName 16053 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 16054 if (LiteralName[0] != '_' && 16055 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) { 16056 // C++11 [usrlit.suffix]p1: 16057 // Literal suffix identifiers that do not start with an underscore 16058 // are reserved for future standardization. 16059 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 16060 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 16061 } 16062 16063 return false; 16064 } 16065 16066 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 16067 /// linkage specification, including the language and (if present) 16068 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 16069 /// language string literal. LBraceLoc, if valid, provides the location of 16070 /// the '{' brace. Otherwise, this linkage specification does not 16071 /// have any braces. 16072 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 16073 Expr *LangStr, 16074 SourceLocation LBraceLoc) { 16075 StringLiteral *Lit = cast<StringLiteral>(LangStr); 16076 if (!Lit->isAscii()) { 16077 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 16078 << LangStr->getSourceRange(); 16079 return nullptr; 16080 } 16081 16082 StringRef Lang = Lit->getString(); 16083 LinkageSpecDecl::LanguageIDs Language; 16084 if (Lang == "C") 16085 Language = LinkageSpecDecl::lang_c; 16086 else if (Lang == "C++") 16087 Language = LinkageSpecDecl::lang_cxx; 16088 else { 16089 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 16090 << LangStr->getSourceRange(); 16091 return nullptr; 16092 } 16093 16094 // FIXME: Add all the various semantics of linkage specifications 16095 16096 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 16097 LangStr->getExprLoc(), Language, 16098 LBraceLoc.isValid()); 16099 CurContext->addDecl(D); 16100 PushDeclContext(S, D); 16101 return D; 16102 } 16103 16104 /// ActOnFinishLinkageSpecification - Complete the definition of 16105 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 16106 /// valid, it's the position of the closing '}' brace in a linkage 16107 /// specification that uses braces. 16108 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 16109 Decl *LinkageSpec, 16110 SourceLocation RBraceLoc) { 16111 if (RBraceLoc.isValid()) { 16112 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 16113 LSDecl->setRBraceLoc(RBraceLoc); 16114 } 16115 PopDeclContext(); 16116 return LinkageSpec; 16117 } 16118 16119 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 16120 const ParsedAttributesView &AttrList, 16121 SourceLocation SemiLoc) { 16122 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 16123 // Attribute declarations appertain to empty declaration so we handle 16124 // them here. 16125 ProcessDeclAttributeList(S, ED, AttrList); 16126 16127 CurContext->addDecl(ED); 16128 return ED; 16129 } 16130 16131 /// Perform semantic analysis for the variable declaration that 16132 /// occurs within a C++ catch clause, returning the newly-created 16133 /// variable. 16134 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 16135 TypeSourceInfo *TInfo, 16136 SourceLocation StartLoc, 16137 SourceLocation Loc, 16138 IdentifierInfo *Name) { 16139 bool Invalid = false; 16140 QualType ExDeclType = TInfo->getType(); 16141 16142 // Arrays and functions decay. 16143 if (ExDeclType->isArrayType()) 16144 ExDeclType = Context.getArrayDecayedType(ExDeclType); 16145 else if (ExDeclType->isFunctionType()) 16146 ExDeclType = Context.getPointerType(ExDeclType); 16147 16148 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 16149 // The exception-declaration shall not denote a pointer or reference to an 16150 // incomplete type, other than [cv] void*. 16151 // N2844 forbids rvalue references. 16152 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 16153 Diag(Loc, diag::err_catch_rvalue_ref); 16154 Invalid = true; 16155 } 16156 16157 if (ExDeclType->isVariablyModifiedType()) { 16158 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType; 16159 Invalid = true; 16160 } 16161 16162 QualType BaseType = ExDeclType; 16163 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 16164 unsigned DK = diag::err_catch_incomplete; 16165 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 16166 BaseType = Ptr->getPointeeType(); 16167 Mode = 1; 16168 DK = diag::err_catch_incomplete_ptr; 16169 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 16170 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 16171 BaseType = Ref->getPointeeType(); 16172 Mode = 2; 16173 DK = diag::err_catch_incomplete_ref; 16174 } 16175 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 16176 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 16177 Invalid = true; 16178 16179 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) { 16180 Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType; 16181 Invalid = true; 16182 } 16183 16184 if (!Invalid && !ExDeclType->isDependentType() && 16185 RequireNonAbstractType(Loc, ExDeclType, 16186 diag::err_abstract_type_in_decl, 16187 AbstractVariableType)) 16188 Invalid = true; 16189 16190 // Only the non-fragile NeXT runtime currently supports C++ catches 16191 // of ObjC types, and no runtime supports catching ObjC types by value. 16192 if (!Invalid && getLangOpts().ObjC) { 16193 QualType T = ExDeclType; 16194 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 16195 T = RT->getPointeeType(); 16196 16197 if (T->isObjCObjectType()) { 16198 Diag(Loc, diag::err_objc_object_catch); 16199 Invalid = true; 16200 } else if (T->isObjCObjectPointerType()) { 16201 // FIXME: should this be a test for macosx-fragile specifically? 16202 if (getLangOpts().ObjCRuntime.isFragile()) 16203 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 16204 } 16205 } 16206 16207 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 16208 ExDeclType, TInfo, SC_None); 16209 ExDecl->setExceptionVariable(true); 16210 16211 // In ARC, infer 'retaining' for variables of retainable type. 16212 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 16213 Invalid = true; 16214 16215 if (!Invalid && !ExDeclType->isDependentType()) { 16216 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 16217 // Insulate this from anything else we might currently be parsing. 16218 EnterExpressionEvaluationContext scope( 16219 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 16220 16221 // C++ [except.handle]p16: 16222 // The object declared in an exception-declaration or, if the 16223 // exception-declaration does not specify a name, a temporary (12.2) is 16224 // copy-initialized (8.5) from the exception object. [...] 16225 // The object is destroyed when the handler exits, after the destruction 16226 // of any automatic objects initialized within the handler. 16227 // 16228 // We just pretend to initialize the object with itself, then make sure 16229 // it can be destroyed later. 16230 QualType initType = Context.getExceptionObjectType(ExDeclType); 16231 16232 InitializedEntity entity = 16233 InitializedEntity::InitializeVariable(ExDecl); 16234 InitializationKind initKind = 16235 InitializationKind::CreateCopy(Loc, SourceLocation()); 16236 16237 Expr *opaqueValue = 16238 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 16239 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 16240 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 16241 if (result.isInvalid()) 16242 Invalid = true; 16243 else { 16244 // If the constructor used was non-trivial, set this as the 16245 // "initializer". 16246 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 16247 if (!construct->getConstructor()->isTrivial()) { 16248 Expr *init = MaybeCreateExprWithCleanups(construct); 16249 ExDecl->setInit(init); 16250 } 16251 16252 // And make sure it's destructable. 16253 FinalizeVarWithDestructor(ExDecl, recordType); 16254 } 16255 } 16256 } 16257 16258 if (Invalid) 16259 ExDecl->setInvalidDecl(); 16260 16261 return ExDecl; 16262 } 16263 16264 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 16265 /// handler. 16266 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 16267 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16268 bool Invalid = D.isInvalidType(); 16269 16270 // Check for unexpanded parameter packs. 16271 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 16272 UPPC_ExceptionType)) { 16273 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 16274 D.getIdentifierLoc()); 16275 Invalid = true; 16276 } 16277 16278 IdentifierInfo *II = D.getIdentifier(); 16279 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 16280 LookupOrdinaryName, 16281 ForVisibleRedeclaration)) { 16282 // The scope should be freshly made just for us. There is just no way 16283 // it contains any previous declaration, except for function parameters in 16284 // a function-try-block's catch statement. 16285 assert(!S->isDeclScope(PrevDecl)); 16286 if (isDeclInScope(PrevDecl, CurContext, S)) { 16287 Diag(D.getIdentifierLoc(), diag::err_redefinition) 16288 << D.getIdentifier(); 16289 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 16290 Invalid = true; 16291 } else if (PrevDecl->isTemplateParameter()) 16292 // Maybe we will complain about the shadowed template parameter. 16293 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 16294 } 16295 16296 if (D.getCXXScopeSpec().isSet() && !Invalid) { 16297 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 16298 << D.getCXXScopeSpec().getRange(); 16299 Invalid = true; 16300 } 16301 16302 VarDecl *ExDecl = BuildExceptionDeclaration( 16303 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier()); 16304 if (Invalid) 16305 ExDecl->setInvalidDecl(); 16306 16307 // Add the exception declaration into this scope. 16308 if (II) 16309 PushOnScopeChains(ExDecl, S); 16310 else 16311 CurContext->addDecl(ExDecl); 16312 16313 ProcessDeclAttributes(S, ExDecl, D); 16314 return ExDecl; 16315 } 16316 16317 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 16318 Expr *AssertExpr, 16319 Expr *AssertMessageExpr, 16320 SourceLocation RParenLoc) { 16321 StringLiteral *AssertMessage = 16322 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 16323 16324 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 16325 return nullptr; 16326 16327 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 16328 AssertMessage, RParenLoc, false); 16329 } 16330 16331 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 16332 Expr *AssertExpr, 16333 StringLiteral *AssertMessage, 16334 SourceLocation RParenLoc, 16335 bool Failed) { 16336 assert(AssertExpr != nullptr && "Expected non-null condition"); 16337 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 16338 !Failed) { 16339 // In a static_assert-declaration, the constant-expression shall be a 16340 // constant expression that can be contextually converted to bool. 16341 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 16342 if (Converted.isInvalid()) 16343 Failed = true; 16344 16345 ExprResult FullAssertExpr = 16346 ActOnFinishFullExpr(Converted.get(), StaticAssertLoc, 16347 /*DiscardedValue*/ false, 16348 /*IsConstexpr*/ true); 16349 if (FullAssertExpr.isInvalid()) 16350 Failed = true; 16351 else 16352 AssertExpr = FullAssertExpr.get(); 16353 16354 llvm::APSInt Cond; 16355 if (!Failed && VerifyIntegerConstantExpression( 16356 AssertExpr, &Cond, 16357 diag::err_static_assert_expression_is_not_constant) 16358 .isInvalid()) 16359 Failed = true; 16360 16361 if (!Failed && !Cond) { 16362 SmallString<256> MsgBuffer; 16363 llvm::raw_svector_ostream Msg(MsgBuffer); 16364 if (AssertMessage) 16365 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 16366 16367 Expr *InnerCond = nullptr; 16368 std::string InnerCondDescription; 16369 std::tie(InnerCond, InnerCondDescription) = 16370 findFailedBooleanCondition(Converted.get()); 16371 if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) { 16372 // Drill down into concept specialization expressions to see why they 16373 // weren't satisfied. 16374 Diag(StaticAssertLoc, diag::err_static_assert_failed) 16375 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 16376 ConstraintSatisfaction Satisfaction; 16377 if (!CheckConstraintSatisfaction(InnerCond, Satisfaction)) 16378 DiagnoseUnsatisfiedConstraint(Satisfaction); 16379 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond) 16380 && !isa<IntegerLiteral>(InnerCond)) { 16381 Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed) 16382 << InnerCondDescription << !AssertMessage 16383 << Msg.str() << InnerCond->getSourceRange(); 16384 } else { 16385 Diag(StaticAssertLoc, diag::err_static_assert_failed) 16386 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 16387 } 16388 Failed = true; 16389 } 16390 } else { 16391 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc, 16392 /*DiscardedValue*/false, 16393 /*IsConstexpr*/true); 16394 if (FullAssertExpr.isInvalid()) 16395 Failed = true; 16396 else 16397 AssertExpr = FullAssertExpr.get(); 16398 } 16399 16400 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 16401 AssertExpr, AssertMessage, RParenLoc, 16402 Failed); 16403 16404 CurContext->addDecl(Decl); 16405 return Decl; 16406 } 16407 16408 /// Perform semantic analysis of the given friend type declaration. 16409 /// 16410 /// \returns A friend declaration that. 16411 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 16412 SourceLocation FriendLoc, 16413 TypeSourceInfo *TSInfo) { 16414 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 16415 16416 QualType T = TSInfo->getType(); 16417 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 16418 16419 // C++03 [class.friend]p2: 16420 // An elaborated-type-specifier shall be used in a friend declaration 16421 // for a class.* 16422 // 16423 // * The class-key of the elaborated-type-specifier is required. 16424 if (!CodeSynthesisContexts.empty()) { 16425 // Do not complain about the form of friend template types during any kind 16426 // of code synthesis. For template instantiation, we will have complained 16427 // when the template was defined. 16428 } else { 16429 if (!T->isElaboratedTypeSpecifier()) { 16430 // If we evaluated the type to a record type, suggest putting 16431 // a tag in front. 16432 if (const RecordType *RT = T->getAs<RecordType>()) { 16433 RecordDecl *RD = RT->getDecl(); 16434 16435 SmallString<16> InsertionText(" "); 16436 InsertionText += RD->getKindName(); 16437 16438 Diag(TypeRange.getBegin(), 16439 getLangOpts().CPlusPlus11 ? 16440 diag::warn_cxx98_compat_unelaborated_friend_type : 16441 diag::ext_unelaborated_friend_type) 16442 << (unsigned) RD->getTagKind() 16443 << T 16444 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc), 16445 InsertionText); 16446 } else { 16447 Diag(FriendLoc, 16448 getLangOpts().CPlusPlus11 ? 16449 diag::warn_cxx98_compat_nonclass_type_friend : 16450 diag::ext_nonclass_type_friend) 16451 << T 16452 << TypeRange; 16453 } 16454 } else if (T->getAs<EnumType>()) { 16455 Diag(FriendLoc, 16456 getLangOpts().CPlusPlus11 ? 16457 diag::warn_cxx98_compat_enum_friend : 16458 diag::ext_enum_friend) 16459 << T 16460 << TypeRange; 16461 } 16462 16463 // C++11 [class.friend]p3: 16464 // A friend declaration that does not declare a function shall have one 16465 // of the following forms: 16466 // friend elaborated-type-specifier ; 16467 // friend simple-type-specifier ; 16468 // friend typename-specifier ; 16469 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 16470 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 16471 } 16472 16473 // If the type specifier in a friend declaration designates a (possibly 16474 // cv-qualified) class type, that class is declared as a friend; otherwise, 16475 // the friend declaration is ignored. 16476 return FriendDecl::Create(Context, CurContext, 16477 TSInfo->getTypeLoc().getBeginLoc(), TSInfo, 16478 FriendLoc); 16479 } 16480 16481 /// Handle a friend tag declaration where the scope specifier was 16482 /// templated. 16483 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 16484 unsigned TagSpec, SourceLocation TagLoc, 16485 CXXScopeSpec &SS, IdentifierInfo *Name, 16486 SourceLocation NameLoc, 16487 const ParsedAttributesView &Attr, 16488 MultiTemplateParamsArg TempParamLists) { 16489 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 16490 16491 bool IsMemberSpecialization = false; 16492 bool Invalid = false; 16493 16494 if (TemplateParameterList *TemplateParams = 16495 MatchTemplateParametersToScopeSpecifier( 16496 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 16497 IsMemberSpecialization, Invalid)) { 16498 if (TemplateParams->size() > 0) { 16499 // This is a declaration of a class template. 16500 if (Invalid) 16501 return nullptr; 16502 16503 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 16504 NameLoc, Attr, TemplateParams, AS_public, 16505 /*ModulePrivateLoc=*/SourceLocation(), 16506 FriendLoc, TempParamLists.size() - 1, 16507 TempParamLists.data()).get(); 16508 } else { 16509 // The "template<>" header is extraneous. 16510 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 16511 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 16512 IsMemberSpecialization = true; 16513 } 16514 } 16515 16516 if (Invalid) return nullptr; 16517 16518 bool isAllExplicitSpecializations = true; 16519 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 16520 if (TempParamLists[I]->size()) { 16521 isAllExplicitSpecializations = false; 16522 break; 16523 } 16524 } 16525 16526 // FIXME: don't ignore attributes. 16527 16528 // If it's explicit specializations all the way down, just forget 16529 // about the template header and build an appropriate non-templated 16530 // friend. TODO: for source fidelity, remember the headers. 16531 if (isAllExplicitSpecializations) { 16532 if (SS.isEmpty()) { 16533 bool Owned = false; 16534 bool IsDependent = false; 16535 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 16536 Attr, AS_public, 16537 /*ModulePrivateLoc=*/SourceLocation(), 16538 MultiTemplateParamsArg(), Owned, IsDependent, 16539 /*ScopedEnumKWLoc=*/SourceLocation(), 16540 /*ScopedEnumUsesClassTag=*/false, 16541 /*UnderlyingType=*/TypeResult(), 16542 /*IsTypeSpecifier=*/false, 16543 /*IsTemplateParamOrArg=*/false); 16544 } 16545 16546 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 16547 ElaboratedTypeKeyword Keyword 16548 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 16549 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 16550 *Name, NameLoc); 16551 if (T.isNull()) 16552 return nullptr; 16553 16554 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 16555 if (isa<DependentNameType>(T)) { 16556 DependentNameTypeLoc TL = 16557 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 16558 TL.setElaboratedKeywordLoc(TagLoc); 16559 TL.setQualifierLoc(QualifierLoc); 16560 TL.setNameLoc(NameLoc); 16561 } else { 16562 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 16563 TL.setElaboratedKeywordLoc(TagLoc); 16564 TL.setQualifierLoc(QualifierLoc); 16565 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 16566 } 16567 16568 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 16569 TSI, FriendLoc, TempParamLists); 16570 Friend->setAccess(AS_public); 16571 CurContext->addDecl(Friend); 16572 return Friend; 16573 } 16574 16575 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 16576 16577 16578 16579 // Handle the case of a templated-scope friend class. e.g. 16580 // template <class T> class A<T>::B; 16581 // FIXME: we don't support these right now. 16582 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 16583 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 16584 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 16585 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 16586 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 16587 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 16588 TL.setElaboratedKeywordLoc(TagLoc); 16589 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 16590 TL.setNameLoc(NameLoc); 16591 16592 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 16593 TSI, FriendLoc, TempParamLists); 16594 Friend->setAccess(AS_public); 16595 Friend->setUnsupportedFriend(true); 16596 CurContext->addDecl(Friend); 16597 return Friend; 16598 } 16599 16600 /// Handle a friend type declaration. This works in tandem with 16601 /// ActOnTag. 16602 /// 16603 /// Notes on friend class templates: 16604 /// 16605 /// We generally treat friend class declarations as if they were 16606 /// declaring a class. So, for example, the elaborated type specifier 16607 /// in a friend declaration is required to obey the restrictions of a 16608 /// class-head (i.e. no typedefs in the scope chain), template 16609 /// parameters are required to match up with simple template-ids, &c. 16610 /// However, unlike when declaring a template specialization, it's 16611 /// okay to refer to a template specialization without an empty 16612 /// template parameter declaration, e.g. 16613 /// friend class A<T>::B<unsigned>; 16614 /// We permit this as a special case; if there are any template 16615 /// parameters present at all, require proper matching, i.e. 16616 /// template <> template \<class T> friend class A<int>::B; 16617 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 16618 MultiTemplateParamsArg TempParams) { 16619 SourceLocation Loc = DS.getBeginLoc(); 16620 16621 assert(DS.isFriendSpecified()); 16622 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 16623 16624 // C++ [class.friend]p3: 16625 // A friend declaration that does not declare a function shall have one of 16626 // the following forms: 16627 // friend elaborated-type-specifier ; 16628 // friend simple-type-specifier ; 16629 // friend typename-specifier ; 16630 // 16631 // Any declaration with a type qualifier does not have that form. (It's 16632 // legal to specify a qualified type as a friend, you just can't write the 16633 // keywords.) 16634 if (DS.getTypeQualifiers()) { 16635 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 16636 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const"; 16637 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 16638 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile"; 16639 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 16640 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict"; 16641 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 16642 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic"; 16643 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 16644 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned"; 16645 } 16646 16647 // Try to convert the decl specifier to a type. This works for 16648 // friend templates because ActOnTag never produces a ClassTemplateDecl 16649 // for a TUK_Friend. 16650 Declarator TheDeclarator(DS, DeclaratorContext::Member); 16651 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 16652 QualType T = TSI->getType(); 16653 if (TheDeclarator.isInvalidType()) 16654 return nullptr; 16655 16656 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 16657 return nullptr; 16658 16659 // This is definitely an error in C++98. It's probably meant to 16660 // be forbidden in C++0x, too, but the specification is just 16661 // poorly written. 16662 // 16663 // The problem is with declarations like the following: 16664 // template <T> friend A<T>::foo; 16665 // where deciding whether a class C is a friend or not now hinges 16666 // on whether there exists an instantiation of A that causes 16667 // 'foo' to equal C. There are restrictions on class-heads 16668 // (which we declare (by fiat) elaborated friend declarations to 16669 // be) that makes this tractable. 16670 // 16671 // FIXME: handle "template <> friend class A<T>;", which 16672 // is possibly well-formed? Who even knows? 16673 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 16674 Diag(Loc, diag::err_tagless_friend_type_template) 16675 << DS.getSourceRange(); 16676 return nullptr; 16677 } 16678 16679 // C++98 [class.friend]p1: A friend of a class is a function 16680 // or class that is not a member of the class . . . 16681 // This is fixed in DR77, which just barely didn't make the C++03 16682 // deadline. It's also a very silly restriction that seriously 16683 // affects inner classes and which nobody else seems to implement; 16684 // thus we never diagnose it, not even in -pedantic. 16685 // 16686 // But note that we could warn about it: it's always useless to 16687 // friend one of your own members (it's not, however, worthless to 16688 // friend a member of an arbitrary specialization of your template). 16689 16690 Decl *D; 16691 if (!TempParams.empty()) 16692 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 16693 TempParams, 16694 TSI, 16695 DS.getFriendSpecLoc()); 16696 else 16697 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 16698 16699 if (!D) 16700 return nullptr; 16701 16702 D->setAccess(AS_public); 16703 CurContext->addDecl(D); 16704 16705 return D; 16706 } 16707 16708 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 16709 MultiTemplateParamsArg TemplateParams) { 16710 const DeclSpec &DS = D.getDeclSpec(); 16711 16712 assert(DS.isFriendSpecified()); 16713 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 16714 16715 SourceLocation Loc = D.getIdentifierLoc(); 16716 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16717 16718 // C++ [class.friend]p1 16719 // A friend of a class is a function or class.... 16720 // Note that this sees through typedefs, which is intended. 16721 // It *doesn't* see through dependent types, which is correct 16722 // according to [temp.arg.type]p3: 16723 // If a declaration acquires a function type through a 16724 // type dependent on a template-parameter and this causes 16725 // a declaration that does not use the syntactic form of a 16726 // function declarator to have a function type, the program 16727 // is ill-formed. 16728 if (!TInfo->getType()->isFunctionType()) { 16729 Diag(Loc, diag::err_unexpected_friend); 16730 16731 // It might be worthwhile to try to recover by creating an 16732 // appropriate declaration. 16733 return nullptr; 16734 } 16735 16736 // C++ [namespace.memdef]p3 16737 // - If a friend declaration in a non-local class first declares a 16738 // class or function, the friend class or function is a member 16739 // of the innermost enclosing namespace. 16740 // - The name of the friend is not found by simple name lookup 16741 // until a matching declaration is provided in that namespace 16742 // scope (either before or after the class declaration granting 16743 // friendship). 16744 // - If a friend function is called, its name may be found by the 16745 // name lookup that considers functions from namespaces and 16746 // classes associated with the types of the function arguments. 16747 // - When looking for a prior declaration of a class or a function 16748 // declared as a friend, scopes outside the innermost enclosing 16749 // namespace scope are not considered. 16750 16751 CXXScopeSpec &SS = D.getCXXScopeSpec(); 16752 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 16753 assert(NameInfo.getName()); 16754 16755 // Check for unexpanded parameter packs. 16756 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 16757 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 16758 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 16759 return nullptr; 16760 16761 // The context we found the declaration in, or in which we should 16762 // create the declaration. 16763 DeclContext *DC; 16764 Scope *DCScope = S; 16765 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 16766 ForExternalRedeclaration); 16767 16768 // There are five cases here. 16769 // - There's no scope specifier and we're in a local class. Only look 16770 // for functions declared in the immediately-enclosing block scope. 16771 // We recover from invalid scope qualifiers as if they just weren't there. 16772 FunctionDecl *FunctionContainingLocalClass = nullptr; 16773 if ((SS.isInvalid() || !SS.isSet()) && 16774 (FunctionContainingLocalClass = 16775 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 16776 // C++11 [class.friend]p11: 16777 // If a friend declaration appears in a local class and the name 16778 // specified is an unqualified name, a prior declaration is 16779 // looked up without considering scopes that are outside the 16780 // innermost enclosing non-class scope. For a friend function 16781 // declaration, if there is no prior declaration, the program is 16782 // ill-formed. 16783 16784 // Find the innermost enclosing non-class scope. This is the block 16785 // scope containing the local class definition (or for a nested class, 16786 // the outer local class). 16787 DCScope = S->getFnParent(); 16788 16789 // Look up the function name in the scope. 16790 Previous.clear(LookupLocalFriendName); 16791 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 16792 16793 if (!Previous.empty()) { 16794 // All possible previous declarations must have the same context: 16795 // either they were declared at block scope or they are members of 16796 // one of the enclosing local classes. 16797 DC = Previous.getRepresentativeDecl()->getDeclContext(); 16798 } else { 16799 // This is ill-formed, but provide the context that we would have 16800 // declared the function in, if we were permitted to, for error recovery. 16801 DC = FunctionContainingLocalClass; 16802 } 16803 adjustContextForLocalExternDecl(DC); 16804 16805 // C++ [class.friend]p6: 16806 // A function can be defined in a friend declaration of a class if and 16807 // only if the class is a non-local class (9.8), the function name is 16808 // unqualified, and the function has namespace scope. 16809 if (D.isFunctionDefinition()) { 16810 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 16811 } 16812 16813 // - There's no scope specifier, in which case we just go to the 16814 // appropriate scope and look for a function or function template 16815 // there as appropriate. 16816 } else if (SS.isInvalid() || !SS.isSet()) { 16817 // C++11 [namespace.memdef]p3: 16818 // If the name in a friend declaration is neither qualified nor 16819 // a template-id and the declaration is a function or an 16820 // elaborated-type-specifier, the lookup to determine whether 16821 // the entity has been previously declared shall not consider 16822 // any scopes outside the innermost enclosing namespace. 16823 bool isTemplateId = 16824 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId; 16825 16826 // Find the appropriate context according to the above. 16827 DC = CurContext; 16828 16829 // Skip class contexts. If someone can cite chapter and verse 16830 // for this behavior, that would be nice --- it's what GCC and 16831 // EDG do, and it seems like a reasonable intent, but the spec 16832 // really only says that checks for unqualified existing 16833 // declarations should stop at the nearest enclosing namespace, 16834 // not that they should only consider the nearest enclosing 16835 // namespace. 16836 while (DC->isRecord()) 16837 DC = DC->getParent(); 16838 16839 DeclContext *LookupDC = DC; 16840 while (LookupDC->isTransparentContext()) 16841 LookupDC = LookupDC->getParent(); 16842 16843 while (true) { 16844 LookupQualifiedName(Previous, LookupDC); 16845 16846 if (!Previous.empty()) { 16847 DC = LookupDC; 16848 break; 16849 } 16850 16851 if (isTemplateId) { 16852 if (isa<TranslationUnitDecl>(LookupDC)) break; 16853 } else { 16854 if (LookupDC->isFileContext()) break; 16855 } 16856 LookupDC = LookupDC->getParent(); 16857 } 16858 16859 DCScope = getScopeForDeclContext(S, DC); 16860 16861 // - There's a non-dependent scope specifier, in which case we 16862 // compute it and do a previous lookup there for a function 16863 // or function template. 16864 } else if (!SS.getScopeRep()->isDependent()) { 16865 DC = computeDeclContext(SS); 16866 if (!DC) return nullptr; 16867 16868 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 16869 16870 LookupQualifiedName(Previous, DC); 16871 16872 // C++ [class.friend]p1: A friend of a class is a function or 16873 // class that is not a member of the class . . . 16874 if (DC->Equals(CurContext)) 16875 Diag(DS.getFriendSpecLoc(), 16876 getLangOpts().CPlusPlus11 ? 16877 diag::warn_cxx98_compat_friend_is_member : 16878 diag::err_friend_is_member); 16879 16880 if (D.isFunctionDefinition()) { 16881 // C++ [class.friend]p6: 16882 // A function can be defined in a friend declaration of a class if and 16883 // only if the class is a non-local class (9.8), the function name is 16884 // unqualified, and the function has namespace scope. 16885 // 16886 // FIXME: We should only do this if the scope specifier names the 16887 // innermost enclosing namespace; otherwise the fixit changes the 16888 // meaning of the code. 16889 SemaDiagnosticBuilder DB 16890 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 16891 16892 DB << SS.getScopeRep(); 16893 if (DC->isFileContext()) 16894 DB << FixItHint::CreateRemoval(SS.getRange()); 16895 SS.clear(); 16896 } 16897 16898 // - There's a scope specifier that does not match any template 16899 // parameter lists, in which case we use some arbitrary context, 16900 // create a method or method template, and wait for instantiation. 16901 // - There's a scope specifier that does match some template 16902 // parameter lists, which we don't handle right now. 16903 } else { 16904 if (D.isFunctionDefinition()) { 16905 // C++ [class.friend]p6: 16906 // A function can be defined in a friend declaration of a class if and 16907 // only if the class is a non-local class (9.8), the function name is 16908 // unqualified, and the function has namespace scope. 16909 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 16910 << SS.getScopeRep(); 16911 } 16912 16913 DC = CurContext; 16914 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 16915 } 16916 16917 if (!DC->isRecord()) { 16918 int DiagArg = -1; 16919 switch (D.getName().getKind()) { 16920 case UnqualifiedIdKind::IK_ConstructorTemplateId: 16921 case UnqualifiedIdKind::IK_ConstructorName: 16922 DiagArg = 0; 16923 break; 16924 case UnqualifiedIdKind::IK_DestructorName: 16925 DiagArg = 1; 16926 break; 16927 case UnqualifiedIdKind::IK_ConversionFunctionId: 16928 DiagArg = 2; 16929 break; 16930 case UnqualifiedIdKind::IK_DeductionGuideName: 16931 DiagArg = 3; 16932 break; 16933 case UnqualifiedIdKind::IK_Identifier: 16934 case UnqualifiedIdKind::IK_ImplicitSelfParam: 16935 case UnqualifiedIdKind::IK_LiteralOperatorId: 16936 case UnqualifiedIdKind::IK_OperatorFunctionId: 16937 case UnqualifiedIdKind::IK_TemplateId: 16938 break; 16939 } 16940 // This implies that it has to be an operator or function. 16941 if (DiagArg >= 0) { 16942 Diag(Loc, diag::err_introducing_special_friend) << DiagArg; 16943 return nullptr; 16944 } 16945 } 16946 16947 // FIXME: This is an egregious hack to cope with cases where the scope stack 16948 // does not contain the declaration context, i.e., in an out-of-line 16949 // definition of a class. 16950 Scope FakeDCScope(S, Scope::DeclScope, Diags); 16951 if (!DCScope) { 16952 FakeDCScope.setEntity(DC); 16953 DCScope = &FakeDCScope; 16954 } 16955 16956 bool AddToScope = true; 16957 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 16958 TemplateParams, AddToScope); 16959 if (!ND) return nullptr; 16960 16961 assert(ND->getLexicalDeclContext() == CurContext); 16962 16963 // If we performed typo correction, we might have added a scope specifier 16964 // and changed the decl context. 16965 DC = ND->getDeclContext(); 16966 16967 // Add the function declaration to the appropriate lookup tables, 16968 // adjusting the redeclarations list as necessary. We don't 16969 // want to do this yet if the friending class is dependent. 16970 // 16971 // Also update the scope-based lookup if the target context's 16972 // lookup context is in lexical scope. 16973 if (!CurContext->isDependentContext()) { 16974 DC = DC->getRedeclContext(); 16975 DC->makeDeclVisibleInContext(ND); 16976 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 16977 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 16978 } 16979 16980 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 16981 D.getIdentifierLoc(), ND, 16982 DS.getFriendSpecLoc()); 16983 FrD->setAccess(AS_public); 16984 CurContext->addDecl(FrD); 16985 16986 if (ND->isInvalidDecl()) { 16987 FrD->setInvalidDecl(); 16988 } else { 16989 if (DC->isRecord()) CheckFriendAccess(ND); 16990 16991 FunctionDecl *FD; 16992 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 16993 FD = FTD->getTemplatedDecl(); 16994 else 16995 FD = cast<FunctionDecl>(ND); 16996 16997 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 16998 // default argument expression, that declaration shall be a definition 16999 // and shall be the only declaration of the function or function 17000 // template in the translation unit. 17001 if (functionDeclHasDefaultArgument(FD)) { 17002 // We can't look at FD->getPreviousDecl() because it may not have been set 17003 // if we're in a dependent context. If the function is known to be a 17004 // redeclaration, we will have narrowed Previous down to the right decl. 17005 if (D.isRedeclaration()) { 17006 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 17007 Diag(Previous.getRepresentativeDecl()->getLocation(), 17008 diag::note_previous_declaration); 17009 } else if (!D.isFunctionDefinition()) 17010 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 17011 } 17012 17013 // Mark templated-scope function declarations as unsupported. 17014 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 17015 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 17016 << SS.getScopeRep() << SS.getRange() 17017 << cast<CXXRecordDecl>(CurContext); 17018 FrD->setUnsupportedFriend(true); 17019 } 17020 } 17021 17022 warnOnReservedIdentifier(ND); 17023 17024 return ND; 17025 } 17026 17027 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 17028 AdjustDeclIfTemplate(Dcl); 17029 17030 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 17031 if (!Fn) { 17032 Diag(DelLoc, diag::err_deleted_non_function); 17033 return; 17034 } 17035 17036 // Deleted function does not have a body. 17037 Fn->setWillHaveBody(false); 17038 17039 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 17040 // Don't consider the implicit declaration we generate for explicit 17041 // specializations. FIXME: Do not generate these implicit declarations. 17042 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 17043 Prev->getPreviousDecl()) && 17044 !Prev->isDefined()) { 17045 Diag(DelLoc, diag::err_deleted_decl_not_first); 17046 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 17047 Prev->isImplicit() ? diag::note_previous_implicit_declaration 17048 : diag::note_previous_declaration); 17049 // We can't recover from this; the declaration might have already 17050 // been used. 17051 Fn->setInvalidDecl(); 17052 return; 17053 } 17054 17055 // To maintain the invariant that functions are only deleted on their first 17056 // declaration, mark the implicitly-instantiated declaration of the 17057 // explicitly-specialized function as deleted instead of marking the 17058 // instantiated redeclaration. 17059 Fn = Fn->getCanonicalDecl(); 17060 } 17061 17062 // dllimport/dllexport cannot be deleted. 17063 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 17064 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 17065 Fn->setInvalidDecl(); 17066 } 17067 17068 // C++11 [basic.start.main]p3: 17069 // A program that defines main as deleted [...] is ill-formed. 17070 if (Fn->isMain()) 17071 Diag(DelLoc, diag::err_deleted_main); 17072 17073 // C++11 [dcl.fct.def.delete]p4: 17074 // A deleted function is implicitly inline. 17075 Fn->setImplicitlyInline(); 17076 Fn->setDeletedAsWritten(); 17077 } 17078 17079 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 17080 if (!Dcl || Dcl->isInvalidDecl()) 17081 return; 17082 17083 auto *FD = dyn_cast<FunctionDecl>(Dcl); 17084 if (!FD) { 17085 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) { 17086 if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) { 17087 Diag(DefaultLoc, diag::err_defaulted_comparison_template); 17088 return; 17089 } 17090 } 17091 17092 Diag(DefaultLoc, diag::err_default_special_members) 17093 << getLangOpts().CPlusPlus20; 17094 return; 17095 } 17096 17097 // Reject if this can't possibly be a defaultable function. 17098 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD); 17099 if (!DefKind && 17100 // A dependent function that doesn't locally look defaultable can 17101 // still instantiate to a defaultable function if it's a constructor 17102 // or assignment operator. 17103 (!FD->isDependentContext() || 17104 (!isa<CXXConstructorDecl>(FD) && 17105 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) { 17106 Diag(DefaultLoc, diag::err_default_special_members) 17107 << getLangOpts().CPlusPlus20; 17108 return; 17109 } 17110 17111 if (DefKind.isComparison() && 17112 !isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 17113 Diag(FD->getLocation(), diag::err_defaulted_comparison_out_of_class) 17114 << (int)DefKind.asComparison(); 17115 return; 17116 } 17117 17118 // Issue compatibility warning. We already warned if the operator is 17119 // 'operator<=>' when parsing the '<=>' token. 17120 if (DefKind.isComparison() && 17121 DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) { 17122 Diag(DefaultLoc, getLangOpts().CPlusPlus20 17123 ? diag::warn_cxx17_compat_defaulted_comparison 17124 : diag::ext_defaulted_comparison); 17125 } 17126 17127 FD->setDefaulted(); 17128 FD->setExplicitlyDefaulted(); 17129 17130 // Defer checking functions that are defaulted in a dependent context. 17131 if (FD->isDependentContext()) 17132 return; 17133 17134 // Unset that we will have a body for this function. We might not, 17135 // if it turns out to be trivial, and we don't need this marking now 17136 // that we've marked it as defaulted. 17137 FD->setWillHaveBody(false); 17138 17139 // If this definition appears within the record, do the checking when 17140 // the record is complete. This is always the case for a defaulted 17141 // comparison. 17142 if (DefKind.isComparison()) 17143 return; 17144 auto *MD = cast<CXXMethodDecl>(FD); 17145 17146 const FunctionDecl *Primary = FD; 17147 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern()) 17148 // Ask the template instantiation pattern that actually had the 17149 // '= default' on it. 17150 Primary = Pattern; 17151 17152 // If the method was defaulted on its first declaration, we will have 17153 // already performed the checking in CheckCompletedCXXClass. Such a 17154 // declaration doesn't trigger an implicit definition. 17155 if (Primary->getCanonicalDecl()->isDefaulted()) 17156 return; 17157 17158 // FIXME: Once we support defining comparisons out of class, check for a 17159 // defaulted comparison here. 17160 if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember())) 17161 MD->setInvalidDecl(); 17162 else 17163 DefineDefaultedFunction(*this, MD, DefaultLoc); 17164 } 17165 17166 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 17167 for (Stmt *SubStmt : S->children()) { 17168 if (!SubStmt) 17169 continue; 17170 if (isa<ReturnStmt>(SubStmt)) 17171 Self.Diag(SubStmt->getBeginLoc(), 17172 diag::err_return_in_constructor_handler); 17173 if (!isa<Expr>(SubStmt)) 17174 SearchForReturnInStmt(Self, SubStmt); 17175 } 17176 } 17177 17178 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 17179 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 17180 CXXCatchStmt *Handler = TryBlock->getHandler(I); 17181 SearchForReturnInStmt(*this, Handler); 17182 } 17183 } 17184 17185 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 17186 const CXXMethodDecl *Old) { 17187 const auto *NewFT = New->getType()->castAs<FunctionProtoType>(); 17188 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>(); 17189 17190 if (OldFT->hasExtParameterInfos()) { 17191 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I) 17192 // A parameter of the overriding method should be annotated with noescape 17193 // if the corresponding parameter of the overridden method is annotated. 17194 if (OldFT->getExtParameterInfo(I).isNoEscape() && 17195 !NewFT->getExtParameterInfo(I).isNoEscape()) { 17196 Diag(New->getParamDecl(I)->getLocation(), 17197 diag::warn_overriding_method_missing_noescape); 17198 Diag(Old->getParamDecl(I)->getLocation(), 17199 diag::note_overridden_marked_noescape); 17200 } 17201 } 17202 17203 // Virtual overrides must have the same code_seg. 17204 const auto *OldCSA = Old->getAttr<CodeSegAttr>(); 17205 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 17206 if ((NewCSA || OldCSA) && 17207 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) { 17208 Diag(New->getLocation(), diag::err_mismatched_code_seg_override); 17209 Diag(Old->getLocation(), diag::note_previous_declaration); 17210 return true; 17211 } 17212 17213 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 17214 17215 // If the calling conventions match, everything is fine 17216 if (NewCC == OldCC) 17217 return false; 17218 17219 // If the calling conventions mismatch because the new function is static, 17220 // suppress the calling convention mismatch error; the error about static 17221 // function override (err_static_overrides_virtual from 17222 // Sema::CheckFunctionDeclaration) is more clear. 17223 if (New->getStorageClass() == SC_Static) 17224 return false; 17225 17226 Diag(New->getLocation(), 17227 diag::err_conflicting_overriding_cc_attributes) 17228 << New->getDeclName() << New->getType() << Old->getType(); 17229 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 17230 return true; 17231 } 17232 17233 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 17234 const CXXMethodDecl *Old) { 17235 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType(); 17236 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType(); 17237 17238 if (Context.hasSameType(NewTy, OldTy) || 17239 NewTy->isDependentType() || OldTy->isDependentType()) 17240 return false; 17241 17242 // Check if the return types are covariant 17243 QualType NewClassTy, OldClassTy; 17244 17245 /// Both types must be pointers or references to classes. 17246 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 17247 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 17248 NewClassTy = NewPT->getPointeeType(); 17249 OldClassTy = OldPT->getPointeeType(); 17250 } 17251 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 17252 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 17253 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 17254 NewClassTy = NewRT->getPointeeType(); 17255 OldClassTy = OldRT->getPointeeType(); 17256 } 17257 } 17258 } 17259 17260 // The return types aren't either both pointers or references to a class type. 17261 if (NewClassTy.isNull()) { 17262 Diag(New->getLocation(), 17263 diag::err_different_return_type_for_overriding_virtual_function) 17264 << New->getDeclName() << NewTy << OldTy 17265 << New->getReturnTypeSourceRange(); 17266 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17267 << Old->getReturnTypeSourceRange(); 17268 17269 return true; 17270 } 17271 17272 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 17273 // C++14 [class.virtual]p8: 17274 // If the class type in the covariant return type of D::f differs from 17275 // that of B::f, the class type in the return type of D::f shall be 17276 // complete at the point of declaration of D::f or shall be the class 17277 // type D. 17278 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 17279 if (!RT->isBeingDefined() && 17280 RequireCompleteType(New->getLocation(), NewClassTy, 17281 diag::err_covariant_return_incomplete, 17282 New->getDeclName())) 17283 return true; 17284 } 17285 17286 // Check if the new class derives from the old class. 17287 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) { 17288 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 17289 << New->getDeclName() << NewTy << OldTy 17290 << New->getReturnTypeSourceRange(); 17291 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17292 << Old->getReturnTypeSourceRange(); 17293 return true; 17294 } 17295 17296 // Check if we the conversion from derived to base is valid. 17297 if (CheckDerivedToBaseConversion( 17298 NewClassTy, OldClassTy, 17299 diag::err_covariant_return_inaccessible_base, 17300 diag::err_covariant_return_ambiguous_derived_to_base_conv, 17301 New->getLocation(), New->getReturnTypeSourceRange(), 17302 New->getDeclName(), nullptr)) { 17303 // FIXME: this note won't trigger for delayed access control 17304 // diagnostics, and it's impossible to get an undelayed error 17305 // here from access control during the original parse because 17306 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 17307 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17308 << Old->getReturnTypeSourceRange(); 17309 return true; 17310 } 17311 } 17312 17313 // The qualifiers of the return types must be the same. 17314 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 17315 Diag(New->getLocation(), 17316 diag::err_covariant_return_type_different_qualifications) 17317 << New->getDeclName() << NewTy << OldTy 17318 << New->getReturnTypeSourceRange(); 17319 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17320 << Old->getReturnTypeSourceRange(); 17321 return true; 17322 } 17323 17324 17325 // The new class type must have the same or less qualifiers as the old type. 17326 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 17327 Diag(New->getLocation(), 17328 diag::err_covariant_return_type_class_type_more_qualified) 17329 << New->getDeclName() << NewTy << OldTy 17330 << New->getReturnTypeSourceRange(); 17331 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 17332 << Old->getReturnTypeSourceRange(); 17333 return true; 17334 } 17335 17336 return false; 17337 } 17338 17339 /// Mark the given method pure. 17340 /// 17341 /// \param Method the method to be marked pure. 17342 /// 17343 /// \param InitRange the source range that covers the "0" initializer. 17344 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 17345 SourceLocation EndLoc = InitRange.getEnd(); 17346 if (EndLoc.isValid()) 17347 Method->setRangeEnd(EndLoc); 17348 17349 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 17350 Method->setPure(); 17351 return false; 17352 } 17353 17354 if (!Method->isInvalidDecl()) 17355 Diag(Method->getLocation(), diag::err_non_virtual_pure) 17356 << Method->getDeclName() << InitRange; 17357 return true; 17358 } 17359 17360 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) { 17361 if (D->getFriendObjectKind()) 17362 Diag(D->getLocation(), diag::err_pure_friend); 17363 else if (auto *M = dyn_cast<CXXMethodDecl>(D)) 17364 CheckPureMethod(M, ZeroLoc); 17365 else 17366 Diag(D->getLocation(), diag::err_illegal_initializer); 17367 } 17368 17369 /// Determine whether the given declaration is a global variable or 17370 /// static data member. 17371 static bool isNonlocalVariable(const Decl *D) { 17372 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 17373 return Var->hasGlobalStorage(); 17374 17375 return false; 17376 } 17377 17378 /// Invoked when we are about to parse an initializer for the declaration 17379 /// 'Dcl'. 17380 /// 17381 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 17382 /// static data member of class X, names should be looked up in the scope of 17383 /// class X. If the declaration had a scope specifier, a scope will have 17384 /// been created and passed in for this purpose. Otherwise, S will be null. 17385 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 17386 // If there is no declaration, there was an error parsing it. 17387 if (!D || D->isInvalidDecl()) 17388 return; 17389 17390 // We will always have a nested name specifier here, but this declaration 17391 // might not be out of line if the specifier names the current namespace: 17392 // extern int n; 17393 // int ::n = 0; 17394 if (S && D->isOutOfLine()) 17395 EnterDeclaratorContext(S, D->getDeclContext()); 17396 17397 // If we are parsing the initializer for a static data member, push a 17398 // new expression evaluation context that is associated with this static 17399 // data member. 17400 if (isNonlocalVariable(D)) 17401 PushExpressionEvaluationContext( 17402 ExpressionEvaluationContext::PotentiallyEvaluated, D); 17403 } 17404 17405 /// Invoked after we are finished parsing an initializer for the declaration D. 17406 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 17407 // If there is no declaration, there was an error parsing it. 17408 if (!D || D->isInvalidDecl()) 17409 return; 17410 17411 if (isNonlocalVariable(D)) 17412 PopExpressionEvaluationContext(); 17413 17414 if (S && D->isOutOfLine()) 17415 ExitDeclaratorContext(S); 17416 } 17417 17418 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 17419 /// C++ if/switch/while/for statement. 17420 /// e.g: "if (int x = f()) {...}" 17421 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 17422 // C++ 6.4p2: 17423 // The declarator shall not specify a function or an array. 17424 // The type-specifier-seq shall not contain typedef and shall not declare a 17425 // new class or enumeration. 17426 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 17427 "Parser allowed 'typedef' as storage class of condition decl."); 17428 17429 Decl *Dcl = ActOnDeclarator(S, D); 17430 if (!Dcl) 17431 return true; 17432 17433 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 17434 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 17435 << D.getSourceRange(); 17436 return true; 17437 } 17438 17439 return Dcl; 17440 } 17441 17442 void Sema::LoadExternalVTableUses() { 17443 if (!ExternalSource) 17444 return; 17445 17446 SmallVector<ExternalVTableUse, 4> VTables; 17447 ExternalSource->ReadUsedVTables(VTables); 17448 SmallVector<VTableUse, 4> NewUses; 17449 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 17450 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 17451 = VTablesUsed.find(VTables[I].Record); 17452 // Even if a definition wasn't required before, it may be required now. 17453 if (Pos != VTablesUsed.end()) { 17454 if (!Pos->second && VTables[I].DefinitionRequired) 17455 Pos->second = true; 17456 continue; 17457 } 17458 17459 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 17460 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 17461 } 17462 17463 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 17464 } 17465 17466 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 17467 bool DefinitionRequired) { 17468 // Ignore any vtable uses in unevaluated operands or for classes that do 17469 // not have a vtable. 17470 if (!Class->isDynamicClass() || Class->isDependentContext() || 17471 CurContext->isDependentContext() || isUnevaluatedContext()) 17472 return; 17473 // Do not mark as used if compiling for the device outside of the target 17474 // region. 17475 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice && 17476 !isInOpenMPDeclareTargetContext() && 17477 !isInOpenMPTargetExecutionDirective()) { 17478 if (!DefinitionRequired) 17479 MarkVirtualMembersReferenced(Loc, Class); 17480 return; 17481 } 17482 17483 // Try to insert this class into the map. 17484 LoadExternalVTableUses(); 17485 Class = Class->getCanonicalDecl(); 17486 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 17487 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 17488 if (!Pos.second) { 17489 // If we already had an entry, check to see if we are promoting this vtable 17490 // to require a definition. If so, we need to reappend to the VTableUses 17491 // list, since we may have already processed the first entry. 17492 if (DefinitionRequired && !Pos.first->second) { 17493 Pos.first->second = true; 17494 } else { 17495 // Otherwise, we can early exit. 17496 return; 17497 } 17498 } else { 17499 // The Microsoft ABI requires that we perform the destructor body 17500 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 17501 // the deleting destructor is emitted with the vtable, not with the 17502 // destructor definition as in the Itanium ABI. 17503 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 17504 CXXDestructorDecl *DD = Class->getDestructor(); 17505 if (DD && DD->isVirtual() && !DD->isDeleted()) { 17506 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) { 17507 // If this is an out-of-line declaration, marking it referenced will 17508 // not do anything. Manually call CheckDestructor to look up operator 17509 // delete(). 17510 ContextRAII SavedContext(*this, DD); 17511 CheckDestructor(DD); 17512 } else { 17513 MarkFunctionReferenced(Loc, Class->getDestructor()); 17514 } 17515 } 17516 } 17517 } 17518 17519 // Local classes need to have their virtual members marked 17520 // immediately. For all other classes, we mark their virtual members 17521 // at the end of the translation unit. 17522 if (Class->isLocalClass()) 17523 MarkVirtualMembersReferenced(Loc, Class); 17524 else 17525 VTableUses.push_back(std::make_pair(Class, Loc)); 17526 } 17527 17528 bool Sema::DefineUsedVTables() { 17529 LoadExternalVTableUses(); 17530 if (VTableUses.empty()) 17531 return false; 17532 17533 // Note: The VTableUses vector could grow as a result of marking 17534 // the members of a class as "used", so we check the size each 17535 // time through the loop and prefer indices (which are stable) to 17536 // iterators (which are not). 17537 bool DefinedAnything = false; 17538 for (unsigned I = 0; I != VTableUses.size(); ++I) { 17539 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 17540 if (!Class) 17541 continue; 17542 TemplateSpecializationKind ClassTSK = 17543 Class->getTemplateSpecializationKind(); 17544 17545 SourceLocation Loc = VTableUses[I].second; 17546 17547 bool DefineVTable = true; 17548 17549 // If this class has a key function, but that key function is 17550 // defined in another translation unit, we don't need to emit the 17551 // vtable even though we're using it. 17552 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 17553 if (KeyFunction && !KeyFunction->hasBody()) { 17554 // The key function is in another translation unit. 17555 DefineVTable = false; 17556 TemplateSpecializationKind TSK = 17557 KeyFunction->getTemplateSpecializationKind(); 17558 assert(TSK != TSK_ExplicitInstantiationDefinition && 17559 TSK != TSK_ImplicitInstantiation && 17560 "Instantiations don't have key functions"); 17561 (void)TSK; 17562 } else if (!KeyFunction) { 17563 // If we have a class with no key function that is the subject 17564 // of an explicit instantiation declaration, suppress the 17565 // vtable; it will live with the explicit instantiation 17566 // definition. 17567 bool IsExplicitInstantiationDeclaration = 17568 ClassTSK == TSK_ExplicitInstantiationDeclaration; 17569 for (auto R : Class->redecls()) { 17570 TemplateSpecializationKind TSK 17571 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 17572 if (TSK == TSK_ExplicitInstantiationDeclaration) 17573 IsExplicitInstantiationDeclaration = true; 17574 else if (TSK == TSK_ExplicitInstantiationDefinition) { 17575 IsExplicitInstantiationDeclaration = false; 17576 break; 17577 } 17578 } 17579 17580 if (IsExplicitInstantiationDeclaration) 17581 DefineVTable = false; 17582 } 17583 17584 // The exception specifications for all virtual members may be needed even 17585 // if we are not providing an authoritative form of the vtable in this TU. 17586 // We may choose to emit it available_externally anyway. 17587 if (!DefineVTable) { 17588 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 17589 continue; 17590 } 17591 17592 // Mark all of the virtual members of this class as referenced, so 17593 // that we can build a vtable. Then, tell the AST consumer that a 17594 // vtable for this class is required. 17595 DefinedAnything = true; 17596 MarkVirtualMembersReferenced(Loc, Class); 17597 CXXRecordDecl *Canonical = Class->getCanonicalDecl(); 17598 if (VTablesUsed[Canonical]) 17599 Consumer.HandleVTable(Class); 17600 17601 // Warn if we're emitting a weak vtable. The vtable will be weak if there is 17602 // no key function or the key function is inlined. Don't warn in C++ ABIs 17603 // that lack key functions, since the user won't be able to make one. 17604 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() && 17605 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) { 17606 const FunctionDecl *KeyFunctionDef = nullptr; 17607 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) && 17608 KeyFunctionDef->isInlined())) { 17609 Diag(Class->getLocation(), 17610 ClassTSK == TSK_ExplicitInstantiationDefinition 17611 ? diag::warn_weak_template_vtable 17612 : diag::warn_weak_vtable) 17613 << Class; 17614 } 17615 } 17616 } 17617 VTableUses.clear(); 17618 17619 return DefinedAnything; 17620 } 17621 17622 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 17623 const CXXRecordDecl *RD) { 17624 for (const auto *I : RD->methods()) 17625 if (I->isVirtual() && !I->isPure()) 17626 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 17627 } 17628 17629 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 17630 const CXXRecordDecl *RD, 17631 bool ConstexprOnly) { 17632 // Mark all functions which will appear in RD's vtable as used. 17633 CXXFinalOverriderMap FinalOverriders; 17634 RD->getFinalOverriders(FinalOverriders); 17635 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 17636 E = FinalOverriders.end(); 17637 I != E; ++I) { 17638 for (OverridingMethods::const_iterator OI = I->second.begin(), 17639 OE = I->second.end(); 17640 OI != OE; ++OI) { 17641 assert(OI->second.size() > 0 && "no final overrider"); 17642 CXXMethodDecl *Overrider = OI->second.front().Method; 17643 17644 // C++ [basic.def.odr]p2: 17645 // [...] A virtual member function is used if it is not pure. [...] 17646 if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr())) 17647 MarkFunctionReferenced(Loc, Overrider); 17648 } 17649 } 17650 17651 // Only classes that have virtual bases need a VTT. 17652 if (RD->getNumVBases() == 0) 17653 return; 17654 17655 for (const auto &I : RD->bases()) { 17656 const auto *Base = 17657 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 17658 if (Base->getNumVBases() == 0) 17659 continue; 17660 MarkVirtualMembersReferenced(Loc, Base); 17661 } 17662 } 17663 17664 /// SetIvarInitializers - This routine builds initialization ASTs for the 17665 /// Objective-C implementation whose ivars need be initialized. 17666 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 17667 if (!getLangOpts().CPlusPlus) 17668 return; 17669 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 17670 SmallVector<ObjCIvarDecl*, 8> ivars; 17671 CollectIvarsToConstructOrDestruct(OID, ivars); 17672 if (ivars.empty()) 17673 return; 17674 SmallVector<CXXCtorInitializer*, 32> AllToInit; 17675 for (unsigned i = 0; i < ivars.size(); i++) { 17676 FieldDecl *Field = ivars[i]; 17677 if (Field->isInvalidDecl()) 17678 continue; 17679 17680 CXXCtorInitializer *Member; 17681 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 17682 InitializationKind InitKind = 17683 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 17684 17685 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 17686 ExprResult MemberInit = 17687 InitSeq.Perform(*this, InitEntity, InitKind, None); 17688 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 17689 // Note, MemberInit could actually come back empty if no initialization 17690 // is required (e.g., because it would call a trivial default constructor) 17691 if (!MemberInit.get() || MemberInit.isInvalid()) 17692 continue; 17693 17694 Member = 17695 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 17696 SourceLocation(), 17697 MemberInit.getAs<Expr>(), 17698 SourceLocation()); 17699 AllToInit.push_back(Member); 17700 17701 // Be sure that the destructor is accessible and is marked as referenced. 17702 if (const RecordType *RecordTy = 17703 Context.getBaseElementType(Field->getType()) 17704 ->getAs<RecordType>()) { 17705 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 17706 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 17707 MarkFunctionReferenced(Field->getLocation(), Destructor); 17708 CheckDestructorAccess(Field->getLocation(), Destructor, 17709 PDiag(diag::err_access_dtor_ivar) 17710 << Context.getBaseElementType(Field->getType())); 17711 } 17712 } 17713 } 17714 ObjCImplementation->setIvarInitializers(Context, 17715 AllToInit.data(), AllToInit.size()); 17716 } 17717 } 17718 17719 static 17720 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 17721 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid, 17722 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid, 17723 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current, 17724 Sema &S) { 17725 if (Ctor->isInvalidDecl()) 17726 return; 17727 17728 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 17729 17730 // Target may not be determinable yet, for instance if this is a dependent 17731 // call in an uninstantiated template. 17732 if (Target) { 17733 const FunctionDecl *FNTarget = nullptr; 17734 (void)Target->hasBody(FNTarget); 17735 Target = const_cast<CXXConstructorDecl*>( 17736 cast_or_null<CXXConstructorDecl>(FNTarget)); 17737 } 17738 17739 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 17740 // Avoid dereferencing a null pointer here. 17741 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 17742 17743 if (!Current.insert(Canonical).second) 17744 return; 17745 17746 // We know that beyond here, we aren't chaining into a cycle. 17747 if (!Target || !Target->isDelegatingConstructor() || 17748 Target->isInvalidDecl() || Valid.count(TCanonical)) { 17749 Valid.insert(Current.begin(), Current.end()); 17750 Current.clear(); 17751 // We've hit a cycle. 17752 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 17753 Current.count(TCanonical)) { 17754 // If we haven't diagnosed this cycle yet, do so now. 17755 if (!Invalid.count(TCanonical)) { 17756 S.Diag((*Ctor->init_begin())->getSourceLocation(), 17757 diag::warn_delegating_ctor_cycle) 17758 << Ctor; 17759 17760 // Don't add a note for a function delegating directly to itself. 17761 if (TCanonical != Canonical) 17762 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 17763 17764 CXXConstructorDecl *C = Target; 17765 while (C->getCanonicalDecl() != Canonical) { 17766 const FunctionDecl *FNTarget = nullptr; 17767 (void)C->getTargetConstructor()->hasBody(FNTarget); 17768 assert(FNTarget && "Ctor cycle through bodiless function"); 17769 17770 C = const_cast<CXXConstructorDecl*>( 17771 cast<CXXConstructorDecl>(FNTarget)); 17772 S.Diag(C->getLocation(), diag::note_which_delegates_to); 17773 } 17774 } 17775 17776 Invalid.insert(Current.begin(), Current.end()); 17777 Current.clear(); 17778 } else { 17779 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 17780 } 17781 } 17782 17783 17784 void Sema::CheckDelegatingCtorCycles() { 17785 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 17786 17787 for (DelegatingCtorDeclsType::iterator 17788 I = DelegatingCtorDecls.begin(ExternalSource), 17789 E = DelegatingCtorDecls.end(); 17790 I != E; ++I) 17791 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 17792 17793 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI) 17794 (*CI)->setInvalidDecl(); 17795 } 17796 17797 namespace { 17798 /// AST visitor that finds references to the 'this' expression. 17799 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 17800 Sema &S; 17801 17802 public: 17803 explicit FindCXXThisExpr(Sema &S) : S(S) { } 17804 17805 bool VisitCXXThisExpr(CXXThisExpr *E) { 17806 S.Diag(E->getLocation(), diag::err_this_static_member_func) 17807 << E->isImplicit(); 17808 return false; 17809 } 17810 }; 17811 } 17812 17813 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 17814 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 17815 if (!TSInfo) 17816 return false; 17817 17818 TypeLoc TL = TSInfo->getTypeLoc(); 17819 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 17820 if (!ProtoTL) 17821 return false; 17822 17823 // C++11 [expr.prim.general]p3: 17824 // [The expression this] shall not appear before the optional 17825 // cv-qualifier-seq and it shall not appear within the declaration of a 17826 // static member function (although its type and value category are defined 17827 // within a static member function as they are within a non-static member 17828 // function). [ Note: this is because declaration matching does not occur 17829 // until the complete declarator is known. - end note ] 17830 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 17831 FindCXXThisExpr Finder(*this); 17832 17833 // If the return type came after the cv-qualifier-seq, check it now. 17834 if (Proto->hasTrailingReturn() && 17835 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 17836 return true; 17837 17838 // Check the exception specification. 17839 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 17840 return true; 17841 17842 // Check the trailing requires clause 17843 if (Expr *E = Method->getTrailingRequiresClause()) 17844 if (!Finder.TraverseStmt(E)) 17845 return true; 17846 17847 return checkThisInStaticMemberFunctionAttributes(Method); 17848 } 17849 17850 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 17851 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 17852 if (!TSInfo) 17853 return false; 17854 17855 TypeLoc TL = TSInfo->getTypeLoc(); 17856 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 17857 if (!ProtoTL) 17858 return false; 17859 17860 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 17861 FindCXXThisExpr Finder(*this); 17862 17863 switch (Proto->getExceptionSpecType()) { 17864 case EST_Unparsed: 17865 case EST_Uninstantiated: 17866 case EST_Unevaluated: 17867 case EST_BasicNoexcept: 17868 case EST_NoThrow: 17869 case EST_DynamicNone: 17870 case EST_MSAny: 17871 case EST_None: 17872 break; 17873 17874 case EST_DependentNoexcept: 17875 case EST_NoexceptFalse: 17876 case EST_NoexceptTrue: 17877 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 17878 return true; 17879 LLVM_FALLTHROUGH; 17880 17881 case EST_Dynamic: 17882 for (const auto &E : Proto->exceptions()) { 17883 if (!Finder.TraverseType(E)) 17884 return true; 17885 } 17886 break; 17887 } 17888 17889 return false; 17890 } 17891 17892 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 17893 FindCXXThisExpr Finder(*this); 17894 17895 // Check attributes. 17896 for (const auto *A : Method->attrs()) { 17897 // FIXME: This should be emitted by tblgen. 17898 Expr *Arg = nullptr; 17899 ArrayRef<Expr *> Args; 17900 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 17901 Arg = G->getArg(); 17902 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 17903 Arg = G->getArg(); 17904 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 17905 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 17906 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 17907 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 17908 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 17909 Arg = ETLF->getSuccessValue(); 17910 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 17911 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 17912 Arg = STLF->getSuccessValue(); 17913 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 17914 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 17915 Arg = LR->getArg(); 17916 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 17917 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 17918 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 17919 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 17920 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 17921 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 17922 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 17923 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 17924 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 17925 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 17926 17927 if (Arg && !Finder.TraverseStmt(Arg)) 17928 return true; 17929 17930 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 17931 if (!Finder.TraverseStmt(Args[I])) 17932 return true; 17933 } 17934 } 17935 17936 return false; 17937 } 17938 17939 void Sema::checkExceptionSpecification( 17940 bool IsTopLevel, ExceptionSpecificationType EST, 17941 ArrayRef<ParsedType> DynamicExceptions, 17942 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 17943 SmallVectorImpl<QualType> &Exceptions, 17944 FunctionProtoType::ExceptionSpecInfo &ESI) { 17945 Exceptions.clear(); 17946 ESI.Type = EST; 17947 if (EST == EST_Dynamic) { 17948 Exceptions.reserve(DynamicExceptions.size()); 17949 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 17950 // FIXME: Preserve type source info. 17951 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 17952 17953 if (IsTopLevel) { 17954 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 17955 collectUnexpandedParameterPacks(ET, Unexpanded); 17956 if (!Unexpanded.empty()) { 17957 DiagnoseUnexpandedParameterPacks( 17958 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 17959 Unexpanded); 17960 continue; 17961 } 17962 } 17963 17964 // Check that the type is valid for an exception spec, and 17965 // drop it if not. 17966 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 17967 Exceptions.push_back(ET); 17968 } 17969 ESI.Exceptions = Exceptions; 17970 return; 17971 } 17972 17973 if (isComputedNoexcept(EST)) { 17974 assert((NoexceptExpr->isTypeDependent() || 17975 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 17976 Context.BoolTy) && 17977 "Parser should have made sure that the expression is boolean"); 17978 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 17979 ESI.Type = EST_BasicNoexcept; 17980 return; 17981 } 17982 17983 ESI.NoexceptExpr = NoexceptExpr; 17984 return; 17985 } 17986 } 17987 17988 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 17989 ExceptionSpecificationType EST, 17990 SourceRange SpecificationRange, 17991 ArrayRef<ParsedType> DynamicExceptions, 17992 ArrayRef<SourceRange> DynamicExceptionRanges, 17993 Expr *NoexceptExpr) { 17994 if (!MethodD) 17995 return; 17996 17997 // Dig out the method we're referring to. 17998 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 17999 MethodD = FunTmpl->getTemplatedDecl(); 18000 18001 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 18002 if (!Method) 18003 return; 18004 18005 // Check the exception specification. 18006 llvm::SmallVector<QualType, 4> Exceptions; 18007 FunctionProtoType::ExceptionSpecInfo ESI; 18008 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 18009 DynamicExceptionRanges, NoexceptExpr, Exceptions, 18010 ESI); 18011 18012 // Update the exception specification on the function type. 18013 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 18014 18015 if (Method->isStatic()) 18016 checkThisInStaticMemberFunctionExceptionSpec(Method); 18017 18018 if (Method->isVirtual()) { 18019 // Check overrides, which we previously had to delay. 18020 for (const CXXMethodDecl *O : Method->overridden_methods()) 18021 CheckOverridingFunctionExceptionSpec(Method, O); 18022 } 18023 } 18024 18025 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 18026 /// 18027 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 18028 SourceLocation DeclStart, Declarator &D, 18029 Expr *BitWidth, 18030 InClassInitStyle InitStyle, 18031 AccessSpecifier AS, 18032 const ParsedAttr &MSPropertyAttr) { 18033 IdentifierInfo *II = D.getIdentifier(); 18034 if (!II) { 18035 Diag(DeclStart, diag::err_anonymous_property); 18036 return nullptr; 18037 } 18038 SourceLocation Loc = D.getIdentifierLoc(); 18039 18040 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 18041 QualType T = TInfo->getType(); 18042 if (getLangOpts().CPlusPlus) { 18043 CheckExtraCXXDefaultArguments(D); 18044 18045 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 18046 UPPC_DataMemberType)) { 18047 D.setInvalidType(); 18048 T = Context.IntTy; 18049 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 18050 } 18051 } 18052 18053 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 18054 18055 if (D.getDeclSpec().isInlineSpecified()) 18056 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 18057 << getLangOpts().CPlusPlus17; 18058 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 18059 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 18060 diag::err_invalid_thread) 18061 << DeclSpec::getSpecifierName(TSCS); 18062 18063 // Check to see if this name was declared as a member previously 18064 NamedDecl *PrevDecl = nullptr; 18065 LookupResult Previous(*this, II, Loc, LookupMemberName, 18066 ForVisibleRedeclaration); 18067 LookupName(Previous, S); 18068 switch (Previous.getResultKind()) { 18069 case LookupResult::Found: 18070 case LookupResult::FoundUnresolvedValue: 18071 PrevDecl = Previous.getAsSingle<NamedDecl>(); 18072 break; 18073 18074 case LookupResult::FoundOverloaded: 18075 PrevDecl = Previous.getRepresentativeDecl(); 18076 break; 18077 18078 case LookupResult::NotFound: 18079 case LookupResult::NotFoundInCurrentInstantiation: 18080 case LookupResult::Ambiguous: 18081 break; 18082 } 18083 18084 if (PrevDecl && PrevDecl->isTemplateParameter()) { 18085 // Maybe we will complain about the shadowed template parameter. 18086 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 18087 // Just pretend that we didn't see the previous declaration. 18088 PrevDecl = nullptr; 18089 } 18090 18091 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 18092 PrevDecl = nullptr; 18093 18094 SourceLocation TSSL = D.getBeginLoc(); 18095 MSPropertyDecl *NewPD = 18096 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL, 18097 MSPropertyAttr.getPropertyDataGetter(), 18098 MSPropertyAttr.getPropertyDataSetter()); 18099 ProcessDeclAttributes(TUScope, NewPD, D); 18100 NewPD->setAccess(AS); 18101 18102 if (NewPD->isInvalidDecl()) 18103 Record->setInvalidDecl(); 18104 18105 if (D.getDeclSpec().isModulePrivateSpecified()) 18106 NewPD->setModulePrivate(); 18107 18108 if (NewPD->isInvalidDecl() && PrevDecl) { 18109 // Don't introduce NewFD into scope; there's already something 18110 // with the same name in the same scope. 18111 } else if (II) { 18112 PushOnScopeChains(NewPD, S); 18113 } else 18114 Record->addDecl(NewPD); 18115 18116 return NewPD; 18117 } 18118 18119 void Sema::ActOnStartFunctionDeclarationDeclarator( 18120 Declarator &Declarator, unsigned TemplateParameterDepth) { 18121 auto &Info = InventedParameterInfos.emplace_back(); 18122 TemplateParameterList *ExplicitParams = nullptr; 18123 ArrayRef<TemplateParameterList *> ExplicitLists = 18124 Declarator.getTemplateParameterLists(); 18125 if (!ExplicitLists.empty()) { 18126 bool IsMemberSpecialization, IsInvalid; 18127 ExplicitParams = MatchTemplateParametersToScopeSpecifier( 18128 Declarator.getBeginLoc(), Declarator.getIdentifierLoc(), 18129 Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr, 18130 ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid, 18131 /*SuppressDiagnostic=*/true); 18132 } 18133 if (ExplicitParams) { 18134 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth(); 18135 for (NamedDecl *Param : *ExplicitParams) 18136 Info.TemplateParams.push_back(Param); 18137 Info.NumExplicitTemplateParams = ExplicitParams->size(); 18138 } else { 18139 Info.AutoTemplateParameterDepth = TemplateParameterDepth; 18140 Info.NumExplicitTemplateParams = 0; 18141 } 18142 } 18143 18144 void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) { 18145 auto &FSI = InventedParameterInfos.back(); 18146 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) { 18147 if (FSI.NumExplicitTemplateParams != 0) { 18148 TemplateParameterList *ExplicitParams = 18149 Declarator.getTemplateParameterLists().back(); 18150 Declarator.setInventedTemplateParameterList( 18151 TemplateParameterList::Create( 18152 Context, ExplicitParams->getTemplateLoc(), 18153 ExplicitParams->getLAngleLoc(), FSI.TemplateParams, 18154 ExplicitParams->getRAngleLoc(), 18155 ExplicitParams->getRequiresClause())); 18156 } else { 18157 Declarator.setInventedTemplateParameterList( 18158 TemplateParameterList::Create( 18159 Context, SourceLocation(), SourceLocation(), FSI.TemplateParams, 18160 SourceLocation(), /*RequiresClause=*/nullptr)); 18161 } 18162 } 18163 InventedParameterInfos.pop_back(); 18164 } 18165