1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements semantic analysis for C++ declarations. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/AST/ASTConsumer.h" 14 #include "clang/AST/ASTContext.h" 15 #include "clang/AST/ASTLambda.h" 16 #include "clang/AST/ASTMutationListener.h" 17 #include "clang/AST/CXXInheritance.h" 18 #include "clang/AST/CharUnits.h" 19 #include "clang/AST/ComparisonCategories.h" 20 #include "clang/AST/EvaluatedExprVisitor.h" 21 #include "clang/AST/ExprCXX.h" 22 #include "clang/AST/RecordLayout.h" 23 #include "clang/AST/RecursiveASTVisitor.h" 24 #include "clang/AST/StmtVisitor.h" 25 #include "clang/AST/TypeLoc.h" 26 #include "clang/AST/TypeOrdering.h" 27 #include "clang/Basic/AttributeCommonInfo.h" 28 #include "clang/Basic/PartialDiagnostic.h" 29 #include "clang/Basic/TargetInfo.h" 30 #include "clang/Lex/LiteralSupport.h" 31 #include "clang/Lex/Preprocessor.h" 32 #include "clang/Sema/CXXFieldCollector.h" 33 #include "clang/Sema/DeclSpec.h" 34 #include "clang/Sema/Initialization.h" 35 #include "clang/Sema/Lookup.h" 36 #include "clang/Sema/ParsedTemplate.h" 37 #include "clang/Sema/Scope.h" 38 #include "clang/Sema/ScopeInfo.h" 39 #include "clang/Sema/SemaInternal.h" 40 #include "clang/Sema/Template.h" 41 #include "llvm/ADT/ScopeExit.h" 42 #include "llvm/ADT/SmallString.h" 43 #include "llvm/ADT/STLExtras.h" 44 #include "llvm/ADT/StringExtras.h" 45 #include <map> 46 #include <set> 47 48 using namespace clang; 49 50 //===----------------------------------------------------------------------===// 51 // CheckDefaultArgumentVisitor 52 //===----------------------------------------------------------------------===// 53 54 namespace { 55 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 56 /// the default argument of a parameter to determine whether it 57 /// contains any ill-formed subexpressions. For example, this will 58 /// diagnose the use of local variables or parameters within the 59 /// default argument expression. 60 class CheckDefaultArgumentVisitor 61 : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> { 62 Sema &S; 63 const Expr *DefaultArg; 64 65 public: 66 CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg) 67 : S(S), DefaultArg(DefaultArg) {} 68 69 bool VisitExpr(const Expr *Node); 70 bool VisitDeclRefExpr(const DeclRefExpr *DRE); 71 bool VisitCXXThisExpr(const CXXThisExpr *ThisE); 72 bool VisitLambdaExpr(const LambdaExpr *Lambda); 73 bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE); 74 }; 75 76 /// VisitExpr - Visit all of the children of this expression. 77 bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) { 78 bool IsInvalid = false; 79 for (const Stmt *SubStmt : Node->children()) 80 IsInvalid |= Visit(SubStmt); 81 return IsInvalid; 82 } 83 84 /// VisitDeclRefExpr - Visit a reference to a declaration, to 85 /// determine whether this declaration can be used in the default 86 /// argument expression. 87 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) { 88 const NamedDecl *Decl = DRE->getDecl(); 89 if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) { 90 // C++ [dcl.fct.default]p9: 91 // [...] parameters of a function shall not be used in default 92 // argument expressions, even if they are not evaluated. [...] 93 // 94 // C++17 [dcl.fct.default]p9 (by CWG 2082): 95 // [...] A parameter shall not appear as a potentially-evaluated 96 // expression in a default argument. [...] 97 // 98 if (DRE->isNonOdrUse() != NOUR_Unevaluated) 99 return S.Diag(DRE->getBeginLoc(), 100 diag::err_param_default_argument_references_param) 101 << Param->getDeclName() << DefaultArg->getSourceRange(); 102 } else if (const auto *VDecl = dyn_cast<VarDecl>(Decl)) { 103 // C++ [dcl.fct.default]p7: 104 // Local variables shall not be used in default argument 105 // expressions. 106 // 107 // C++17 [dcl.fct.default]p7 (by CWG 2082): 108 // A local variable shall not appear as a potentially-evaluated 109 // expression in a default argument. 110 // 111 // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346): 112 // Note: A local variable cannot be odr-used (6.3) in a default argument. 113 // 114 if (VDecl->isLocalVarDecl() && !DRE->isNonOdrUse()) 115 return S.Diag(DRE->getBeginLoc(), 116 diag::err_param_default_argument_references_local) 117 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 118 } 119 120 return false; 121 } 122 123 /// VisitCXXThisExpr - Visit a C++ "this" expression. 124 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) { 125 // C++ [dcl.fct.default]p8: 126 // The keyword this shall not be used in a default argument of a 127 // member function. 128 return S.Diag(ThisE->getBeginLoc(), 129 diag::err_param_default_argument_references_this) 130 << ThisE->getSourceRange(); 131 } 132 133 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr( 134 const PseudoObjectExpr *POE) { 135 bool Invalid = false; 136 for (const Expr *E : POE->semantics()) { 137 // Look through bindings. 138 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) { 139 E = OVE->getSourceExpr(); 140 assert(E && "pseudo-object binding without source expression?"); 141 } 142 143 Invalid |= Visit(E); 144 } 145 return Invalid; 146 } 147 148 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) { 149 // C++11 [expr.lambda.prim]p13: 150 // A lambda-expression appearing in a default argument shall not 151 // implicitly or explicitly capture any entity. 152 if (Lambda->capture_begin() == Lambda->capture_end()) 153 return false; 154 155 return S.Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg); 156 } 157 } // namespace 158 159 void 160 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc, 161 const CXXMethodDecl *Method) { 162 // If we have an MSAny spec already, don't bother. 163 if (!Method || ComputedEST == EST_MSAny) 164 return; 165 166 const FunctionProtoType *Proto 167 = Method->getType()->getAs<FunctionProtoType>(); 168 Proto = Self->ResolveExceptionSpec(CallLoc, Proto); 169 if (!Proto) 170 return; 171 172 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 173 174 // If we have a throw-all spec at this point, ignore the function. 175 if (ComputedEST == EST_None) 176 return; 177 178 if (EST == EST_None && Method->hasAttr<NoThrowAttr>()) 179 EST = EST_BasicNoexcept; 180 181 switch (EST) { 182 case EST_Unparsed: 183 case EST_Uninstantiated: 184 case EST_Unevaluated: 185 llvm_unreachable("should not see unresolved exception specs here"); 186 187 // If this function can throw any exceptions, make a note of that. 188 case EST_MSAny: 189 case EST_None: 190 // FIXME: Whichever we see last of MSAny and None determines our result. 191 // We should make a consistent, order-independent choice here. 192 ClearExceptions(); 193 ComputedEST = EST; 194 return; 195 case EST_NoexceptFalse: 196 ClearExceptions(); 197 ComputedEST = EST_None; 198 return; 199 // FIXME: If the call to this decl is using any of its default arguments, we 200 // need to search them for potentially-throwing calls. 201 // If this function has a basic noexcept, it doesn't affect the outcome. 202 case EST_BasicNoexcept: 203 case EST_NoexceptTrue: 204 case EST_NoThrow: 205 return; 206 // If we're still at noexcept(true) and there's a throw() callee, 207 // change to that specification. 208 case EST_DynamicNone: 209 if (ComputedEST == EST_BasicNoexcept) 210 ComputedEST = EST_DynamicNone; 211 return; 212 case EST_DependentNoexcept: 213 llvm_unreachable( 214 "should not generate implicit declarations for dependent cases"); 215 case EST_Dynamic: 216 break; 217 } 218 assert(EST == EST_Dynamic && "EST case not considered earlier."); 219 assert(ComputedEST != EST_None && 220 "Shouldn't collect exceptions when throw-all is guaranteed."); 221 ComputedEST = EST_Dynamic; 222 // Record the exceptions in this function's exception specification. 223 for (const auto &E : Proto->exceptions()) 224 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second) 225 Exceptions.push_back(E); 226 } 227 228 void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) { 229 if (!S || ComputedEST == EST_MSAny) 230 return; 231 232 // FIXME: 233 // 234 // C++0x [except.spec]p14: 235 // [An] implicit exception-specification specifies the type-id T if and 236 // only if T is allowed by the exception-specification of a function directly 237 // invoked by f's implicit definition; f shall allow all exceptions if any 238 // function it directly invokes allows all exceptions, and f shall allow no 239 // exceptions if every function it directly invokes allows no exceptions. 240 // 241 // Note in particular that if an implicit exception-specification is generated 242 // for a function containing a throw-expression, that specification can still 243 // be noexcept(true). 244 // 245 // Note also that 'directly invoked' is not defined in the standard, and there 246 // is no indication that we should only consider potentially-evaluated calls. 247 // 248 // Ultimately we should implement the intent of the standard: the exception 249 // specification should be the set of exceptions which can be thrown by the 250 // implicit definition. For now, we assume that any non-nothrow expression can 251 // throw any exception. 252 253 if (Self->canThrow(S)) 254 ComputedEST = EST_None; 255 } 256 257 ExprResult Sema::ConvertParamDefaultArgument(const ParmVarDecl *Param, 258 Expr *Arg, 259 SourceLocation EqualLoc) { 260 if (RequireCompleteType(Param->getLocation(), Param->getType(), 261 diag::err_typecheck_decl_incomplete_type)) 262 return true; 263 264 // C++ [dcl.fct.default]p5 265 // A default argument expression is implicitly converted (clause 266 // 4) to the parameter type. The default argument expression has 267 // the same semantic constraints as the initializer expression in 268 // a declaration of a variable of the parameter type, using the 269 // copy-initialization semantics (8.5). 270 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 271 Param); 272 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 273 EqualLoc); 274 InitializationSequence InitSeq(*this, Entity, Kind, Arg); 275 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); 276 if (Result.isInvalid()) 277 return true; 278 Arg = Result.getAs<Expr>(); 279 280 CheckCompletedExpr(Arg, EqualLoc); 281 Arg = MaybeCreateExprWithCleanups(Arg); 282 283 return Arg; 284 } 285 286 void Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 287 SourceLocation EqualLoc) { 288 // Add the default argument to the parameter 289 Param->setDefaultArg(Arg); 290 291 // We have already instantiated this parameter; provide each of the 292 // instantiations with the uninstantiated default argument. 293 UnparsedDefaultArgInstantiationsMap::iterator InstPos 294 = UnparsedDefaultArgInstantiations.find(Param); 295 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 296 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 297 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 298 299 // We're done tracking this parameter's instantiations. 300 UnparsedDefaultArgInstantiations.erase(InstPos); 301 } 302 } 303 304 /// ActOnParamDefaultArgument - Check whether the default argument 305 /// provided for a function parameter is well-formed. If so, attach it 306 /// to the parameter declaration. 307 void 308 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 309 Expr *DefaultArg) { 310 if (!param || !DefaultArg) 311 return; 312 313 ParmVarDecl *Param = cast<ParmVarDecl>(param); 314 UnparsedDefaultArgLocs.erase(Param); 315 316 auto Fail = [&] { 317 Param->setInvalidDecl(); 318 Param->setDefaultArg(new (Context) OpaqueValueExpr( 319 EqualLoc, Param->getType().getNonReferenceType(), VK_RValue)); 320 }; 321 322 // Default arguments are only permitted in C++ 323 if (!getLangOpts().CPlusPlus) { 324 Diag(EqualLoc, diag::err_param_default_argument) 325 << DefaultArg->getSourceRange(); 326 return Fail(); 327 } 328 329 // Check for unexpanded parameter packs. 330 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 331 return Fail(); 332 } 333 334 // C++11 [dcl.fct.default]p3 335 // A default argument expression [...] shall not be specified for a 336 // parameter pack. 337 if (Param->isParameterPack()) { 338 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack) 339 << DefaultArg->getSourceRange(); 340 // Recover by discarding the default argument. 341 Param->setDefaultArg(nullptr); 342 return; 343 } 344 345 ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc); 346 if (Result.isInvalid()) 347 return Fail(); 348 349 DefaultArg = Result.getAs<Expr>(); 350 351 // Check that the default argument is well-formed 352 CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg); 353 if (DefaultArgChecker.Visit(DefaultArg)) 354 return Fail(); 355 356 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 357 } 358 359 /// ActOnParamUnparsedDefaultArgument - We've seen a default 360 /// argument for a function parameter, but we can't parse it yet 361 /// because we're inside a class definition. Note that this default 362 /// argument will be parsed later. 363 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 364 SourceLocation EqualLoc, 365 SourceLocation ArgLoc) { 366 if (!param) 367 return; 368 369 ParmVarDecl *Param = cast<ParmVarDecl>(param); 370 Param->setUnparsedDefaultArg(); 371 UnparsedDefaultArgLocs[Param] = ArgLoc; 372 } 373 374 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 375 /// the default argument for the parameter param failed. 376 void Sema::ActOnParamDefaultArgumentError(Decl *param, 377 SourceLocation EqualLoc) { 378 if (!param) 379 return; 380 381 ParmVarDecl *Param = cast<ParmVarDecl>(param); 382 Param->setInvalidDecl(); 383 UnparsedDefaultArgLocs.erase(Param); 384 Param->setDefaultArg(new(Context) 385 OpaqueValueExpr(EqualLoc, 386 Param->getType().getNonReferenceType(), 387 VK_RValue)); 388 } 389 390 /// CheckExtraCXXDefaultArguments - Check for any extra default 391 /// arguments in the declarator, which is not a function declaration 392 /// or definition and therefore is not permitted to have default 393 /// arguments. This routine should be invoked for every declarator 394 /// that is not a function declaration or definition. 395 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 396 // C++ [dcl.fct.default]p3 397 // A default argument expression shall be specified only in the 398 // parameter-declaration-clause of a function declaration or in a 399 // template-parameter (14.1). It shall not be specified for a 400 // parameter pack. If it is specified in a 401 // parameter-declaration-clause, it shall not occur within a 402 // declarator or abstract-declarator of a parameter-declaration. 403 bool MightBeFunction = D.isFunctionDeclarationContext(); 404 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 405 DeclaratorChunk &chunk = D.getTypeObject(i); 406 if (chunk.Kind == DeclaratorChunk::Function) { 407 if (MightBeFunction) { 408 // This is a function declaration. It can have default arguments, but 409 // keep looking in case its return type is a function type with default 410 // arguments. 411 MightBeFunction = false; 412 continue; 413 } 414 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e; 415 ++argIdx) { 416 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param); 417 if (Param->hasUnparsedDefaultArg()) { 418 std::unique_ptr<CachedTokens> Toks = 419 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens); 420 SourceRange SR; 421 if (Toks->size() > 1) 422 SR = SourceRange((*Toks)[1].getLocation(), 423 Toks->back().getLocation()); 424 else 425 SR = UnparsedDefaultArgLocs[Param]; 426 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 427 << SR; 428 } else if (Param->getDefaultArg()) { 429 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 430 << Param->getDefaultArg()->getSourceRange(); 431 Param->setDefaultArg(nullptr); 432 } 433 } 434 } else if (chunk.Kind != DeclaratorChunk::Paren) { 435 MightBeFunction = false; 436 } 437 } 438 } 439 440 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { 441 return std::any_of(FD->param_begin(), FD->param_end(), [](ParmVarDecl *P) { 442 return P->hasDefaultArg() && !P->hasInheritedDefaultArg(); 443 }); 444 } 445 446 /// MergeCXXFunctionDecl - Merge two declarations of the same C++ 447 /// function, once we already know that they have the same 448 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an 449 /// error, false otherwise. 450 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 451 Scope *S) { 452 bool Invalid = false; 453 454 // The declaration context corresponding to the scope is the semantic 455 // parent, unless this is a local function declaration, in which case 456 // it is that surrounding function. 457 DeclContext *ScopeDC = New->isLocalExternDecl() 458 ? New->getLexicalDeclContext() 459 : New->getDeclContext(); 460 461 // Find the previous declaration for the purpose of default arguments. 462 FunctionDecl *PrevForDefaultArgs = Old; 463 for (/**/; PrevForDefaultArgs; 464 // Don't bother looking back past the latest decl if this is a local 465 // extern declaration; nothing else could work. 466 PrevForDefaultArgs = New->isLocalExternDecl() 467 ? nullptr 468 : PrevForDefaultArgs->getPreviousDecl()) { 469 // Ignore hidden declarations. 470 if (!LookupResult::isVisible(*this, PrevForDefaultArgs)) 471 continue; 472 473 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) && 474 !New->isCXXClassMember()) { 475 // Ignore default arguments of old decl if they are not in 476 // the same scope and this is not an out-of-line definition of 477 // a member function. 478 continue; 479 } 480 481 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) { 482 // If only one of these is a local function declaration, then they are 483 // declared in different scopes, even though isDeclInScope may think 484 // they're in the same scope. (If both are local, the scope check is 485 // sufficient, and if neither is local, then they are in the same scope.) 486 continue; 487 } 488 489 // We found the right previous declaration. 490 break; 491 } 492 493 // C++ [dcl.fct.default]p4: 494 // For non-template functions, default arguments can be added in 495 // later declarations of a function in the same 496 // scope. Declarations in different scopes have completely 497 // distinct sets of default arguments. That is, declarations in 498 // inner scopes do not acquire default arguments from 499 // declarations in outer scopes, and vice versa. In a given 500 // function declaration, all parameters subsequent to a 501 // parameter with a default argument shall have default 502 // arguments supplied in this or previous declarations. A 503 // default argument shall not be redefined by a later 504 // declaration (not even to the same value). 505 // 506 // C++ [dcl.fct.default]p6: 507 // Except for member functions of class templates, the default arguments 508 // in a member function definition that appears outside of the class 509 // definition are added to the set of default arguments provided by the 510 // member function declaration in the class definition. 511 for (unsigned p = 0, NumParams = PrevForDefaultArgs 512 ? PrevForDefaultArgs->getNumParams() 513 : 0; 514 p < NumParams; ++p) { 515 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p); 516 ParmVarDecl *NewParam = New->getParamDecl(p); 517 518 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false; 519 bool NewParamHasDfl = NewParam->hasDefaultArg(); 520 521 if (OldParamHasDfl && NewParamHasDfl) { 522 unsigned DiagDefaultParamID = 523 diag::err_param_default_argument_redefinition; 524 525 // MSVC accepts that default parameters be redefined for member functions 526 // of template class. The new default parameter's value is ignored. 527 Invalid = true; 528 if (getLangOpts().MicrosoftExt) { 529 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New); 530 if (MD && MD->getParent()->getDescribedClassTemplate()) { 531 // Merge the old default argument into the new parameter. 532 NewParam->setHasInheritedDefaultArg(); 533 if (OldParam->hasUninstantiatedDefaultArg()) 534 NewParam->setUninstantiatedDefaultArg( 535 OldParam->getUninstantiatedDefaultArg()); 536 else 537 NewParam->setDefaultArg(OldParam->getInit()); 538 DiagDefaultParamID = diag::ext_param_default_argument_redefinition; 539 Invalid = false; 540 } 541 } 542 543 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 544 // hint here. Alternatively, we could walk the type-source information 545 // for NewParam to find the last source location in the type... but it 546 // isn't worth the effort right now. This is the kind of test case that 547 // is hard to get right: 548 // int f(int); 549 // void g(int (*fp)(int) = f); 550 // void g(int (*fp)(int) = &f); 551 Diag(NewParam->getLocation(), DiagDefaultParamID) 552 << NewParam->getDefaultArgRange(); 553 554 // Look for the function declaration where the default argument was 555 // actually written, which may be a declaration prior to Old. 556 for (auto Older = PrevForDefaultArgs; 557 OldParam->hasInheritedDefaultArg(); /**/) { 558 Older = Older->getPreviousDecl(); 559 OldParam = Older->getParamDecl(p); 560 } 561 562 Diag(OldParam->getLocation(), diag::note_previous_definition) 563 << OldParam->getDefaultArgRange(); 564 } else if (OldParamHasDfl) { 565 // Merge the old default argument into the new parameter unless the new 566 // function is a friend declaration in a template class. In the latter 567 // case the default arguments will be inherited when the friend 568 // declaration will be instantiated. 569 if (New->getFriendObjectKind() == Decl::FOK_None || 570 !New->getLexicalDeclContext()->isDependentContext()) { 571 // It's important to use getInit() here; getDefaultArg() 572 // strips off any top-level ExprWithCleanups. 573 NewParam->setHasInheritedDefaultArg(); 574 if (OldParam->hasUnparsedDefaultArg()) 575 NewParam->setUnparsedDefaultArg(); 576 else if (OldParam->hasUninstantiatedDefaultArg()) 577 NewParam->setUninstantiatedDefaultArg( 578 OldParam->getUninstantiatedDefaultArg()); 579 else 580 NewParam->setDefaultArg(OldParam->getInit()); 581 } 582 } else if (NewParamHasDfl) { 583 if (New->getDescribedFunctionTemplate()) { 584 // Paragraph 4, quoted above, only applies to non-template functions. 585 Diag(NewParam->getLocation(), 586 diag::err_param_default_argument_template_redecl) 587 << NewParam->getDefaultArgRange(); 588 Diag(PrevForDefaultArgs->getLocation(), 589 diag::note_template_prev_declaration) 590 << false; 591 } else if (New->getTemplateSpecializationKind() 592 != TSK_ImplicitInstantiation && 593 New->getTemplateSpecializationKind() != TSK_Undeclared) { 594 // C++ [temp.expr.spec]p21: 595 // Default function arguments shall not be specified in a declaration 596 // or a definition for one of the following explicit specializations: 597 // - the explicit specialization of a function template; 598 // - the explicit specialization of a member function template; 599 // - the explicit specialization of a member function of a class 600 // template where the class template specialization to which the 601 // member function specialization belongs is implicitly 602 // instantiated. 603 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 604 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 605 << New->getDeclName() 606 << NewParam->getDefaultArgRange(); 607 } else if (New->getDeclContext()->isDependentContext()) { 608 // C++ [dcl.fct.default]p6 (DR217): 609 // Default arguments for a member function of a class template shall 610 // be specified on the initial declaration of the member function 611 // within the class template. 612 // 613 // Reading the tea leaves a bit in DR217 and its reference to DR205 614 // leads me to the conclusion that one cannot add default function 615 // arguments for an out-of-line definition of a member function of a 616 // dependent type. 617 int WhichKind = 2; 618 if (CXXRecordDecl *Record 619 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 620 if (Record->getDescribedClassTemplate()) 621 WhichKind = 0; 622 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 623 WhichKind = 1; 624 else 625 WhichKind = 2; 626 } 627 628 Diag(NewParam->getLocation(), 629 diag::err_param_default_argument_member_template_redecl) 630 << WhichKind 631 << NewParam->getDefaultArgRange(); 632 } 633 } 634 } 635 636 // DR1344: If a default argument is added outside a class definition and that 637 // default argument makes the function a special member function, the program 638 // is ill-formed. This can only happen for constructors. 639 if (isa<CXXConstructorDecl>(New) && 640 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 641 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 642 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 643 if (NewSM != OldSM) { 644 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 645 assert(NewParam->hasDefaultArg()); 646 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 647 << NewParam->getDefaultArgRange() << NewSM; 648 Diag(Old->getLocation(), diag::note_previous_declaration); 649 } 650 } 651 652 const FunctionDecl *Def; 653 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 654 // template has a constexpr specifier then all its declarations shall 655 // contain the constexpr specifier. 656 if (New->getConstexprKind() != Old->getConstexprKind()) { 657 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 658 << New << New->getConstexprKind() << Old->getConstexprKind(); 659 Diag(Old->getLocation(), diag::note_previous_declaration); 660 Invalid = true; 661 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() && 662 Old->isDefined(Def) && 663 // If a friend function is inlined but does not have 'inline' 664 // specifier, it is a definition. Do not report attribute conflict 665 // in this case, redefinition will be diagnosed later. 666 (New->isInlineSpecified() || 667 New->getFriendObjectKind() == Decl::FOK_None)) { 668 // C++11 [dcl.fcn.spec]p4: 669 // If the definition of a function appears in a translation unit before its 670 // first declaration as inline, the program is ill-formed. 671 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 672 Diag(Def->getLocation(), diag::note_previous_definition); 673 Invalid = true; 674 } 675 676 // C++17 [temp.deduct.guide]p3: 677 // Two deduction guide declarations in the same translation unit 678 // for the same class template shall not have equivalent 679 // parameter-declaration-clauses. 680 if (isa<CXXDeductionGuideDecl>(New) && 681 !New->isFunctionTemplateSpecialization() && isVisible(Old)) { 682 Diag(New->getLocation(), diag::err_deduction_guide_redeclared); 683 Diag(Old->getLocation(), diag::note_previous_declaration); 684 } 685 686 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 687 // argument expression, that declaration shall be a definition and shall be 688 // the only declaration of the function or function template in the 689 // translation unit. 690 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 691 functionDeclHasDefaultArgument(Old)) { 692 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 693 Diag(Old->getLocation(), diag::note_previous_declaration); 694 Invalid = true; 695 } 696 697 return Invalid; 698 } 699 700 NamedDecl * 701 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D, 702 MultiTemplateParamsArg TemplateParamLists) { 703 assert(D.isDecompositionDeclarator()); 704 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 705 706 // The syntax only allows a decomposition declarator as a simple-declaration, 707 // a for-range-declaration, or a condition in Clang, but we parse it in more 708 // cases than that. 709 if (!D.mayHaveDecompositionDeclarator()) { 710 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 711 << Decomp.getSourceRange(); 712 return nullptr; 713 } 714 715 if (!TemplateParamLists.empty()) { 716 // FIXME: There's no rule against this, but there are also no rules that 717 // would actually make it usable, so we reject it for now. 718 Diag(TemplateParamLists.front()->getTemplateLoc(), 719 diag::err_decomp_decl_template); 720 return nullptr; 721 } 722 723 Diag(Decomp.getLSquareLoc(), 724 !getLangOpts().CPlusPlus17 725 ? diag::ext_decomp_decl 726 : D.getContext() == DeclaratorContext::ConditionContext 727 ? diag::ext_decomp_decl_cond 728 : diag::warn_cxx14_compat_decomp_decl) 729 << Decomp.getSourceRange(); 730 731 // The semantic context is always just the current context. 732 DeclContext *const DC = CurContext; 733 734 // C++17 [dcl.dcl]/8: 735 // The decl-specifier-seq shall contain only the type-specifier auto 736 // and cv-qualifiers. 737 // C++2a [dcl.dcl]/8: 738 // If decl-specifier-seq contains any decl-specifier other than static, 739 // thread_local, auto, or cv-qualifiers, the program is ill-formed. 740 auto &DS = D.getDeclSpec(); 741 { 742 SmallVector<StringRef, 8> BadSpecifiers; 743 SmallVector<SourceLocation, 8> BadSpecifierLocs; 744 SmallVector<StringRef, 8> CPlusPlus20Specifiers; 745 SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs; 746 if (auto SCS = DS.getStorageClassSpec()) { 747 if (SCS == DeclSpec::SCS_static) { 748 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS)); 749 CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 750 } else { 751 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS)); 752 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 753 } 754 } 755 if (auto TSCS = DS.getThreadStorageClassSpec()) { 756 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS)); 757 CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc()); 758 } 759 if (DS.hasConstexprSpecifier()) { 760 BadSpecifiers.push_back( 761 DeclSpec::getSpecifierName(DS.getConstexprSpecifier())); 762 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc()); 763 } 764 if (DS.isInlineSpecified()) { 765 BadSpecifiers.push_back("inline"); 766 BadSpecifierLocs.push_back(DS.getInlineSpecLoc()); 767 } 768 if (!BadSpecifiers.empty()) { 769 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec); 770 Err << (int)BadSpecifiers.size() 771 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " "); 772 // Don't add FixItHints to remove the specifiers; we do still respect 773 // them when building the underlying variable. 774 for (auto Loc : BadSpecifierLocs) 775 Err << SourceRange(Loc, Loc); 776 } else if (!CPlusPlus20Specifiers.empty()) { 777 auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(), 778 getLangOpts().CPlusPlus20 779 ? diag::warn_cxx17_compat_decomp_decl_spec 780 : diag::ext_decomp_decl_spec); 781 Warn << (int)CPlusPlus20Specifiers.size() 782 << llvm::join(CPlusPlus20Specifiers.begin(), 783 CPlusPlus20Specifiers.end(), " "); 784 for (auto Loc : CPlusPlus20SpecifierLocs) 785 Warn << SourceRange(Loc, Loc); 786 } 787 // We can't recover from it being declared as a typedef. 788 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 789 return nullptr; 790 } 791 792 // C++2a [dcl.struct.bind]p1: 793 // A cv that includes volatile is deprecated 794 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) && 795 getLangOpts().CPlusPlus20) 796 Diag(DS.getVolatileSpecLoc(), 797 diag::warn_deprecated_volatile_structured_binding); 798 799 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 800 QualType R = TInfo->getType(); 801 802 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 803 UPPC_DeclarationType)) 804 D.setInvalidType(); 805 806 // The syntax only allows a single ref-qualifier prior to the decomposition 807 // declarator. No other declarator chunks are permitted. Also check the type 808 // specifier here. 809 if (DS.getTypeSpecType() != DeclSpec::TST_auto || 810 D.hasGroupingParens() || D.getNumTypeObjects() > 1 || 811 (D.getNumTypeObjects() == 1 && 812 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) { 813 Diag(Decomp.getLSquareLoc(), 814 (D.hasGroupingParens() || 815 (D.getNumTypeObjects() && 816 D.getTypeObject(0).Kind == DeclaratorChunk::Paren)) 817 ? diag::err_decomp_decl_parens 818 : diag::err_decomp_decl_type) 819 << R; 820 821 // In most cases, there's no actual problem with an explicitly-specified 822 // type, but a function type won't work here, and ActOnVariableDeclarator 823 // shouldn't be called for such a type. 824 if (R->isFunctionType()) 825 D.setInvalidType(); 826 } 827 828 // Build the BindingDecls. 829 SmallVector<BindingDecl*, 8> Bindings; 830 831 // Build the BindingDecls. 832 for (auto &B : D.getDecompositionDeclarator().bindings()) { 833 // Check for name conflicts. 834 DeclarationNameInfo NameInfo(B.Name, B.NameLoc); 835 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 836 ForVisibleRedeclaration); 837 LookupName(Previous, S, 838 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit()); 839 840 // It's not permitted to shadow a template parameter name. 841 if (Previous.isSingleResult() && 842 Previous.getFoundDecl()->isTemplateParameter()) { 843 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 844 Previous.getFoundDecl()); 845 Previous.clear(); 846 } 847 848 bool ConsiderLinkage = DC->isFunctionOrMethod() && 849 DS.getStorageClassSpec() == DeclSpec::SCS_extern; 850 FilterLookupForScope(Previous, DC, S, ConsiderLinkage, 851 /*AllowInlineNamespace*/false); 852 if (!Previous.empty()) { 853 auto *Old = Previous.getRepresentativeDecl(); 854 Diag(B.NameLoc, diag::err_redefinition) << B.Name; 855 Diag(Old->getLocation(), diag::note_previous_definition); 856 } 857 858 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name); 859 PushOnScopeChains(BD, S, true); 860 Bindings.push_back(BD); 861 ParsingInitForAutoVars.insert(BD); 862 } 863 864 // There are no prior lookup results for the variable itself, because it 865 // is unnamed. 866 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr, 867 Decomp.getLSquareLoc()); 868 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 869 ForVisibleRedeclaration); 870 871 // Build the variable that holds the non-decomposed object. 872 bool AddToScope = true; 873 NamedDecl *New = 874 ActOnVariableDeclarator(S, D, DC, TInfo, Previous, 875 MultiTemplateParamsArg(), AddToScope, Bindings); 876 if (AddToScope) { 877 S->AddDecl(New); 878 CurContext->addHiddenDecl(New); 879 } 880 881 if (isInOpenMPDeclareTargetContext()) 882 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 883 884 return New; 885 } 886 887 static bool checkSimpleDecomposition( 888 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src, 889 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType, 890 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) { 891 if ((int64_t)Bindings.size() != NumElems) { 892 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 893 << DecompType << (unsigned)Bindings.size() << NumElems.toString(10) 894 << (NumElems < Bindings.size()); 895 return true; 896 } 897 898 unsigned I = 0; 899 for (auto *B : Bindings) { 900 SourceLocation Loc = B->getLocation(); 901 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 902 if (E.isInvalid()) 903 return true; 904 E = GetInit(Loc, E.get(), I++); 905 if (E.isInvalid()) 906 return true; 907 B->setBinding(ElemType, E.get()); 908 } 909 910 return false; 911 } 912 913 static bool checkArrayLikeDecomposition(Sema &S, 914 ArrayRef<BindingDecl *> Bindings, 915 ValueDecl *Src, QualType DecompType, 916 const llvm::APSInt &NumElems, 917 QualType ElemType) { 918 return checkSimpleDecomposition( 919 S, Bindings, Src, DecompType, NumElems, ElemType, 920 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 921 ExprResult E = S.ActOnIntegerConstant(Loc, I); 922 if (E.isInvalid()) 923 return ExprError(); 924 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc); 925 }); 926 } 927 928 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 929 ValueDecl *Src, QualType DecompType, 930 const ConstantArrayType *CAT) { 931 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType, 932 llvm::APSInt(CAT->getSize()), 933 CAT->getElementType()); 934 } 935 936 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 937 ValueDecl *Src, QualType DecompType, 938 const VectorType *VT) { 939 return checkArrayLikeDecomposition( 940 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()), 941 S.Context.getQualifiedType(VT->getElementType(), 942 DecompType.getQualifiers())); 943 } 944 945 static bool checkComplexDecomposition(Sema &S, 946 ArrayRef<BindingDecl *> Bindings, 947 ValueDecl *Src, QualType DecompType, 948 const ComplexType *CT) { 949 return checkSimpleDecomposition( 950 S, Bindings, Src, DecompType, llvm::APSInt::get(2), 951 S.Context.getQualifiedType(CT->getElementType(), 952 DecompType.getQualifiers()), 953 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 954 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base); 955 }); 956 } 957 958 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy, 959 TemplateArgumentListInfo &Args) { 960 SmallString<128> SS; 961 llvm::raw_svector_ostream OS(SS); 962 bool First = true; 963 for (auto &Arg : Args.arguments()) { 964 if (!First) 965 OS << ", "; 966 Arg.getArgument().print(PrintingPolicy, OS); 967 First = false; 968 } 969 return std::string(OS.str()); 970 } 971 972 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup, 973 SourceLocation Loc, StringRef Trait, 974 TemplateArgumentListInfo &Args, 975 unsigned DiagID) { 976 auto DiagnoseMissing = [&] { 977 if (DiagID) 978 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(), 979 Args); 980 return true; 981 }; 982 983 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine. 984 NamespaceDecl *Std = S.getStdNamespace(); 985 if (!Std) 986 return DiagnoseMissing(); 987 988 // Look up the trait itself, within namespace std. We can diagnose various 989 // problems with this lookup even if we've been asked to not diagnose a 990 // missing specialization, because this can only fail if the user has been 991 // declaring their own names in namespace std or we don't support the 992 // standard library implementation in use. 993 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait), 994 Loc, Sema::LookupOrdinaryName); 995 if (!S.LookupQualifiedName(Result, Std)) 996 return DiagnoseMissing(); 997 if (Result.isAmbiguous()) 998 return true; 999 1000 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>(); 1001 if (!TraitTD) { 1002 Result.suppressDiagnostics(); 1003 NamedDecl *Found = *Result.begin(); 1004 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait; 1005 S.Diag(Found->getLocation(), diag::note_declared_at); 1006 return true; 1007 } 1008 1009 // Build the template-id. 1010 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args); 1011 if (TraitTy.isNull()) 1012 return true; 1013 if (!S.isCompleteType(Loc, TraitTy)) { 1014 if (DiagID) 1015 S.RequireCompleteType( 1016 Loc, TraitTy, DiagID, 1017 printTemplateArgs(S.Context.getPrintingPolicy(), Args)); 1018 return true; 1019 } 1020 1021 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl(); 1022 assert(RD && "specialization of class template is not a class?"); 1023 1024 // Look up the member of the trait type. 1025 S.LookupQualifiedName(TraitMemberLookup, RD); 1026 return TraitMemberLookup.isAmbiguous(); 1027 } 1028 1029 static TemplateArgumentLoc 1030 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, 1031 uint64_t I) { 1032 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T); 1033 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc); 1034 } 1035 1036 static TemplateArgumentLoc 1037 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) { 1038 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc); 1039 } 1040 1041 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; } 1042 1043 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, 1044 llvm::APSInt &Size) { 1045 EnterExpressionEvaluationContext ContextRAII( 1046 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 1047 1048 DeclarationName Value = S.PP.getIdentifierInfo("value"); 1049 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName); 1050 1051 // Form template argument list for tuple_size<T>. 1052 TemplateArgumentListInfo Args(Loc, Loc); 1053 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1054 1055 // If there's no tuple_size specialization or the lookup of 'value' is empty, 1056 // it's not tuple-like. 1057 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) || 1058 R.empty()) 1059 return IsTupleLike::NotTupleLike; 1060 1061 // If we get this far, we've committed to the tuple interpretation, but 1062 // we can still fail if there actually isn't a usable ::value. 1063 1064 struct ICEDiagnoser : Sema::VerifyICEDiagnoser { 1065 LookupResult &R; 1066 TemplateArgumentListInfo &Args; 1067 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args) 1068 : R(R), Args(Args) {} 1069 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { 1070 S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant) 1071 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1072 } 1073 } Diagnoser(R, Args); 1074 1075 ExprResult E = 1076 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false); 1077 if (E.isInvalid()) 1078 return IsTupleLike::Error; 1079 1080 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false); 1081 if (E.isInvalid()) 1082 return IsTupleLike::Error; 1083 1084 return IsTupleLike::TupleLike; 1085 } 1086 1087 /// \return std::tuple_element<I, T>::type. 1088 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, 1089 unsigned I, QualType T) { 1090 // Form template argument list for tuple_element<I, T>. 1091 TemplateArgumentListInfo Args(Loc, Loc); 1092 Args.addArgument( 1093 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1094 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1095 1096 DeclarationName TypeDN = S.PP.getIdentifierInfo("type"); 1097 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName); 1098 if (lookupStdTypeTraitMember( 1099 S, R, Loc, "tuple_element", Args, 1100 diag::err_decomp_decl_std_tuple_element_not_specialized)) 1101 return QualType(); 1102 1103 auto *TD = R.getAsSingle<TypeDecl>(); 1104 if (!TD) { 1105 R.suppressDiagnostics(); 1106 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized) 1107 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1108 if (!R.empty()) 1109 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at); 1110 return QualType(); 1111 } 1112 1113 return S.Context.getTypeDeclType(TD); 1114 } 1115 1116 namespace { 1117 struct InitializingBinding { 1118 Sema &S; 1119 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) { 1120 Sema::CodeSynthesisContext Ctx; 1121 Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding; 1122 Ctx.PointOfInstantiation = BD->getLocation(); 1123 Ctx.Entity = BD; 1124 S.pushCodeSynthesisContext(Ctx); 1125 } 1126 ~InitializingBinding() { 1127 S.popCodeSynthesisContext(); 1128 } 1129 }; 1130 } 1131 1132 static bool checkTupleLikeDecomposition(Sema &S, 1133 ArrayRef<BindingDecl *> Bindings, 1134 VarDecl *Src, QualType DecompType, 1135 const llvm::APSInt &TupleSize) { 1136 if ((int64_t)Bindings.size() != TupleSize) { 1137 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1138 << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10) 1139 << (TupleSize < Bindings.size()); 1140 return true; 1141 } 1142 1143 if (Bindings.empty()) 1144 return false; 1145 1146 DeclarationName GetDN = S.PP.getIdentifierInfo("get"); 1147 1148 // [dcl.decomp]p3: 1149 // The unqualified-id get is looked up in the scope of E by class member 1150 // access lookup ... 1151 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName); 1152 bool UseMemberGet = false; 1153 if (S.isCompleteType(Src->getLocation(), DecompType)) { 1154 if (auto *RD = DecompType->getAsCXXRecordDecl()) 1155 S.LookupQualifiedName(MemberGet, RD); 1156 if (MemberGet.isAmbiguous()) 1157 return true; 1158 // ... and if that finds at least one declaration that is a function 1159 // template whose first template parameter is a non-type parameter ... 1160 for (NamedDecl *D : MemberGet) { 1161 if (FunctionTemplateDecl *FTD = 1162 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) { 1163 TemplateParameterList *TPL = FTD->getTemplateParameters(); 1164 if (TPL->size() != 0 && 1165 isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) { 1166 // ... the initializer is e.get<i>(). 1167 UseMemberGet = true; 1168 break; 1169 } 1170 } 1171 } 1172 } 1173 1174 unsigned I = 0; 1175 for (auto *B : Bindings) { 1176 InitializingBinding InitContext(S, B); 1177 SourceLocation Loc = B->getLocation(); 1178 1179 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1180 if (E.isInvalid()) 1181 return true; 1182 1183 // e is an lvalue if the type of the entity is an lvalue reference and 1184 // an xvalue otherwise 1185 if (!Src->getType()->isLValueReferenceType()) 1186 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp, 1187 E.get(), nullptr, VK_XValue); 1188 1189 TemplateArgumentListInfo Args(Loc, Loc); 1190 Args.addArgument( 1191 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1192 1193 if (UseMemberGet) { 1194 // if [lookup of member get] finds at least one declaration, the 1195 // initializer is e.get<i-1>(). 1196 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false, 1197 CXXScopeSpec(), SourceLocation(), nullptr, 1198 MemberGet, &Args, nullptr); 1199 if (E.isInvalid()) 1200 return true; 1201 1202 E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc); 1203 } else { 1204 // Otherwise, the initializer is get<i-1>(e), where get is looked up 1205 // in the associated namespaces. 1206 Expr *Get = UnresolvedLookupExpr::Create( 1207 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(), 1208 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args, 1209 UnresolvedSetIterator(), UnresolvedSetIterator()); 1210 1211 Expr *Arg = E.get(); 1212 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc); 1213 } 1214 if (E.isInvalid()) 1215 return true; 1216 Expr *Init = E.get(); 1217 1218 // Given the type T designated by std::tuple_element<i - 1, E>::type, 1219 QualType T = getTupleLikeElementType(S, Loc, I, DecompType); 1220 if (T.isNull()) 1221 return true; 1222 1223 // each vi is a variable of type "reference to T" initialized with the 1224 // initializer, where the reference is an lvalue reference if the 1225 // initializer is an lvalue and an rvalue reference otherwise 1226 QualType RefType = 1227 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName()); 1228 if (RefType.isNull()) 1229 return true; 1230 auto *RefVD = VarDecl::Create( 1231 S.Context, Src->getDeclContext(), Loc, Loc, 1232 B->getDeclName().getAsIdentifierInfo(), RefType, 1233 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass()); 1234 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext()); 1235 RefVD->setTSCSpec(Src->getTSCSpec()); 1236 RefVD->setImplicit(); 1237 if (Src->isInlineSpecified()) 1238 RefVD->setInlineSpecified(); 1239 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD); 1240 1241 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD); 1242 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc); 1243 InitializationSequence Seq(S, Entity, Kind, Init); 1244 E = Seq.Perform(S, Entity, Kind, Init); 1245 if (E.isInvalid()) 1246 return true; 1247 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false); 1248 if (E.isInvalid()) 1249 return true; 1250 RefVD->setInit(E.get()); 1251 if (!E.get()->isValueDependent()) 1252 RefVD->checkInitIsICE(); 1253 1254 E = S.BuildDeclarationNameExpr(CXXScopeSpec(), 1255 DeclarationNameInfo(B->getDeclName(), Loc), 1256 RefVD); 1257 if (E.isInvalid()) 1258 return true; 1259 1260 B->setBinding(T, E.get()); 1261 I++; 1262 } 1263 1264 return false; 1265 } 1266 1267 /// Find the base class to decompose in a built-in decomposition of a class type. 1268 /// This base class search is, unfortunately, not quite like any other that we 1269 /// perform anywhere else in C++. 1270 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc, 1271 const CXXRecordDecl *RD, 1272 CXXCastPath &BasePath) { 1273 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier, 1274 CXXBasePath &Path) { 1275 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields(); 1276 }; 1277 1278 const CXXRecordDecl *ClassWithFields = nullptr; 1279 AccessSpecifier AS = AS_public; 1280 if (RD->hasDirectFields()) 1281 // [dcl.decomp]p4: 1282 // Otherwise, all of E's non-static data members shall be public direct 1283 // members of E ... 1284 ClassWithFields = RD; 1285 else { 1286 // ... or of ... 1287 CXXBasePaths Paths; 1288 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD)); 1289 if (!RD->lookupInBases(BaseHasFields, Paths)) { 1290 // If no classes have fields, just decompose RD itself. (This will work 1291 // if and only if zero bindings were provided.) 1292 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public); 1293 } 1294 1295 CXXBasePath *BestPath = nullptr; 1296 for (auto &P : Paths) { 1297 if (!BestPath) 1298 BestPath = &P; 1299 else if (!S.Context.hasSameType(P.back().Base->getType(), 1300 BestPath->back().Base->getType())) { 1301 // ... the same ... 1302 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1303 << false << RD << BestPath->back().Base->getType() 1304 << P.back().Base->getType(); 1305 return DeclAccessPair(); 1306 } else if (P.Access < BestPath->Access) { 1307 BestPath = &P; 1308 } 1309 } 1310 1311 // ... unambiguous ... 1312 QualType BaseType = BestPath->back().Base->getType(); 1313 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) { 1314 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base) 1315 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths); 1316 return DeclAccessPair(); 1317 } 1318 1319 // ... [accessible, implied by other rules] base class of E. 1320 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD), 1321 *BestPath, diag::err_decomp_decl_inaccessible_base); 1322 AS = BestPath->Access; 1323 1324 ClassWithFields = BaseType->getAsCXXRecordDecl(); 1325 S.BuildBasePathArray(Paths, BasePath); 1326 } 1327 1328 // The above search did not check whether the selected class itself has base 1329 // classes with fields, so check that now. 1330 CXXBasePaths Paths; 1331 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) { 1332 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1333 << (ClassWithFields == RD) << RD << ClassWithFields 1334 << Paths.front().back().Base->getType(); 1335 return DeclAccessPair(); 1336 } 1337 1338 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS); 1339 } 1340 1341 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 1342 ValueDecl *Src, QualType DecompType, 1343 const CXXRecordDecl *OrigRD) { 1344 if (S.RequireCompleteType(Src->getLocation(), DecompType, 1345 diag::err_incomplete_type)) 1346 return true; 1347 1348 CXXCastPath BasePath; 1349 DeclAccessPair BasePair = 1350 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath); 1351 const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl()); 1352 if (!RD) 1353 return true; 1354 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD), 1355 DecompType.getQualifiers()); 1356 1357 auto DiagnoseBadNumberOfBindings = [&]() -> bool { 1358 unsigned NumFields = 1359 std::count_if(RD->field_begin(), RD->field_end(), 1360 [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); }); 1361 assert(Bindings.size() != NumFields); 1362 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1363 << DecompType << (unsigned)Bindings.size() << NumFields 1364 << (NumFields < Bindings.size()); 1365 return true; 1366 }; 1367 1368 // all of E's non-static data members shall be [...] well-formed 1369 // when named as e.name in the context of the structured binding, 1370 // E shall not have an anonymous union member, ... 1371 unsigned I = 0; 1372 for (auto *FD : RD->fields()) { 1373 if (FD->isUnnamedBitfield()) 1374 continue; 1375 1376 if (FD->isAnonymousStructOrUnion()) { 1377 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member) 1378 << DecompType << FD->getType()->isUnionType(); 1379 S.Diag(FD->getLocation(), diag::note_declared_at); 1380 return true; 1381 } 1382 1383 // We have a real field to bind. 1384 if (I >= Bindings.size()) 1385 return DiagnoseBadNumberOfBindings(); 1386 auto *B = Bindings[I++]; 1387 SourceLocation Loc = B->getLocation(); 1388 1389 // The field must be accessible in the context of the structured binding. 1390 // We already checked that the base class is accessible. 1391 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the 1392 // const_cast here. 1393 S.CheckStructuredBindingMemberAccess( 1394 Loc, const_cast<CXXRecordDecl *>(OrigRD), 1395 DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess( 1396 BasePair.getAccess(), FD->getAccess()))); 1397 1398 // Initialize the binding to Src.FD. 1399 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1400 if (E.isInvalid()) 1401 return true; 1402 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase, 1403 VK_LValue, &BasePath); 1404 if (E.isInvalid()) 1405 return true; 1406 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc, 1407 CXXScopeSpec(), FD, 1408 DeclAccessPair::make(FD, FD->getAccess()), 1409 DeclarationNameInfo(FD->getDeclName(), Loc)); 1410 if (E.isInvalid()) 1411 return true; 1412 1413 // If the type of the member is T, the referenced type is cv T, where cv is 1414 // the cv-qualification of the decomposition expression. 1415 // 1416 // FIXME: We resolve a defect here: if the field is mutable, we do not add 1417 // 'const' to the type of the field. 1418 Qualifiers Q = DecompType.getQualifiers(); 1419 if (FD->isMutable()) 1420 Q.removeConst(); 1421 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get()); 1422 } 1423 1424 if (I != Bindings.size()) 1425 return DiagnoseBadNumberOfBindings(); 1426 1427 return false; 1428 } 1429 1430 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) { 1431 QualType DecompType = DD->getType(); 1432 1433 // If the type of the decomposition is dependent, then so is the type of 1434 // each binding. 1435 if (DecompType->isDependentType()) { 1436 for (auto *B : DD->bindings()) 1437 B->setType(Context.DependentTy); 1438 return; 1439 } 1440 1441 DecompType = DecompType.getNonReferenceType(); 1442 ArrayRef<BindingDecl*> Bindings = DD->bindings(); 1443 1444 // C++1z [dcl.decomp]/2: 1445 // If E is an array type [...] 1446 // As an extension, we also support decomposition of built-in complex and 1447 // vector types. 1448 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) { 1449 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT)) 1450 DD->setInvalidDecl(); 1451 return; 1452 } 1453 if (auto *VT = DecompType->getAs<VectorType>()) { 1454 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT)) 1455 DD->setInvalidDecl(); 1456 return; 1457 } 1458 if (auto *CT = DecompType->getAs<ComplexType>()) { 1459 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT)) 1460 DD->setInvalidDecl(); 1461 return; 1462 } 1463 1464 // C++1z [dcl.decomp]/3: 1465 // if the expression std::tuple_size<E>::value is a well-formed integral 1466 // constant expression, [...] 1467 llvm::APSInt TupleSize(32); 1468 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) { 1469 case IsTupleLike::Error: 1470 DD->setInvalidDecl(); 1471 return; 1472 1473 case IsTupleLike::TupleLike: 1474 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize)) 1475 DD->setInvalidDecl(); 1476 return; 1477 1478 case IsTupleLike::NotTupleLike: 1479 break; 1480 } 1481 1482 // C++1z [dcl.dcl]/8: 1483 // [E shall be of array or non-union class type] 1484 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl(); 1485 if (!RD || RD->isUnion()) { 1486 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type) 1487 << DD << !RD << DecompType; 1488 DD->setInvalidDecl(); 1489 return; 1490 } 1491 1492 // C++1z [dcl.decomp]/4: 1493 // all of E's non-static data members shall be [...] direct members of 1494 // E or of the same unambiguous public base class of E, ... 1495 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD)) 1496 DD->setInvalidDecl(); 1497 } 1498 1499 /// Merge the exception specifications of two variable declarations. 1500 /// 1501 /// This is called when there's a redeclaration of a VarDecl. The function 1502 /// checks if the redeclaration might have an exception specification and 1503 /// validates compatibility and merges the specs if necessary. 1504 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 1505 // Shortcut if exceptions are disabled. 1506 if (!getLangOpts().CXXExceptions) 1507 return; 1508 1509 assert(Context.hasSameType(New->getType(), Old->getType()) && 1510 "Should only be called if types are otherwise the same."); 1511 1512 QualType NewType = New->getType(); 1513 QualType OldType = Old->getType(); 1514 1515 // We're only interested in pointers and references to functions, as well 1516 // as pointers to member functions. 1517 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 1518 NewType = R->getPointeeType(); 1519 OldType = OldType->castAs<ReferenceType>()->getPointeeType(); 1520 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 1521 NewType = P->getPointeeType(); 1522 OldType = OldType->castAs<PointerType>()->getPointeeType(); 1523 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 1524 NewType = M->getPointeeType(); 1525 OldType = OldType->castAs<MemberPointerType>()->getPointeeType(); 1526 } 1527 1528 if (!NewType->isFunctionProtoType()) 1529 return; 1530 1531 // There's lots of special cases for functions. For function pointers, system 1532 // libraries are hopefully not as broken so that we don't need these 1533 // workarounds. 1534 if (CheckEquivalentExceptionSpec( 1535 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 1536 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 1537 New->setInvalidDecl(); 1538 } 1539 } 1540 1541 /// CheckCXXDefaultArguments - Verify that the default arguments for a 1542 /// function declaration are well-formed according to C++ 1543 /// [dcl.fct.default]. 1544 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 1545 unsigned NumParams = FD->getNumParams(); 1546 unsigned ParamIdx = 0; 1547 1548 // This checking doesn't make sense for explicit specializations; their 1549 // default arguments are determined by the declaration we're specializing, 1550 // not by FD. 1551 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 1552 return; 1553 if (auto *FTD = FD->getDescribedFunctionTemplate()) 1554 if (FTD->isMemberSpecialization()) 1555 return; 1556 1557 // Find first parameter with a default argument 1558 for (; ParamIdx < NumParams; ++ParamIdx) { 1559 ParmVarDecl *Param = FD->getParamDecl(ParamIdx); 1560 if (Param->hasDefaultArg()) 1561 break; 1562 } 1563 1564 // C++20 [dcl.fct.default]p4: 1565 // In a given function declaration, each parameter subsequent to a parameter 1566 // with a default argument shall have a default argument supplied in this or 1567 // a previous declaration, unless the parameter was expanded from a 1568 // parameter pack, or shall be a function parameter pack. 1569 for (; ParamIdx < NumParams; ++ParamIdx) { 1570 ParmVarDecl *Param = FD->getParamDecl(ParamIdx); 1571 if (!Param->hasDefaultArg() && !Param->isParameterPack() && 1572 !(CurrentInstantiationScope && 1573 CurrentInstantiationScope->isLocalPackExpansion(Param))) { 1574 if (Param->isInvalidDecl()) 1575 /* We already complained about this parameter. */; 1576 else if (Param->getIdentifier()) 1577 Diag(Param->getLocation(), 1578 diag::err_param_default_argument_missing_name) 1579 << Param->getIdentifier(); 1580 else 1581 Diag(Param->getLocation(), 1582 diag::err_param_default_argument_missing); 1583 } 1584 } 1585 } 1586 1587 /// Check that the given type is a literal type. Issue a diagnostic if not, 1588 /// if Kind is Diagnose. 1589 /// \return \c true if a problem has been found (and optionally diagnosed). 1590 template <typename... Ts> 1591 static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind, 1592 SourceLocation Loc, QualType T, unsigned DiagID, 1593 Ts &&...DiagArgs) { 1594 if (T->isDependentType()) 1595 return false; 1596 1597 switch (Kind) { 1598 case Sema::CheckConstexprKind::Diagnose: 1599 return SemaRef.RequireLiteralType(Loc, T, DiagID, 1600 std::forward<Ts>(DiagArgs)...); 1601 1602 case Sema::CheckConstexprKind::CheckValid: 1603 return !T->isLiteralType(SemaRef.Context); 1604 } 1605 1606 llvm_unreachable("unknown CheckConstexprKind"); 1607 } 1608 1609 /// Determine whether a destructor cannot be constexpr due to 1610 static bool CheckConstexprDestructorSubobjects(Sema &SemaRef, 1611 const CXXDestructorDecl *DD, 1612 Sema::CheckConstexprKind Kind) { 1613 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) { 1614 const CXXRecordDecl *RD = 1615 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 1616 if (!RD || RD->hasConstexprDestructor()) 1617 return true; 1618 1619 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1620 SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject) 1621 << DD->getConstexprKind() << !FD 1622 << (FD ? FD->getDeclName() : DeclarationName()) << T; 1623 SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject) 1624 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T; 1625 } 1626 return false; 1627 }; 1628 1629 const CXXRecordDecl *RD = DD->getParent(); 1630 for (const CXXBaseSpecifier &B : RD->bases()) 1631 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr)) 1632 return false; 1633 for (const FieldDecl *FD : RD->fields()) 1634 if (!Check(FD->getLocation(), FD->getType(), FD)) 1635 return false; 1636 return true; 1637 } 1638 1639 /// Check whether a function's parameter types are all literal types. If so, 1640 /// return true. If not, produce a suitable diagnostic and return false. 1641 static bool CheckConstexprParameterTypes(Sema &SemaRef, 1642 const FunctionDecl *FD, 1643 Sema::CheckConstexprKind Kind) { 1644 unsigned ArgIndex = 0; 1645 const auto *FT = FD->getType()->castAs<FunctionProtoType>(); 1646 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 1647 e = FT->param_type_end(); 1648 i != e; ++i, ++ArgIndex) { 1649 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 1650 SourceLocation ParamLoc = PD->getLocation(); 1651 if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i, 1652 diag::err_constexpr_non_literal_param, ArgIndex + 1, 1653 PD->getSourceRange(), isa<CXXConstructorDecl>(FD), 1654 FD->isConsteval())) 1655 return false; 1656 } 1657 return true; 1658 } 1659 1660 /// Check whether a function's return type is a literal type. If so, return 1661 /// true. If not, produce a suitable diagnostic and return false. 1662 static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD, 1663 Sema::CheckConstexprKind Kind) { 1664 if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(), 1665 diag::err_constexpr_non_literal_return, 1666 FD->isConsteval())) 1667 return false; 1668 return true; 1669 } 1670 1671 /// Get diagnostic %select index for tag kind for 1672 /// record diagnostic message. 1673 /// WARNING: Indexes apply to particular diagnostics only! 1674 /// 1675 /// \returns diagnostic %select index. 1676 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 1677 switch (Tag) { 1678 case TTK_Struct: return 0; 1679 case TTK_Interface: return 1; 1680 case TTK_Class: return 2; 1681 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 1682 } 1683 } 1684 1685 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, 1686 Stmt *Body, 1687 Sema::CheckConstexprKind Kind); 1688 1689 // Check whether a function declaration satisfies the requirements of a 1690 // constexpr function definition or a constexpr constructor definition. If so, 1691 // return true. If not, produce appropriate diagnostics (unless asked not to by 1692 // Kind) and return false. 1693 // 1694 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 1695 bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD, 1696 CheckConstexprKind Kind) { 1697 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 1698 if (MD && MD->isInstance()) { 1699 // C++11 [dcl.constexpr]p4: 1700 // The definition of a constexpr constructor shall satisfy the following 1701 // constraints: 1702 // - the class shall not have any virtual base classes; 1703 // 1704 // FIXME: This only applies to constructors and destructors, not arbitrary 1705 // member functions. 1706 const CXXRecordDecl *RD = MD->getParent(); 1707 if (RD->getNumVBases()) { 1708 if (Kind == CheckConstexprKind::CheckValid) 1709 return false; 1710 1711 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 1712 << isa<CXXConstructorDecl>(NewFD) 1713 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 1714 for (const auto &I : RD->vbases()) 1715 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here) 1716 << I.getSourceRange(); 1717 return false; 1718 } 1719 } 1720 1721 if (!isa<CXXConstructorDecl>(NewFD)) { 1722 // C++11 [dcl.constexpr]p3: 1723 // The definition of a constexpr function shall satisfy the following 1724 // constraints: 1725 // - it shall not be virtual; (removed in C++20) 1726 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 1727 if (Method && Method->isVirtual()) { 1728 if (getLangOpts().CPlusPlus20) { 1729 if (Kind == CheckConstexprKind::Diagnose) 1730 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual); 1731 } else { 1732 if (Kind == CheckConstexprKind::CheckValid) 1733 return false; 1734 1735 Method = Method->getCanonicalDecl(); 1736 Diag(Method->getLocation(), diag::err_constexpr_virtual); 1737 1738 // If it's not obvious why this function is virtual, find an overridden 1739 // function which uses the 'virtual' keyword. 1740 const CXXMethodDecl *WrittenVirtual = Method; 1741 while (!WrittenVirtual->isVirtualAsWritten()) 1742 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 1743 if (WrittenVirtual != Method) 1744 Diag(WrittenVirtual->getLocation(), 1745 diag::note_overridden_virtual_function); 1746 return false; 1747 } 1748 } 1749 1750 // - its return type shall be a literal type; 1751 if (!CheckConstexprReturnType(*this, NewFD, Kind)) 1752 return false; 1753 } 1754 1755 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) { 1756 // A destructor can be constexpr only if the defaulted destructor could be; 1757 // we don't need to check the members and bases if we already know they all 1758 // have constexpr destructors. 1759 if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) { 1760 if (Kind == CheckConstexprKind::CheckValid) 1761 return false; 1762 if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind)) 1763 return false; 1764 } 1765 } 1766 1767 // - each of its parameter types shall be a literal type; 1768 if (!CheckConstexprParameterTypes(*this, NewFD, Kind)) 1769 return false; 1770 1771 Stmt *Body = NewFD->getBody(); 1772 assert(Body && 1773 "CheckConstexprFunctionDefinition called on function with no body"); 1774 return CheckConstexprFunctionBody(*this, NewFD, Body, Kind); 1775 } 1776 1777 /// Check the given declaration statement is legal within a constexpr function 1778 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 1779 /// 1780 /// \return true if the body is OK (maybe only as an extension), false if we 1781 /// have diagnosed a problem. 1782 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 1783 DeclStmt *DS, SourceLocation &Cxx1yLoc, 1784 Sema::CheckConstexprKind Kind) { 1785 // C++11 [dcl.constexpr]p3 and p4: 1786 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 1787 // contain only 1788 for (const auto *DclIt : DS->decls()) { 1789 switch (DclIt->getKind()) { 1790 case Decl::StaticAssert: 1791 case Decl::Using: 1792 case Decl::UsingShadow: 1793 case Decl::UsingDirective: 1794 case Decl::UnresolvedUsingTypename: 1795 case Decl::UnresolvedUsingValue: 1796 // - static_assert-declarations 1797 // - using-declarations, 1798 // - using-directives, 1799 continue; 1800 1801 case Decl::Typedef: 1802 case Decl::TypeAlias: { 1803 // - typedef declarations and alias-declarations that do not define 1804 // classes or enumerations, 1805 const auto *TN = cast<TypedefNameDecl>(DclIt); 1806 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 1807 // Don't allow variably-modified types in constexpr functions. 1808 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1809 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 1810 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 1811 << TL.getSourceRange() << TL.getType() 1812 << isa<CXXConstructorDecl>(Dcl); 1813 } 1814 return false; 1815 } 1816 continue; 1817 } 1818 1819 case Decl::Enum: 1820 case Decl::CXXRecord: 1821 // C++1y allows types to be defined, not just declared. 1822 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) { 1823 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1824 SemaRef.Diag(DS->getBeginLoc(), 1825 SemaRef.getLangOpts().CPlusPlus14 1826 ? diag::warn_cxx11_compat_constexpr_type_definition 1827 : diag::ext_constexpr_type_definition) 1828 << isa<CXXConstructorDecl>(Dcl); 1829 } else if (!SemaRef.getLangOpts().CPlusPlus14) { 1830 return false; 1831 } 1832 } 1833 continue; 1834 1835 case Decl::EnumConstant: 1836 case Decl::IndirectField: 1837 case Decl::ParmVar: 1838 // These can only appear with other declarations which are banned in 1839 // C++11 and permitted in C++1y, so ignore them. 1840 continue; 1841 1842 case Decl::Var: 1843 case Decl::Decomposition: { 1844 // C++1y [dcl.constexpr]p3 allows anything except: 1845 // a definition of a variable of non-literal type or of static or 1846 // thread storage duration or [before C++2a] for which no 1847 // initialization is performed. 1848 const auto *VD = cast<VarDecl>(DclIt); 1849 if (VD->isThisDeclarationADefinition()) { 1850 if (VD->isStaticLocal()) { 1851 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1852 SemaRef.Diag(VD->getLocation(), 1853 diag::err_constexpr_local_var_static) 1854 << isa<CXXConstructorDecl>(Dcl) 1855 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 1856 } 1857 return false; 1858 } 1859 if (CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(), 1860 diag::err_constexpr_local_var_non_literal_type, 1861 isa<CXXConstructorDecl>(Dcl))) 1862 return false; 1863 if (!VD->getType()->isDependentType() && 1864 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 1865 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1866 SemaRef.Diag( 1867 VD->getLocation(), 1868 SemaRef.getLangOpts().CPlusPlus20 1869 ? diag::warn_cxx17_compat_constexpr_local_var_no_init 1870 : diag::ext_constexpr_local_var_no_init) 1871 << isa<CXXConstructorDecl>(Dcl); 1872 } else if (!SemaRef.getLangOpts().CPlusPlus20) { 1873 return false; 1874 } 1875 continue; 1876 } 1877 } 1878 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1879 SemaRef.Diag(VD->getLocation(), 1880 SemaRef.getLangOpts().CPlusPlus14 1881 ? diag::warn_cxx11_compat_constexpr_local_var 1882 : diag::ext_constexpr_local_var) 1883 << isa<CXXConstructorDecl>(Dcl); 1884 } else if (!SemaRef.getLangOpts().CPlusPlus14) { 1885 return false; 1886 } 1887 continue; 1888 } 1889 1890 case Decl::NamespaceAlias: 1891 case Decl::Function: 1892 // These are disallowed in C++11 and permitted in C++1y. Allow them 1893 // everywhere as an extension. 1894 if (!Cxx1yLoc.isValid()) 1895 Cxx1yLoc = DS->getBeginLoc(); 1896 continue; 1897 1898 default: 1899 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1900 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 1901 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 1902 } 1903 return false; 1904 } 1905 } 1906 1907 return true; 1908 } 1909 1910 /// Check that the given field is initialized within a constexpr constructor. 1911 /// 1912 /// \param Dcl The constexpr constructor being checked. 1913 /// \param Field The field being checked. This may be a member of an anonymous 1914 /// struct or union nested within the class being checked. 1915 /// \param Inits All declarations, including anonymous struct/union members and 1916 /// indirect members, for which any initialization was provided. 1917 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach 1918 /// multiple notes for different members to the same error. 1919 /// \param Kind Whether we're diagnosing a constructor as written or determining 1920 /// whether the formal requirements are satisfied. 1921 /// \return \c false if we're checking for validity and the constructor does 1922 /// not satisfy the requirements on a constexpr constructor. 1923 static bool CheckConstexprCtorInitializer(Sema &SemaRef, 1924 const FunctionDecl *Dcl, 1925 FieldDecl *Field, 1926 llvm::SmallSet<Decl*, 16> &Inits, 1927 bool &Diagnosed, 1928 Sema::CheckConstexprKind Kind) { 1929 // In C++20 onwards, there's nothing to check for validity. 1930 if (Kind == Sema::CheckConstexprKind::CheckValid && 1931 SemaRef.getLangOpts().CPlusPlus20) 1932 return true; 1933 1934 if (Field->isInvalidDecl()) 1935 return true; 1936 1937 if (Field->isUnnamedBitfield()) 1938 return true; 1939 1940 // Anonymous unions with no variant members and empty anonymous structs do not 1941 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 1942 // indirect fields don't need initializing. 1943 if (Field->isAnonymousStructOrUnion() && 1944 (Field->getType()->isUnionType() 1945 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 1946 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 1947 return true; 1948 1949 if (!Inits.count(Field)) { 1950 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1951 if (!Diagnosed) { 1952 SemaRef.Diag(Dcl->getLocation(), 1953 SemaRef.getLangOpts().CPlusPlus20 1954 ? diag::warn_cxx17_compat_constexpr_ctor_missing_init 1955 : diag::ext_constexpr_ctor_missing_init); 1956 Diagnosed = true; 1957 } 1958 SemaRef.Diag(Field->getLocation(), 1959 diag::note_constexpr_ctor_missing_init); 1960 } else if (!SemaRef.getLangOpts().CPlusPlus20) { 1961 return false; 1962 } 1963 } else if (Field->isAnonymousStructOrUnion()) { 1964 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 1965 for (auto *I : RD->fields()) 1966 // If an anonymous union contains an anonymous struct of which any member 1967 // is initialized, all members must be initialized. 1968 if (!RD->isUnion() || Inits.count(I)) 1969 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, 1970 Kind)) 1971 return false; 1972 } 1973 return true; 1974 } 1975 1976 /// Check the provided statement is allowed in a constexpr function 1977 /// definition. 1978 static bool 1979 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 1980 SmallVectorImpl<SourceLocation> &ReturnStmts, 1981 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc, 1982 Sema::CheckConstexprKind Kind) { 1983 // - its function-body shall be [...] a compound-statement that contains only 1984 switch (S->getStmtClass()) { 1985 case Stmt::NullStmtClass: 1986 // - null statements, 1987 return true; 1988 1989 case Stmt::DeclStmtClass: 1990 // - static_assert-declarations 1991 // - using-declarations, 1992 // - using-directives, 1993 // - typedef declarations and alias-declarations that do not define 1994 // classes or enumerations, 1995 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind)) 1996 return false; 1997 return true; 1998 1999 case Stmt::ReturnStmtClass: 2000 // - and exactly one return statement; 2001 if (isa<CXXConstructorDecl>(Dcl)) { 2002 // C++1y allows return statements in constexpr constructors. 2003 if (!Cxx1yLoc.isValid()) 2004 Cxx1yLoc = S->getBeginLoc(); 2005 return true; 2006 } 2007 2008 ReturnStmts.push_back(S->getBeginLoc()); 2009 return true; 2010 2011 case Stmt::CompoundStmtClass: { 2012 // C++1y allows compound-statements. 2013 if (!Cxx1yLoc.isValid()) 2014 Cxx1yLoc = S->getBeginLoc(); 2015 2016 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 2017 for (auto *BodyIt : CompStmt->body()) { 2018 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 2019 Cxx1yLoc, Cxx2aLoc, Kind)) 2020 return false; 2021 } 2022 return true; 2023 } 2024 2025 case Stmt::AttributedStmtClass: 2026 if (!Cxx1yLoc.isValid()) 2027 Cxx1yLoc = S->getBeginLoc(); 2028 return true; 2029 2030 case Stmt::IfStmtClass: { 2031 // C++1y allows if-statements. 2032 if (!Cxx1yLoc.isValid()) 2033 Cxx1yLoc = S->getBeginLoc(); 2034 2035 IfStmt *If = cast<IfStmt>(S); 2036 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 2037 Cxx1yLoc, Cxx2aLoc, Kind)) 2038 return false; 2039 if (If->getElse() && 2040 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 2041 Cxx1yLoc, Cxx2aLoc, Kind)) 2042 return false; 2043 return true; 2044 } 2045 2046 case Stmt::WhileStmtClass: 2047 case Stmt::DoStmtClass: 2048 case Stmt::ForStmtClass: 2049 case Stmt::CXXForRangeStmtClass: 2050 case Stmt::ContinueStmtClass: 2051 // C++1y allows all of these. We don't allow them as extensions in C++11, 2052 // because they don't make sense without variable mutation. 2053 if (!SemaRef.getLangOpts().CPlusPlus14) 2054 break; 2055 if (!Cxx1yLoc.isValid()) 2056 Cxx1yLoc = S->getBeginLoc(); 2057 for (Stmt *SubStmt : S->children()) 2058 if (SubStmt && 2059 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2060 Cxx1yLoc, Cxx2aLoc, Kind)) 2061 return false; 2062 return true; 2063 2064 case Stmt::SwitchStmtClass: 2065 case Stmt::CaseStmtClass: 2066 case Stmt::DefaultStmtClass: 2067 case Stmt::BreakStmtClass: 2068 // C++1y allows switch-statements, and since they don't need variable 2069 // mutation, we can reasonably allow them in C++11 as an extension. 2070 if (!Cxx1yLoc.isValid()) 2071 Cxx1yLoc = S->getBeginLoc(); 2072 for (Stmt *SubStmt : S->children()) 2073 if (SubStmt && 2074 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2075 Cxx1yLoc, Cxx2aLoc, Kind)) 2076 return false; 2077 return true; 2078 2079 case Stmt::GCCAsmStmtClass: 2080 case Stmt::MSAsmStmtClass: 2081 // C++2a allows inline assembly statements. 2082 case Stmt::CXXTryStmtClass: 2083 if (Cxx2aLoc.isInvalid()) 2084 Cxx2aLoc = S->getBeginLoc(); 2085 for (Stmt *SubStmt : S->children()) { 2086 if (SubStmt && 2087 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2088 Cxx1yLoc, Cxx2aLoc, Kind)) 2089 return false; 2090 } 2091 return true; 2092 2093 case Stmt::CXXCatchStmtClass: 2094 // Do not bother checking the language mode (already covered by the 2095 // try block check). 2096 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, 2097 cast<CXXCatchStmt>(S)->getHandlerBlock(), 2098 ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind)) 2099 return false; 2100 return true; 2101 2102 default: 2103 if (!isa<Expr>(S)) 2104 break; 2105 2106 // C++1y allows expression-statements. 2107 if (!Cxx1yLoc.isValid()) 2108 Cxx1yLoc = S->getBeginLoc(); 2109 return true; 2110 } 2111 2112 if (Kind == Sema::CheckConstexprKind::Diagnose) { 2113 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 2114 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 2115 } 2116 return false; 2117 } 2118 2119 /// Check the body for the given constexpr function declaration only contains 2120 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 2121 /// 2122 /// \return true if the body is OK, false if we have found or diagnosed a 2123 /// problem. 2124 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, 2125 Stmt *Body, 2126 Sema::CheckConstexprKind Kind) { 2127 SmallVector<SourceLocation, 4> ReturnStmts; 2128 2129 if (isa<CXXTryStmt>(Body)) { 2130 // C++11 [dcl.constexpr]p3: 2131 // The definition of a constexpr function shall satisfy the following 2132 // constraints: [...] 2133 // - its function-body shall be = delete, = default, or a 2134 // compound-statement 2135 // 2136 // C++11 [dcl.constexpr]p4: 2137 // In the definition of a constexpr constructor, [...] 2138 // - its function-body shall not be a function-try-block; 2139 // 2140 // This restriction is lifted in C++2a, as long as inner statements also 2141 // apply the general constexpr rules. 2142 switch (Kind) { 2143 case Sema::CheckConstexprKind::CheckValid: 2144 if (!SemaRef.getLangOpts().CPlusPlus20) 2145 return false; 2146 break; 2147 2148 case Sema::CheckConstexprKind::Diagnose: 2149 SemaRef.Diag(Body->getBeginLoc(), 2150 !SemaRef.getLangOpts().CPlusPlus20 2151 ? diag::ext_constexpr_function_try_block_cxx20 2152 : diag::warn_cxx17_compat_constexpr_function_try_block) 2153 << isa<CXXConstructorDecl>(Dcl); 2154 break; 2155 } 2156 } 2157 2158 // - its function-body shall be [...] a compound-statement that contains only 2159 // [... list of cases ...] 2160 // 2161 // Note that walking the children here is enough to properly check for 2162 // CompoundStmt and CXXTryStmt body. 2163 SourceLocation Cxx1yLoc, Cxx2aLoc; 2164 for (Stmt *SubStmt : Body->children()) { 2165 if (SubStmt && 2166 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2167 Cxx1yLoc, Cxx2aLoc, Kind)) 2168 return false; 2169 } 2170 2171 if (Kind == Sema::CheckConstexprKind::CheckValid) { 2172 // If this is only valid as an extension, report that we don't satisfy the 2173 // constraints of the current language. 2174 if ((Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) || 2175 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17)) 2176 return false; 2177 } else if (Cxx2aLoc.isValid()) { 2178 SemaRef.Diag(Cxx2aLoc, 2179 SemaRef.getLangOpts().CPlusPlus20 2180 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt 2181 : diag::ext_constexpr_body_invalid_stmt_cxx20) 2182 << isa<CXXConstructorDecl>(Dcl); 2183 } else if (Cxx1yLoc.isValid()) { 2184 SemaRef.Diag(Cxx1yLoc, 2185 SemaRef.getLangOpts().CPlusPlus14 2186 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 2187 : diag::ext_constexpr_body_invalid_stmt) 2188 << isa<CXXConstructorDecl>(Dcl); 2189 } 2190 2191 if (const CXXConstructorDecl *Constructor 2192 = dyn_cast<CXXConstructorDecl>(Dcl)) { 2193 const CXXRecordDecl *RD = Constructor->getParent(); 2194 // DR1359: 2195 // - every non-variant non-static data member and base class sub-object 2196 // shall be initialized; 2197 // DR1460: 2198 // - if the class is a union having variant members, exactly one of them 2199 // shall be initialized; 2200 if (RD->isUnion()) { 2201 if (Constructor->getNumCtorInitializers() == 0 && 2202 RD->hasVariantMembers()) { 2203 if (Kind == Sema::CheckConstexprKind::Diagnose) { 2204 SemaRef.Diag( 2205 Dcl->getLocation(), 2206 SemaRef.getLangOpts().CPlusPlus20 2207 ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init 2208 : diag::ext_constexpr_union_ctor_no_init); 2209 } else if (!SemaRef.getLangOpts().CPlusPlus20) { 2210 return false; 2211 } 2212 } 2213 } else if (!Constructor->isDependentContext() && 2214 !Constructor->isDelegatingConstructor()) { 2215 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 2216 2217 // Skip detailed checking if we have enough initializers, and we would 2218 // allow at most one initializer per member. 2219 bool AnyAnonStructUnionMembers = false; 2220 unsigned Fields = 0; 2221 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 2222 E = RD->field_end(); I != E; ++I, ++Fields) { 2223 if (I->isAnonymousStructOrUnion()) { 2224 AnyAnonStructUnionMembers = true; 2225 break; 2226 } 2227 } 2228 // DR1460: 2229 // - if the class is a union-like class, but is not a union, for each of 2230 // its anonymous union members having variant members, exactly one of 2231 // them shall be initialized; 2232 if (AnyAnonStructUnionMembers || 2233 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 2234 // Check initialization of non-static data members. Base classes are 2235 // always initialized so do not need to be checked. Dependent bases 2236 // might not have initializers in the member initializer list. 2237 llvm::SmallSet<Decl*, 16> Inits; 2238 for (const auto *I: Constructor->inits()) { 2239 if (FieldDecl *FD = I->getMember()) 2240 Inits.insert(FD); 2241 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 2242 Inits.insert(ID->chain_begin(), ID->chain_end()); 2243 } 2244 2245 bool Diagnosed = false; 2246 for (auto *I : RD->fields()) 2247 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, 2248 Kind)) 2249 return false; 2250 } 2251 } 2252 } else { 2253 if (ReturnStmts.empty()) { 2254 // C++1y doesn't require constexpr functions to contain a 'return' 2255 // statement. We still do, unless the return type might be void, because 2256 // otherwise if there's no return statement, the function cannot 2257 // be used in a core constant expression. 2258 bool OK = SemaRef.getLangOpts().CPlusPlus14 && 2259 (Dcl->getReturnType()->isVoidType() || 2260 Dcl->getReturnType()->isDependentType()); 2261 switch (Kind) { 2262 case Sema::CheckConstexprKind::Diagnose: 2263 SemaRef.Diag(Dcl->getLocation(), 2264 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 2265 : diag::err_constexpr_body_no_return) 2266 << Dcl->isConsteval(); 2267 if (!OK) 2268 return false; 2269 break; 2270 2271 case Sema::CheckConstexprKind::CheckValid: 2272 // The formal requirements don't include this rule in C++14, even 2273 // though the "must be able to produce a constant expression" rules 2274 // still imply it in some cases. 2275 if (!SemaRef.getLangOpts().CPlusPlus14) 2276 return false; 2277 break; 2278 } 2279 } else if (ReturnStmts.size() > 1) { 2280 switch (Kind) { 2281 case Sema::CheckConstexprKind::Diagnose: 2282 SemaRef.Diag( 2283 ReturnStmts.back(), 2284 SemaRef.getLangOpts().CPlusPlus14 2285 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 2286 : diag::ext_constexpr_body_multiple_return); 2287 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 2288 SemaRef.Diag(ReturnStmts[I], 2289 diag::note_constexpr_body_previous_return); 2290 break; 2291 2292 case Sema::CheckConstexprKind::CheckValid: 2293 if (!SemaRef.getLangOpts().CPlusPlus14) 2294 return false; 2295 break; 2296 } 2297 } 2298 } 2299 2300 // C++11 [dcl.constexpr]p5: 2301 // if no function argument values exist such that the function invocation 2302 // substitution would produce a constant expression, the program is 2303 // ill-formed; no diagnostic required. 2304 // C++11 [dcl.constexpr]p3: 2305 // - every constructor call and implicit conversion used in initializing the 2306 // return value shall be one of those allowed in a constant expression. 2307 // C++11 [dcl.constexpr]p4: 2308 // - every constructor involved in initializing non-static data members and 2309 // base class sub-objects shall be a constexpr constructor. 2310 // 2311 // Note that this rule is distinct from the "requirements for a constexpr 2312 // function", so is not checked in CheckValid mode. 2313 SmallVector<PartialDiagnosticAt, 8> Diags; 2314 if (Kind == Sema::CheckConstexprKind::Diagnose && 2315 !Expr::isPotentialConstantExpr(Dcl, Diags)) { 2316 SemaRef.Diag(Dcl->getLocation(), 2317 diag::ext_constexpr_function_never_constant_expr) 2318 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 2319 for (size_t I = 0, N = Diags.size(); I != N; ++I) 2320 SemaRef.Diag(Diags[I].first, Diags[I].second); 2321 // Don't return false here: we allow this for compatibility in 2322 // system headers. 2323 } 2324 2325 return true; 2326 } 2327 2328 /// Get the class that is directly named by the current context. This is the 2329 /// class for which an unqualified-id in this scope could name a constructor 2330 /// or destructor. 2331 /// 2332 /// If the scope specifier denotes a class, this will be that class. 2333 /// If the scope specifier is empty, this will be the class whose 2334 /// member-specification we are currently within. Otherwise, there 2335 /// is no such class. 2336 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) { 2337 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2338 2339 if (SS && SS->isInvalid()) 2340 return nullptr; 2341 2342 if (SS && SS->isNotEmpty()) { 2343 DeclContext *DC = computeDeclContext(*SS, true); 2344 return dyn_cast_or_null<CXXRecordDecl>(DC); 2345 } 2346 2347 return dyn_cast_or_null<CXXRecordDecl>(CurContext); 2348 } 2349 2350 /// isCurrentClassName - Determine whether the identifier II is the 2351 /// name of the class type currently being defined. In the case of 2352 /// nested classes, this will only return true if II is the name of 2353 /// the innermost class. 2354 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S, 2355 const CXXScopeSpec *SS) { 2356 CXXRecordDecl *CurDecl = getCurrentClass(S, SS); 2357 return CurDecl && &II == CurDecl->getIdentifier(); 2358 } 2359 2360 /// Determine whether the identifier II is a typo for the name of 2361 /// the class type currently being defined. If so, update it to the identifier 2362 /// that should have been used. 2363 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 2364 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2365 2366 if (!getLangOpts().SpellChecking) 2367 return false; 2368 2369 CXXRecordDecl *CurDecl; 2370 if (SS && SS->isSet() && !SS->isInvalid()) { 2371 DeclContext *DC = computeDeclContext(*SS, true); 2372 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 2373 } else 2374 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 2375 2376 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 2377 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 2378 < II->getLength()) { 2379 II = CurDecl->getIdentifier(); 2380 return true; 2381 } 2382 2383 return false; 2384 } 2385 2386 /// Determine whether the given class is a base class of the given 2387 /// class, including looking at dependent bases. 2388 static bool findCircularInheritance(const CXXRecordDecl *Class, 2389 const CXXRecordDecl *Current) { 2390 SmallVector<const CXXRecordDecl*, 8> Queue; 2391 2392 Class = Class->getCanonicalDecl(); 2393 while (true) { 2394 for (const auto &I : Current->bases()) { 2395 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 2396 if (!Base) 2397 continue; 2398 2399 Base = Base->getDefinition(); 2400 if (!Base) 2401 continue; 2402 2403 if (Base->getCanonicalDecl() == Class) 2404 return true; 2405 2406 Queue.push_back(Base); 2407 } 2408 2409 if (Queue.empty()) 2410 return false; 2411 2412 Current = Queue.pop_back_val(); 2413 } 2414 2415 return false; 2416 } 2417 2418 /// Check the validity of a C++ base class specifier. 2419 /// 2420 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 2421 /// and returns NULL otherwise. 2422 CXXBaseSpecifier * 2423 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 2424 SourceRange SpecifierRange, 2425 bool Virtual, AccessSpecifier Access, 2426 TypeSourceInfo *TInfo, 2427 SourceLocation EllipsisLoc) { 2428 QualType BaseType = TInfo->getType(); 2429 2430 // C++ [class.union]p1: 2431 // A union shall not have base classes. 2432 if (Class->isUnion()) { 2433 Diag(Class->getLocation(), diag::err_base_clause_on_union) 2434 << SpecifierRange; 2435 return nullptr; 2436 } 2437 2438 if (EllipsisLoc.isValid() && 2439 !TInfo->getType()->containsUnexpandedParameterPack()) { 2440 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2441 << TInfo->getTypeLoc().getSourceRange(); 2442 EllipsisLoc = SourceLocation(); 2443 } 2444 2445 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 2446 2447 if (BaseType->isDependentType()) { 2448 // Make sure that we don't have circular inheritance among our dependent 2449 // bases. For non-dependent bases, the check for completeness below handles 2450 // this. 2451 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 2452 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 2453 ((BaseDecl = BaseDecl->getDefinition()) && 2454 findCircularInheritance(Class, BaseDecl))) { 2455 Diag(BaseLoc, diag::err_circular_inheritance) 2456 << BaseType << Context.getTypeDeclType(Class); 2457 2458 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 2459 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 2460 << BaseType; 2461 2462 return nullptr; 2463 } 2464 } 2465 2466 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2467 Class->getTagKind() == TTK_Class, 2468 Access, TInfo, EllipsisLoc); 2469 } 2470 2471 // Base specifiers must be record types. 2472 if (!BaseType->isRecordType()) { 2473 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 2474 return nullptr; 2475 } 2476 2477 // C++ [class.union]p1: 2478 // A union shall not be used as a base class. 2479 if (BaseType->isUnionType()) { 2480 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 2481 return nullptr; 2482 } 2483 2484 // For the MS ABI, propagate DLL attributes to base class templates. 2485 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 2486 if (Attr *ClassAttr = getDLLAttr(Class)) { 2487 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 2488 BaseType->getAsCXXRecordDecl())) { 2489 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate, 2490 BaseLoc); 2491 } 2492 } 2493 } 2494 2495 // C++ [class.derived]p2: 2496 // The class-name in a base-specifier shall not be an incompletely 2497 // defined class. 2498 if (RequireCompleteType(BaseLoc, BaseType, 2499 diag::err_incomplete_base_class, SpecifierRange)) { 2500 Class->setInvalidDecl(); 2501 return nullptr; 2502 } 2503 2504 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 2505 RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl(); 2506 assert(BaseDecl && "Record type has no declaration"); 2507 BaseDecl = BaseDecl->getDefinition(); 2508 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 2509 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 2510 assert(CXXBaseDecl && "Base type is not a C++ type"); 2511 2512 // Microsoft docs say: 2513 // "If a base-class has a code_seg attribute, derived classes must have the 2514 // same attribute." 2515 const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>(); 2516 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>(); 2517 if ((DerivedCSA || BaseCSA) && 2518 (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) { 2519 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base); 2520 Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here) 2521 << CXXBaseDecl; 2522 return nullptr; 2523 } 2524 2525 // A class which contains a flexible array member is not suitable for use as a 2526 // base class: 2527 // - If the layout determines that a base comes before another base, 2528 // the flexible array member would index into the subsequent base. 2529 // - If the layout determines that base comes before the derived class, 2530 // the flexible array member would index into the derived class. 2531 if (CXXBaseDecl->hasFlexibleArrayMember()) { 2532 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 2533 << CXXBaseDecl->getDeclName(); 2534 return nullptr; 2535 } 2536 2537 // C++ [class]p3: 2538 // If a class is marked final and it appears as a base-type-specifier in 2539 // base-clause, the program is ill-formed. 2540 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 2541 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 2542 << CXXBaseDecl->getDeclName() 2543 << FA->isSpelledAsSealed(); 2544 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 2545 << CXXBaseDecl->getDeclName() << FA->getRange(); 2546 return nullptr; 2547 } 2548 2549 if (BaseDecl->isInvalidDecl()) 2550 Class->setInvalidDecl(); 2551 2552 // Create the base specifier. 2553 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2554 Class->getTagKind() == TTK_Class, 2555 Access, TInfo, EllipsisLoc); 2556 } 2557 2558 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 2559 /// one entry in the base class list of a class specifier, for 2560 /// example: 2561 /// class foo : public bar, virtual private baz { 2562 /// 'public bar' and 'virtual private baz' are each base-specifiers. 2563 BaseResult 2564 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 2565 ParsedAttributes &Attributes, 2566 bool Virtual, AccessSpecifier Access, 2567 ParsedType basetype, SourceLocation BaseLoc, 2568 SourceLocation EllipsisLoc) { 2569 if (!classdecl) 2570 return true; 2571 2572 AdjustDeclIfTemplate(classdecl); 2573 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 2574 if (!Class) 2575 return true; 2576 2577 // We haven't yet attached the base specifiers. 2578 Class->setIsParsingBaseSpecifiers(); 2579 2580 // We do not support any C++11 attributes on base-specifiers yet. 2581 // Diagnose any attributes we see. 2582 for (const ParsedAttr &AL : Attributes) { 2583 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute) 2584 continue; 2585 Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute 2586 ? (unsigned)diag::warn_unknown_attribute_ignored 2587 : (unsigned)diag::err_base_specifier_attribute) 2588 << AL; 2589 } 2590 2591 TypeSourceInfo *TInfo = nullptr; 2592 GetTypeFromParser(basetype, &TInfo); 2593 2594 if (EllipsisLoc.isInvalid() && 2595 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 2596 UPPC_BaseType)) 2597 return true; 2598 2599 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 2600 Virtual, Access, TInfo, 2601 EllipsisLoc)) 2602 return BaseSpec; 2603 else 2604 Class->setInvalidDecl(); 2605 2606 return true; 2607 } 2608 2609 /// Use small set to collect indirect bases. As this is only used 2610 /// locally, there's no need to abstract the small size parameter. 2611 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet; 2612 2613 /// Recursively add the bases of Type. Don't add Type itself. 2614 static void 2615 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, 2616 const QualType &Type) 2617 { 2618 // Even though the incoming type is a base, it might not be 2619 // a class -- it could be a template parm, for instance. 2620 if (auto Rec = Type->getAs<RecordType>()) { 2621 auto Decl = Rec->getAsCXXRecordDecl(); 2622 2623 // Iterate over its bases. 2624 for (const auto &BaseSpec : Decl->bases()) { 2625 QualType Base = Context.getCanonicalType(BaseSpec.getType()) 2626 .getUnqualifiedType(); 2627 if (Set.insert(Base).second) 2628 // If we've not already seen it, recurse. 2629 NoteIndirectBases(Context, Set, Base); 2630 } 2631 } 2632 } 2633 2634 /// Performs the actual work of attaching the given base class 2635 /// specifiers to a C++ class. 2636 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, 2637 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2638 if (Bases.empty()) 2639 return false; 2640 2641 // Used to keep track of which base types we have already seen, so 2642 // that we can properly diagnose redundant direct base types. Note 2643 // that the key is always the unqualified canonical type of the base 2644 // class. 2645 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 2646 2647 // Used to track indirect bases so we can see if a direct base is 2648 // ambiguous. 2649 IndirectBaseSet IndirectBaseTypes; 2650 2651 // Copy non-redundant base specifiers into permanent storage. 2652 unsigned NumGoodBases = 0; 2653 bool Invalid = false; 2654 for (unsigned idx = 0; idx < Bases.size(); ++idx) { 2655 QualType NewBaseType 2656 = Context.getCanonicalType(Bases[idx]->getType()); 2657 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 2658 2659 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 2660 if (KnownBase) { 2661 // C++ [class.mi]p3: 2662 // A class shall not be specified as a direct base class of a 2663 // derived class more than once. 2664 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class) 2665 << KnownBase->getType() << Bases[idx]->getSourceRange(); 2666 2667 // Delete the duplicate base class specifier; we're going to 2668 // overwrite its pointer later. 2669 Context.Deallocate(Bases[idx]); 2670 2671 Invalid = true; 2672 } else { 2673 // Okay, add this new base class. 2674 KnownBase = Bases[idx]; 2675 Bases[NumGoodBases++] = Bases[idx]; 2676 2677 // Note this base's direct & indirect bases, if there could be ambiguity. 2678 if (Bases.size() > 1) 2679 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType); 2680 2681 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 2682 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 2683 if (Class->isInterface() && 2684 (!RD->isInterfaceLike() || 2685 KnownBase->getAccessSpecifier() != AS_public)) { 2686 // The Microsoft extension __interface does not permit bases that 2687 // are not themselves public interfaces. 2688 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface) 2689 << getRecordDiagFromTagKind(RD->getTagKind()) << RD 2690 << RD->getSourceRange(); 2691 Invalid = true; 2692 } 2693 if (RD->hasAttr<WeakAttr>()) 2694 Class->addAttr(WeakAttr::CreateImplicit(Context)); 2695 } 2696 } 2697 } 2698 2699 // Attach the remaining base class specifiers to the derived class. 2700 Class->setBases(Bases.data(), NumGoodBases); 2701 2702 // Check that the only base classes that are duplicate are virtual. 2703 for (unsigned idx = 0; idx < NumGoodBases; ++idx) { 2704 // Check whether this direct base is inaccessible due to ambiguity. 2705 QualType BaseType = Bases[idx]->getType(); 2706 2707 // Skip all dependent types in templates being used as base specifiers. 2708 // Checks below assume that the base specifier is a CXXRecord. 2709 if (BaseType->isDependentType()) 2710 continue; 2711 2712 CanQualType CanonicalBase = Context.getCanonicalType(BaseType) 2713 .getUnqualifiedType(); 2714 2715 if (IndirectBaseTypes.count(CanonicalBase)) { 2716 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2717 /*DetectVirtual=*/true); 2718 bool found 2719 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); 2720 assert(found); 2721 (void)found; 2722 2723 if (Paths.isAmbiguous(CanonicalBase)) 2724 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class) 2725 << BaseType << getAmbiguousPathsDisplayString(Paths) 2726 << Bases[idx]->getSourceRange(); 2727 else 2728 assert(Bases[idx]->isVirtual()); 2729 } 2730 2731 // Delete the base class specifier, since its data has been copied 2732 // into the CXXRecordDecl. 2733 Context.Deallocate(Bases[idx]); 2734 } 2735 2736 return Invalid; 2737 } 2738 2739 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 2740 /// class, after checking whether there are any duplicate base 2741 /// classes. 2742 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, 2743 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2744 if (!ClassDecl || Bases.empty()) 2745 return; 2746 2747 AdjustDeclIfTemplate(ClassDecl); 2748 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases); 2749 } 2750 2751 /// Determine whether the type \p Derived is a C++ class that is 2752 /// derived from the type \p Base. 2753 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) { 2754 if (!getLangOpts().CPlusPlus) 2755 return false; 2756 2757 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2758 if (!DerivedRD) 2759 return false; 2760 2761 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2762 if (!BaseRD) 2763 return false; 2764 2765 // If either the base or the derived type is invalid, don't try to 2766 // check whether one is derived from the other. 2767 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 2768 return false; 2769 2770 // FIXME: In a modules build, do we need the entire path to be visible for us 2771 // to be able to use the inheritance relationship? 2772 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2773 return false; 2774 2775 return DerivedRD->isDerivedFrom(BaseRD); 2776 } 2777 2778 /// Determine whether the type \p Derived is a C++ class that is 2779 /// derived from the type \p Base. 2780 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, 2781 CXXBasePaths &Paths) { 2782 if (!getLangOpts().CPlusPlus) 2783 return false; 2784 2785 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2786 if (!DerivedRD) 2787 return false; 2788 2789 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2790 if (!BaseRD) 2791 return false; 2792 2793 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2794 return false; 2795 2796 return DerivedRD->isDerivedFrom(BaseRD, Paths); 2797 } 2798 2799 static void BuildBasePathArray(const CXXBasePath &Path, 2800 CXXCastPath &BasePathArray) { 2801 // We first go backward and check if we have a virtual base. 2802 // FIXME: It would be better if CXXBasePath had the base specifier for 2803 // the nearest virtual base. 2804 unsigned Start = 0; 2805 for (unsigned I = Path.size(); I != 0; --I) { 2806 if (Path[I - 1].Base->isVirtual()) { 2807 Start = I - 1; 2808 break; 2809 } 2810 } 2811 2812 // Now add all bases. 2813 for (unsigned I = Start, E = Path.size(); I != E; ++I) 2814 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 2815 } 2816 2817 2818 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 2819 CXXCastPath &BasePathArray) { 2820 assert(BasePathArray.empty() && "Base path array must be empty!"); 2821 assert(Paths.isRecordingPaths() && "Must record paths!"); 2822 return ::BuildBasePathArray(Paths.front(), BasePathArray); 2823 } 2824 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 2825 /// conversion (where Derived and Base are class types) is 2826 /// well-formed, meaning that the conversion is unambiguous (and 2827 /// that all of the base classes are accessible). Returns true 2828 /// and emits a diagnostic if the code is ill-formed, returns false 2829 /// otherwise. Loc is the location where this routine should point to 2830 /// if there is an error, and Range is the source range to highlight 2831 /// if there is an error. 2832 /// 2833 /// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the 2834 /// diagnostic for the respective type of error will be suppressed, but the 2835 /// check for ill-formed code will still be performed. 2836 bool 2837 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2838 unsigned InaccessibleBaseID, 2839 unsigned AmbiguousBaseConvID, 2840 SourceLocation Loc, SourceRange Range, 2841 DeclarationName Name, 2842 CXXCastPath *BasePath, 2843 bool IgnoreAccess) { 2844 // First, determine whether the path from Derived to Base is 2845 // ambiguous. This is slightly more expensive than checking whether 2846 // the Derived to Base conversion exists, because here we need to 2847 // explore multiple paths to determine if there is an ambiguity. 2848 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2849 /*DetectVirtual=*/false); 2850 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2851 if (!DerivationOkay) 2852 return true; 2853 2854 const CXXBasePath *Path = nullptr; 2855 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) 2856 Path = &Paths.front(); 2857 2858 // For MSVC compatibility, check if Derived directly inherits from Base. Clang 2859 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the 2860 // user to access such bases. 2861 if (!Path && getLangOpts().MSVCCompat) { 2862 for (const CXXBasePath &PossiblePath : Paths) { 2863 if (PossiblePath.size() == 1) { 2864 Path = &PossiblePath; 2865 if (AmbiguousBaseConvID) 2866 Diag(Loc, diag::ext_ms_ambiguous_direct_base) 2867 << Base << Derived << Range; 2868 break; 2869 } 2870 } 2871 } 2872 2873 if (Path) { 2874 if (!IgnoreAccess) { 2875 // Check that the base class can be accessed. 2876 switch ( 2877 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) { 2878 case AR_inaccessible: 2879 return true; 2880 case AR_accessible: 2881 case AR_dependent: 2882 case AR_delayed: 2883 break; 2884 } 2885 } 2886 2887 // Build a base path if necessary. 2888 if (BasePath) 2889 ::BuildBasePathArray(*Path, *BasePath); 2890 return false; 2891 } 2892 2893 if (AmbiguousBaseConvID) { 2894 // We know that the derived-to-base conversion is ambiguous, and 2895 // we're going to produce a diagnostic. Perform the derived-to-base 2896 // search just one more time to compute all of the possible paths so 2897 // that we can print them out. This is more expensive than any of 2898 // the previous derived-to-base checks we've done, but at this point 2899 // performance isn't as much of an issue. 2900 Paths.clear(); 2901 Paths.setRecordingPaths(true); 2902 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2903 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 2904 (void)StillOkay; 2905 2906 // Build up a textual representation of the ambiguous paths, e.g., 2907 // D -> B -> A, that will be used to illustrate the ambiguous 2908 // conversions in the diagnostic. We only print one of the paths 2909 // to each base class subobject. 2910 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2911 2912 Diag(Loc, AmbiguousBaseConvID) 2913 << Derived << Base << PathDisplayStr << Range << Name; 2914 } 2915 return true; 2916 } 2917 2918 bool 2919 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2920 SourceLocation Loc, SourceRange Range, 2921 CXXCastPath *BasePath, 2922 bool IgnoreAccess) { 2923 return CheckDerivedToBaseConversion( 2924 Derived, Base, diag::err_upcast_to_inaccessible_base, 2925 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(), 2926 BasePath, IgnoreAccess); 2927 } 2928 2929 2930 /// Builds a string representing ambiguous paths from a 2931 /// specific derived class to different subobjects of the same base 2932 /// class. 2933 /// 2934 /// This function builds a string that can be used in error messages 2935 /// to show the different paths that one can take through the 2936 /// inheritance hierarchy to go from the derived class to different 2937 /// subobjects of a base class. The result looks something like this: 2938 /// @code 2939 /// struct D -> struct B -> struct A 2940 /// struct D -> struct C -> struct A 2941 /// @endcode 2942 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 2943 std::string PathDisplayStr; 2944 std::set<unsigned> DisplayedPaths; 2945 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2946 Path != Paths.end(); ++Path) { 2947 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 2948 // We haven't displayed a path to this particular base 2949 // class subobject yet. 2950 PathDisplayStr += "\n "; 2951 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 2952 for (CXXBasePath::const_iterator Element = Path->begin(); 2953 Element != Path->end(); ++Element) 2954 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 2955 } 2956 } 2957 2958 return PathDisplayStr; 2959 } 2960 2961 //===----------------------------------------------------------------------===// 2962 // C++ class member Handling 2963 //===----------------------------------------------------------------------===// 2964 2965 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 2966 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, 2967 SourceLocation ColonLoc, 2968 const ParsedAttributesView &Attrs) { 2969 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 2970 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 2971 ASLoc, ColonLoc); 2972 CurContext->addHiddenDecl(ASDecl); 2973 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 2974 } 2975 2976 /// CheckOverrideControl - Check C++11 override control semantics. 2977 void Sema::CheckOverrideControl(NamedDecl *D) { 2978 if (D->isInvalidDecl()) 2979 return; 2980 2981 // We only care about "override" and "final" declarations. 2982 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 2983 return; 2984 2985 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 2986 2987 // We can't check dependent instance methods. 2988 if (MD && MD->isInstance() && 2989 (MD->getParent()->hasAnyDependentBases() || 2990 MD->getType()->isDependentType())) 2991 return; 2992 2993 if (MD && !MD->isVirtual()) { 2994 // If we have a non-virtual method, check if if hides a virtual method. 2995 // (In that case, it's most likely the method has the wrong type.) 2996 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 2997 FindHiddenVirtualMethods(MD, OverloadedMethods); 2998 2999 if (!OverloadedMethods.empty()) { 3000 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 3001 Diag(OA->getLocation(), 3002 diag::override_keyword_hides_virtual_member_function) 3003 << "override" << (OverloadedMethods.size() > 1); 3004 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 3005 Diag(FA->getLocation(), 3006 diag::override_keyword_hides_virtual_member_function) 3007 << (FA->isSpelledAsSealed() ? "sealed" : "final") 3008 << (OverloadedMethods.size() > 1); 3009 } 3010 NoteHiddenVirtualMethods(MD, OverloadedMethods); 3011 MD->setInvalidDecl(); 3012 return; 3013 } 3014 // Fall through into the general case diagnostic. 3015 // FIXME: We might want to attempt typo correction here. 3016 } 3017 3018 if (!MD || !MD->isVirtual()) { 3019 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 3020 Diag(OA->getLocation(), 3021 diag::override_keyword_only_allowed_on_virtual_member_functions) 3022 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 3023 D->dropAttr<OverrideAttr>(); 3024 } 3025 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 3026 Diag(FA->getLocation(), 3027 diag::override_keyword_only_allowed_on_virtual_member_functions) 3028 << (FA->isSpelledAsSealed() ? "sealed" : "final") 3029 << FixItHint::CreateRemoval(FA->getLocation()); 3030 D->dropAttr<FinalAttr>(); 3031 } 3032 return; 3033 } 3034 3035 // C++11 [class.virtual]p5: 3036 // If a function is marked with the virt-specifier override and 3037 // does not override a member function of a base class, the program is 3038 // ill-formed. 3039 bool HasOverriddenMethods = MD->size_overridden_methods() != 0; 3040 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 3041 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 3042 << MD->getDeclName(); 3043 } 3044 3045 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) { 3046 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) 3047 return; 3048 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 3049 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>()) 3050 return; 3051 3052 SourceLocation Loc = MD->getLocation(); 3053 SourceLocation SpellingLoc = Loc; 3054 if (getSourceManager().isMacroArgExpansion(Loc)) 3055 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin(); 3056 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); 3057 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) 3058 return; 3059 3060 if (MD->size_overridden_methods() > 0) { 3061 unsigned DiagID = isa<CXXDestructorDecl>(MD) 3062 ? diag::warn_destructor_marked_not_override_overriding 3063 : diag::warn_function_marked_not_override_overriding; 3064 Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 3065 const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); 3066 Diag(OMD->getLocation(), diag::note_overridden_virtual_function); 3067 } 3068 } 3069 3070 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 3071 /// function overrides a virtual member function marked 'final', according to 3072 /// C++11 [class.virtual]p4. 3073 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 3074 const CXXMethodDecl *Old) { 3075 FinalAttr *FA = Old->getAttr<FinalAttr>(); 3076 if (!FA) 3077 return false; 3078 3079 Diag(New->getLocation(), diag::err_final_function_overridden) 3080 << New->getDeclName() 3081 << FA->isSpelledAsSealed(); 3082 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 3083 return true; 3084 } 3085 3086 static bool InitializationHasSideEffects(const FieldDecl &FD) { 3087 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 3088 // FIXME: Destruction of ObjC lifetime types has side-effects. 3089 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 3090 return !RD->isCompleteDefinition() || 3091 !RD->hasTrivialDefaultConstructor() || 3092 !RD->hasTrivialDestructor(); 3093 return false; 3094 } 3095 3096 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) { 3097 ParsedAttributesView::const_iterator Itr = 3098 llvm::find_if(list, [](const ParsedAttr &AL) { 3099 return AL.isDeclspecPropertyAttribute(); 3100 }); 3101 if (Itr != list.end()) 3102 return &*Itr; 3103 return nullptr; 3104 } 3105 3106 // Check if there is a field shadowing. 3107 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc, 3108 DeclarationName FieldName, 3109 const CXXRecordDecl *RD, 3110 bool DeclIsField) { 3111 if (Diags.isIgnored(diag::warn_shadow_field, Loc)) 3112 return; 3113 3114 // To record a shadowed field in a base 3115 std::map<CXXRecordDecl*, NamedDecl*> Bases; 3116 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier, 3117 CXXBasePath &Path) { 3118 const auto Base = Specifier->getType()->getAsCXXRecordDecl(); 3119 // Record an ambiguous path directly 3120 if (Bases.find(Base) != Bases.end()) 3121 return true; 3122 for (const auto Field : Base->lookup(FieldName)) { 3123 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) && 3124 Field->getAccess() != AS_private) { 3125 assert(Field->getAccess() != AS_none); 3126 assert(Bases.find(Base) == Bases.end()); 3127 Bases[Base] = Field; 3128 return true; 3129 } 3130 } 3131 return false; 3132 }; 3133 3134 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3135 /*DetectVirtual=*/true); 3136 if (!RD->lookupInBases(FieldShadowed, Paths)) 3137 return; 3138 3139 for (const auto &P : Paths) { 3140 auto Base = P.back().Base->getType()->getAsCXXRecordDecl(); 3141 auto It = Bases.find(Base); 3142 // Skip duplicated bases 3143 if (It == Bases.end()) 3144 continue; 3145 auto BaseField = It->second; 3146 assert(BaseField->getAccess() != AS_private); 3147 if (AS_none != 3148 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) { 3149 Diag(Loc, diag::warn_shadow_field) 3150 << FieldName << RD << Base << DeclIsField; 3151 Diag(BaseField->getLocation(), diag::note_shadow_field); 3152 Bases.erase(It); 3153 } 3154 } 3155 } 3156 3157 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 3158 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 3159 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 3160 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 3161 /// present (but parsing it has been deferred). 3162 NamedDecl * 3163 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 3164 MultiTemplateParamsArg TemplateParameterLists, 3165 Expr *BW, const VirtSpecifiers &VS, 3166 InClassInitStyle InitStyle) { 3167 const DeclSpec &DS = D.getDeclSpec(); 3168 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 3169 DeclarationName Name = NameInfo.getName(); 3170 SourceLocation Loc = NameInfo.getLoc(); 3171 3172 // For anonymous bitfields, the location should point to the type. 3173 if (Loc.isInvalid()) 3174 Loc = D.getBeginLoc(); 3175 3176 Expr *BitWidth = static_cast<Expr*>(BW); 3177 3178 assert(isa<CXXRecordDecl>(CurContext)); 3179 assert(!DS.isFriendSpecified()); 3180 3181 bool isFunc = D.isDeclarationOfFunction(); 3182 const ParsedAttr *MSPropertyAttr = 3183 getMSPropertyAttr(D.getDeclSpec().getAttributes()); 3184 3185 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 3186 // The Microsoft extension __interface only permits public member functions 3187 // and prohibits constructors, destructors, operators, non-public member 3188 // functions, static methods and data members. 3189 unsigned InvalidDecl; 3190 bool ShowDeclName = true; 3191 if (!isFunc && 3192 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr)) 3193 InvalidDecl = 0; 3194 else if (!isFunc) 3195 InvalidDecl = 1; 3196 else if (AS != AS_public) 3197 InvalidDecl = 2; 3198 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 3199 InvalidDecl = 3; 3200 else switch (Name.getNameKind()) { 3201 case DeclarationName::CXXConstructorName: 3202 InvalidDecl = 4; 3203 ShowDeclName = false; 3204 break; 3205 3206 case DeclarationName::CXXDestructorName: 3207 InvalidDecl = 5; 3208 ShowDeclName = false; 3209 break; 3210 3211 case DeclarationName::CXXOperatorName: 3212 case DeclarationName::CXXConversionFunctionName: 3213 InvalidDecl = 6; 3214 break; 3215 3216 default: 3217 InvalidDecl = 0; 3218 break; 3219 } 3220 3221 if (InvalidDecl) { 3222 if (ShowDeclName) 3223 Diag(Loc, diag::err_invalid_member_in_interface) 3224 << (InvalidDecl-1) << Name; 3225 else 3226 Diag(Loc, diag::err_invalid_member_in_interface) 3227 << (InvalidDecl-1) << ""; 3228 return nullptr; 3229 } 3230 } 3231 3232 // C++ 9.2p6: A member shall not be declared to have automatic storage 3233 // duration (auto, register) or with the extern storage-class-specifier. 3234 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 3235 // data members and cannot be applied to names declared const or static, 3236 // and cannot be applied to reference members. 3237 switch (DS.getStorageClassSpec()) { 3238 case DeclSpec::SCS_unspecified: 3239 case DeclSpec::SCS_typedef: 3240 case DeclSpec::SCS_static: 3241 break; 3242 case DeclSpec::SCS_mutable: 3243 if (isFunc) { 3244 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 3245 3246 // FIXME: It would be nicer if the keyword was ignored only for this 3247 // declarator. Otherwise we could get follow-up errors. 3248 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3249 } 3250 break; 3251 default: 3252 Diag(DS.getStorageClassSpecLoc(), 3253 diag::err_storageclass_invalid_for_member); 3254 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3255 break; 3256 } 3257 3258 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 3259 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 3260 !isFunc); 3261 3262 if (DS.hasConstexprSpecifier() && isInstField) { 3263 SemaDiagnosticBuilder B = 3264 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 3265 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 3266 if (InitStyle == ICIS_NoInit) { 3267 B << 0 << 0; 3268 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 3269 B << FixItHint::CreateRemoval(ConstexprLoc); 3270 else { 3271 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 3272 D.getMutableDeclSpec().ClearConstexprSpec(); 3273 const char *PrevSpec; 3274 unsigned DiagID; 3275 bool Failed = D.getMutableDeclSpec().SetTypeQual( 3276 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 3277 (void)Failed; 3278 assert(!Failed && "Making a constexpr member const shouldn't fail"); 3279 } 3280 } else { 3281 B << 1; 3282 const char *PrevSpec; 3283 unsigned DiagID; 3284 if (D.getMutableDeclSpec().SetStorageClassSpec( 3285 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 3286 Context.getPrintingPolicy())) { 3287 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 3288 "This is the only DeclSpec that should fail to be applied"); 3289 B << 1; 3290 } else { 3291 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 3292 isInstField = false; 3293 } 3294 } 3295 } 3296 3297 NamedDecl *Member; 3298 if (isInstField) { 3299 CXXScopeSpec &SS = D.getCXXScopeSpec(); 3300 3301 // Data members must have identifiers for names. 3302 if (!Name.isIdentifier()) { 3303 Diag(Loc, diag::err_bad_variable_name) 3304 << Name; 3305 return nullptr; 3306 } 3307 3308 IdentifierInfo *II = Name.getAsIdentifierInfo(); 3309 3310 // Member field could not be with "template" keyword. 3311 // So TemplateParameterLists should be empty in this case. 3312 if (TemplateParameterLists.size()) { 3313 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 3314 if (TemplateParams->size()) { 3315 // There is no such thing as a member field template. 3316 Diag(D.getIdentifierLoc(), diag::err_template_member) 3317 << II 3318 << SourceRange(TemplateParams->getTemplateLoc(), 3319 TemplateParams->getRAngleLoc()); 3320 } else { 3321 // There is an extraneous 'template<>' for this member. 3322 Diag(TemplateParams->getTemplateLoc(), 3323 diag::err_template_member_noparams) 3324 << II 3325 << SourceRange(TemplateParams->getTemplateLoc(), 3326 TemplateParams->getRAngleLoc()); 3327 } 3328 return nullptr; 3329 } 3330 3331 if (SS.isSet() && !SS.isInvalid()) { 3332 // The user provided a superfluous scope specifier inside a class 3333 // definition: 3334 // 3335 // class X { 3336 // int X::member; 3337 // }; 3338 if (DeclContext *DC = computeDeclContext(SS, false)) 3339 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(), 3340 D.getName().getKind() == 3341 UnqualifiedIdKind::IK_TemplateId); 3342 else 3343 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 3344 << Name << SS.getRange(); 3345 3346 SS.clear(); 3347 } 3348 3349 if (MSPropertyAttr) { 3350 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3351 BitWidth, InitStyle, AS, *MSPropertyAttr); 3352 if (!Member) 3353 return nullptr; 3354 isInstField = false; 3355 } else { 3356 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3357 BitWidth, InitStyle, AS); 3358 if (!Member) 3359 return nullptr; 3360 } 3361 3362 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext)); 3363 } else { 3364 Member = HandleDeclarator(S, D, TemplateParameterLists); 3365 if (!Member) 3366 return nullptr; 3367 3368 // Non-instance-fields can't have a bitfield. 3369 if (BitWidth) { 3370 if (Member->isInvalidDecl()) { 3371 // don't emit another diagnostic. 3372 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) { 3373 // C++ 9.6p3: A bit-field shall not be a static member. 3374 // "static member 'A' cannot be a bit-field" 3375 Diag(Loc, diag::err_static_not_bitfield) 3376 << Name << BitWidth->getSourceRange(); 3377 } else if (isa<TypedefDecl>(Member)) { 3378 // "typedef member 'x' cannot be a bit-field" 3379 Diag(Loc, diag::err_typedef_not_bitfield) 3380 << Name << BitWidth->getSourceRange(); 3381 } else { 3382 // A function typedef ("typedef int f(); f a;"). 3383 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 3384 Diag(Loc, diag::err_not_integral_type_bitfield) 3385 << Name << cast<ValueDecl>(Member)->getType() 3386 << BitWidth->getSourceRange(); 3387 } 3388 3389 BitWidth = nullptr; 3390 Member->setInvalidDecl(); 3391 } 3392 3393 NamedDecl *NonTemplateMember = Member; 3394 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 3395 NonTemplateMember = FunTmpl->getTemplatedDecl(); 3396 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 3397 NonTemplateMember = VarTmpl->getTemplatedDecl(); 3398 3399 Member->setAccess(AS); 3400 3401 // If we have declared a member function template or static data member 3402 // template, set the access of the templated declaration as well. 3403 if (NonTemplateMember != Member) 3404 NonTemplateMember->setAccess(AS); 3405 3406 // C++ [temp.deduct.guide]p3: 3407 // A deduction guide [...] for a member class template [shall be 3408 // declared] with the same access [as the template]. 3409 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) { 3410 auto *TD = DG->getDeducedTemplate(); 3411 // Access specifiers are only meaningful if both the template and the 3412 // deduction guide are from the same scope. 3413 if (AS != TD->getAccess() && 3414 TD->getDeclContext()->getRedeclContext()->Equals( 3415 DG->getDeclContext()->getRedeclContext())) { 3416 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access); 3417 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access) 3418 << TD->getAccess(); 3419 const AccessSpecDecl *LastAccessSpec = nullptr; 3420 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) { 3421 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D)) 3422 LastAccessSpec = AccessSpec; 3423 } 3424 assert(LastAccessSpec && "differing access with no access specifier"); 3425 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access) 3426 << AS; 3427 } 3428 } 3429 } 3430 3431 if (VS.isOverrideSpecified()) 3432 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(), 3433 AttributeCommonInfo::AS_Keyword)); 3434 if (VS.isFinalSpecified()) 3435 Member->addAttr(FinalAttr::Create( 3436 Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword, 3437 static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed()))); 3438 3439 if (VS.getLastLocation().isValid()) { 3440 // Update the end location of a method that has a virt-specifiers. 3441 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 3442 MD->setRangeEnd(VS.getLastLocation()); 3443 } 3444 3445 CheckOverrideControl(Member); 3446 3447 assert((Name || isInstField) && "No identifier for non-field ?"); 3448 3449 if (isInstField) { 3450 FieldDecl *FD = cast<FieldDecl>(Member); 3451 FieldCollector->Add(FD); 3452 3453 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 3454 // Remember all explicit private FieldDecls that have a name, no side 3455 // effects and are not part of a dependent type declaration. 3456 if (!FD->isImplicit() && FD->getDeclName() && 3457 FD->getAccess() == AS_private && 3458 !FD->hasAttr<UnusedAttr>() && 3459 !FD->getParent()->isDependentContext() && 3460 !InitializationHasSideEffects(*FD)) 3461 UnusedPrivateFields.insert(FD); 3462 } 3463 } 3464 3465 return Member; 3466 } 3467 3468 namespace { 3469 class UninitializedFieldVisitor 3470 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 3471 Sema &S; 3472 // List of Decls to generate a warning on. Also remove Decls that become 3473 // initialized. 3474 llvm::SmallPtrSetImpl<ValueDecl*> &Decls; 3475 // List of base classes of the record. Classes are removed after their 3476 // initializers. 3477 llvm::SmallPtrSetImpl<QualType> &BaseClasses; 3478 // Vector of decls to be removed from the Decl set prior to visiting the 3479 // nodes. These Decls may have been initialized in the prior initializer. 3480 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; 3481 // If non-null, add a note to the warning pointing back to the constructor. 3482 const CXXConstructorDecl *Constructor; 3483 // Variables to hold state when processing an initializer list. When 3484 // InitList is true, special case initialization of FieldDecls matching 3485 // InitListFieldDecl. 3486 bool InitList; 3487 FieldDecl *InitListFieldDecl; 3488 llvm::SmallVector<unsigned, 4> InitFieldIndex; 3489 3490 public: 3491 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 3492 UninitializedFieldVisitor(Sema &S, 3493 llvm::SmallPtrSetImpl<ValueDecl*> &Decls, 3494 llvm::SmallPtrSetImpl<QualType> &BaseClasses) 3495 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), 3496 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} 3497 3498 // Returns true if the use of ME is not an uninitialized use. 3499 bool IsInitListMemberExprInitialized(MemberExpr *ME, 3500 bool CheckReferenceOnly) { 3501 llvm::SmallVector<FieldDecl*, 4> Fields; 3502 bool ReferenceField = false; 3503 while (ME) { 3504 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 3505 if (!FD) 3506 return false; 3507 Fields.push_back(FD); 3508 if (FD->getType()->isReferenceType()) 3509 ReferenceField = true; 3510 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); 3511 } 3512 3513 // Binding a reference to an uninitialized field is not an 3514 // uninitialized use. 3515 if (CheckReferenceOnly && !ReferenceField) 3516 return true; 3517 3518 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 3519 // Discard the first field since it is the field decl that is being 3520 // initialized. 3521 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) { 3522 UsedFieldIndex.push_back((*I)->getFieldIndex()); 3523 } 3524 3525 for (auto UsedIter = UsedFieldIndex.begin(), 3526 UsedEnd = UsedFieldIndex.end(), 3527 OrigIter = InitFieldIndex.begin(), 3528 OrigEnd = InitFieldIndex.end(); 3529 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 3530 if (*UsedIter < *OrigIter) 3531 return true; 3532 if (*UsedIter > *OrigIter) 3533 break; 3534 } 3535 3536 return false; 3537 } 3538 3539 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, 3540 bool AddressOf) { 3541 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 3542 return; 3543 3544 // FieldME is the inner-most MemberExpr that is not an anonymous struct 3545 // or union. 3546 MemberExpr *FieldME = ME; 3547 3548 bool AllPODFields = FieldME->getType().isPODType(S.Context); 3549 3550 Expr *Base = ME; 3551 while (MemberExpr *SubME = 3552 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { 3553 3554 if (isa<VarDecl>(SubME->getMemberDecl())) 3555 return; 3556 3557 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) 3558 if (!FD->isAnonymousStructOrUnion()) 3559 FieldME = SubME; 3560 3561 if (!FieldME->getType().isPODType(S.Context)) 3562 AllPODFields = false; 3563 3564 Base = SubME->getBase(); 3565 } 3566 3567 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) 3568 return; 3569 3570 if (AddressOf && AllPODFields) 3571 return; 3572 3573 ValueDecl* FoundVD = FieldME->getMemberDecl(); 3574 3575 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { 3576 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { 3577 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); 3578 } 3579 3580 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { 3581 QualType T = BaseCast->getType(); 3582 if (T->isPointerType() && 3583 BaseClasses.count(T->getPointeeType())) { 3584 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) 3585 << T->getPointeeType() << FoundVD; 3586 } 3587 } 3588 } 3589 3590 if (!Decls.count(FoundVD)) 3591 return; 3592 3593 const bool IsReference = FoundVD->getType()->isReferenceType(); 3594 3595 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { 3596 // Special checking for initializer lists. 3597 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { 3598 return; 3599 } 3600 } else { 3601 // Prevent double warnings on use of unbounded references. 3602 if (CheckReferenceOnly && !IsReference) 3603 return; 3604 } 3605 3606 unsigned diag = IsReference 3607 ? diag::warn_reference_field_is_uninit 3608 : diag::warn_field_is_uninit; 3609 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 3610 if (Constructor) 3611 S.Diag(Constructor->getLocation(), 3612 diag::note_uninit_in_this_constructor) 3613 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 3614 3615 } 3616 3617 void HandleValue(Expr *E, bool AddressOf) { 3618 E = E->IgnoreParens(); 3619 3620 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3621 HandleMemberExpr(ME, false /*CheckReferenceOnly*/, 3622 AddressOf /*AddressOf*/); 3623 return; 3624 } 3625 3626 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 3627 Visit(CO->getCond()); 3628 HandleValue(CO->getTrueExpr(), AddressOf); 3629 HandleValue(CO->getFalseExpr(), AddressOf); 3630 return; 3631 } 3632 3633 if (BinaryConditionalOperator *BCO = 3634 dyn_cast<BinaryConditionalOperator>(E)) { 3635 Visit(BCO->getCond()); 3636 HandleValue(BCO->getFalseExpr(), AddressOf); 3637 return; 3638 } 3639 3640 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 3641 HandleValue(OVE->getSourceExpr(), AddressOf); 3642 return; 3643 } 3644 3645 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 3646 switch (BO->getOpcode()) { 3647 default: 3648 break; 3649 case(BO_PtrMemD): 3650 case(BO_PtrMemI): 3651 HandleValue(BO->getLHS(), AddressOf); 3652 Visit(BO->getRHS()); 3653 return; 3654 case(BO_Comma): 3655 Visit(BO->getLHS()); 3656 HandleValue(BO->getRHS(), AddressOf); 3657 return; 3658 } 3659 } 3660 3661 Visit(E); 3662 } 3663 3664 void CheckInitListExpr(InitListExpr *ILE) { 3665 InitFieldIndex.push_back(0); 3666 for (auto Child : ILE->children()) { 3667 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { 3668 CheckInitListExpr(SubList); 3669 } else { 3670 Visit(Child); 3671 } 3672 ++InitFieldIndex.back(); 3673 } 3674 InitFieldIndex.pop_back(); 3675 } 3676 3677 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, 3678 FieldDecl *Field, const Type *BaseClass) { 3679 // Remove Decls that may have been initialized in the previous 3680 // initializer. 3681 for (ValueDecl* VD : DeclsToRemove) 3682 Decls.erase(VD); 3683 DeclsToRemove.clear(); 3684 3685 Constructor = FieldConstructor; 3686 InitListExpr *ILE = dyn_cast<InitListExpr>(E); 3687 3688 if (ILE && Field) { 3689 InitList = true; 3690 InitListFieldDecl = Field; 3691 InitFieldIndex.clear(); 3692 CheckInitListExpr(ILE); 3693 } else { 3694 InitList = false; 3695 Visit(E); 3696 } 3697 3698 if (Field) 3699 Decls.erase(Field); 3700 if (BaseClass) 3701 BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); 3702 } 3703 3704 void VisitMemberExpr(MemberExpr *ME) { 3705 // All uses of unbounded reference fields will warn. 3706 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); 3707 } 3708 3709 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 3710 if (E->getCastKind() == CK_LValueToRValue) { 3711 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3712 return; 3713 } 3714 3715 Inherited::VisitImplicitCastExpr(E); 3716 } 3717 3718 void VisitCXXConstructExpr(CXXConstructExpr *E) { 3719 if (E->getConstructor()->isCopyConstructor()) { 3720 Expr *ArgExpr = E->getArg(0); 3721 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 3722 if (ILE->getNumInits() == 1) 3723 ArgExpr = ILE->getInit(0); 3724 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 3725 if (ICE->getCastKind() == CK_NoOp) 3726 ArgExpr = ICE->getSubExpr(); 3727 HandleValue(ArgExpr, false /*AddressOf*/); 3728 return; 3729 } 3730 Inherited::VisitCXXConstructExpr(E); 3731 } 3732 3733 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 3734 Expr *Callee = E->getCallee(); 3735 if (isa<MemberExpr>(Callee)) { 3736 HandleValue(Callee, false /*AddressOf*/); 3737 for (auto Arg : E->arguments()) 3738 Visit(Arg); 3739 return; 3740 } 3741 3742 Inherited::VisitCXXMemberCallExpr(E); 3743 } 3744 3745 void VisitCallExpr(CallExpr *E) { 3746 // Treat std::move as a use. 3747 if (E->isCallToStdMove()) { 3748 HandleValue(E->getArg(0), /*AddressOf=*/false); 3749 return; 3750 } 3751 3752 Inherited::VisitCallExpr(E); 3753 } 3754 3755 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 3756 Expr *Callee = E->getCallee(); 3757 3758 if (isa<UnresolvedLookupExpr>(Callee)) 3759 return Inherited::VisitCXXOperatorCallExpr(E); 3760 3761 Visit(Callee); 3762 for (auto Arg : E->arguments()) 3763 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); 3764 } 3765 3766 void VisitBinaryOperator(BinaryOperator *E) { 3767 // If a field assignment is detected, remove the field from the 3768 // uninitiailized field set. 3769 if (E->getOpcode() == BO_Assign) 3770 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 3771 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 3772 if (!FD->getType()->isReferenceType()) 3773 DeclsToRemove.push_back(FD); 3774 3775 if (E->isCompoundAssignmentOp()) { 3776 HandleValue(E->getLHS(), false /*AddressOf*/); 3777 Visit(E->getRHS()); 3778 return; 3779 } 3780 3781 Inherited::VisitBinaryOperator(E); 3782 } 3783 3784 void VisitUnaryOperator(UnaryOperator *E) { 3785 if (E->isIncrementDecrementOp()) { 3786 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3787 return; 3788 } 3789 if (E->getOpcode() == UO_AddrOf) { 3790 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { 3791 HandleValue(ME->getBase(), true /*AddressOf*/); 3792 return; 3793 } 3794 } 3795 3796 Inherited::VisitUnaryOperator(E); 3797 } 3798 }; 3799 3800 // Diagnose value-uses of fields to initialize themselves, e.g. 3801 // foo(foo) 3802 // where foo is not also a parameter to the constructor. 3803 // Also diagnose across field uninitialized use such as 3804 // x(y), y(x) 3805 // TODO: implement -Wuninitialized and fold this into that framework. 3806 static void DiagnoseUninitializedFields( 3807 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 3808 3809 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 3810 Constructor->getLocation())) { 3811 return; 3812 } 3813 3814 if (Constructor->isInvalidDecl()) 3815 return; 3816 3817 const CXXRecordDecl *RD = Constructor->getParent(); 3818 3819 if (RD->isDependentContext()) 3820 return; 3821 3822 // Holds fields that are uninitialized. 3823 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 3824 3825 // At the beginning, all fields are uninitialized. 3826 for (auto *I : RD->decls()) { 3827 if (auto *FD = dyn_cast<FieldDecl>(I)) { 3828 UninitializedFields.insert(FD); 3829 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 3830 UninitializedFields.insert(IFD->getAnonField()); 3831 } 3832 } 3833 3834 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; 3835 for (auto I : RD->bases()) 3836 UninitializedBaseClasses.insert(I.getType().getCanonicalType()); 3837 3838 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3839 return; 3840 3841 UninitializedFieldVisitor UninitializedChecker(SemaRef, 3842 UninitializedFields, 3843 UninitializedBaseClasses); 3844 3845 for (const auto *FieldInit : Constructor->inits()) { 3846 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3847 break; 3848 3849 Expr *InitExpr = FieldInit->getInit(); 3850 if (!InitExpr) 3851 continue; 3852 3853 if (CXXDefaultInitExpr *Default = 3854 dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 3855 InitExpr = Default->getExpr(); 3856 if (!InitExpr) 3857 continue; 3858 // In class initializers will point to the constructor. 3859 UninitializedChecker.CheckInitializer(InitExpr, Constructor, 3860 FieldInit->getAnyMember(), 3861 FieldInit->getBaseClass()); 3862 } else { 3863 UninitializedChecker.CheckInitializer(InitExpr, nullptr, 3864 FieldInit->getAnyMember(), 3865 FieldInit->getBaseClass()); 3866 } 3867 } 3868 } 3869 } // namespace 3870 3871 /// Enter a new C++ default initializer scope. After calling this, the 3872 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 3873 /// parsing or instantiating the initializer failed. 3874 void Sema::ActOnStartCXXInClassMemberInitializer() { 3875 // Create a synthetic function scope to represent the call to the constructor 3876 // that notionally surrounds a use of this initializer. 3877 PushFunctionScope(); 3878 } 3879 3880 void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) { 3881 if (!D.isFunctionDeclarator()) 3882 return; 3883 auto &FTI = D.getFunctionTypeInfo(); 3884 if (!FTI.Params) 3885 return; 3886 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params, 3887 FTI.NumParams)) { 3888 auto *ParamDecl = cast<NamedDecl>(Param.Param); 3889 if (ParamDecl->getDeclName()) 3890 PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false); 3891 } 3892 } 3893 3894 ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) { 3895 if (ConstraintExpr.isInvalid()) 3896 return ExprError(); 3897 return CorrectDelayedTyposInExpr(ConstraintExpr); 3898 } 3899 3900 /// This is invoked after parsing an in-class initializer for a 3901 /// non-static C++ class member, and after instantiating an in-class initializer 3902 /// in a class template. Such actions are deferred until the class is complete. 3903 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 3904 SourceLocation InitLoc, 3905 Expr *InitExpr) { 3906 // Pop the notional constructor scope we created earlier. 3907 PopFunctionScopeInfo(nullptr, D); 3908 3909 FieldDecl *FD = dyn_cast<FieldDecl>(D); 3910 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && 3911 "must set init style when field is created"); 3912 3913 if (!InitExpr) { 3914 D->setInvalidDecl(); 3915 if (FD) 3916 FD->removeInClassInitializer(); 3917 return; 3918 } 3919 3920 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 3921 FD->setInvalidDecl(); 3922 FD->removeInClassInitializer(); 3923 return; 3924 } 3925 3926 ExprResult Init = InitExpr; 3927 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 3928 InitializedEntity Entity = 3929 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD); 3930 InitializationKind Kind = 3931 FD->getInClassInitStyle() == ICIS_ListInit 3932 ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(), 3933 InitExpr->getBeginLoc(), 3934 InitExpr->getEndLoc()) 3935 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc); 3936 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 3937 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 3938 if (Init.isInvalid()) { 3939 FD->setInvalidDecl(); 3940 return; 3941 } 3942 } 3943 3944 // C++11 [class.base.init]p7: 3945 // The initialization of each base and member constitutes a 3946 // full-expression. 3947 Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false); 3948 if (Init.isInvalid()) { 3949 FD->setInvalidDecl(); 3950 return; 3951 } 3952 3953 InitExpr = Init.get(); 3954 3955 FD->setInClassInitializer(InitExpr); 3956 } 3957 3958 /// Find the direct and/or virtual base specifiers that 3959 /// correspond to the given base type, for use in base initialization 3960 /// within a constructor. 3961 static bool FindBaseInitializer(Sema &SemaRef, 3962 CXXRecordDecl *ClassDecl, 3963 QualType BaseType, 3964 const CXXBaseSpecifier *&DirectBaseSpec, 3965 const CXXBaseSpecifier *&VirtualBaseSpec) { 3966 // First, check for a direct base class. 3967 DirectBaseSpec = nullptr; 3968 for (const auto &Base : ClassDecl->bases()) { 3969 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 3970 // We found a direct base of this type. That's what we're 3971 // initializing. 3972 DirectBaseSpec = &Base; 3973 break; 3974 } 3975 } 3976 3977 // Check for a virtual base class. 3978 // FIXME: We might be able to short-circuit this if we know in advance that 3979 // there are no virtual bases. 3980 VirtualBaseSpec = nullptr; 3981 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 3982 // We haven't found a base yet; search the class hierarchy for a 3983 // virtual base class. 3984 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3985 /*DetectVirtual=*/false); 3986 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(), 3987 SemaRef.Context.getTypeDeclType(ClassDecl), 3988 BaseType, Paths)) { 3989 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 3990 Path != Paths.end(); ++Path) { 3991 if (Path->back().Base->isVirtual()) { 3992 VirtualBaseSpec = Path->back().Base; 3993 break; 3994 } 3995 } 3996 } 3997 } 3998 3999 return DirectBaseSpec || VirtualBaseSpec; 4000 } 4001 4002 /// Handle a C++ member initializer using braced-init-list syntax. 4003 MemInitResult 4004 Sema::ActOnMemInitializer(Decl *ConstructorD, 4005 Scope *S, 4006 CXXScopeSpec &SS, 4007 IdentifierInfo *MemberOrBase, 4008 ParsedType TemplateTypeTy, 4009 const DeclSpec &DS, 4010 SourceLocation IdLoc, 4011 Expr *InitList, 4012 SourceLocation EllipsisLoc) { 4013 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 4014 DS, IdLoc, InitList, 4015 EllipsisLoc); 4016 } 4017 4018 /// Handle a C++ member initializer using parentheses syntax. 4019 MemInitResult 4020 Sema::ActOnMemInitializer(Decl *ConstructorD, 4021 Scope *S, 4022 CXXScopeSpec &SS, 4023 IdentifierInfo *MemberOrBase, 4024 ParsedType TemplateTypeTy, 4025 const DeclSpec &DS, 4026 SourceLocation IdLoc, 4027 SourceLocation LParenLoc, 4028 ArrayRef<Expr *> Args, 4029 SourceLocation RParenLoc, 4030 SourceLocation EllipsisLoc) { 4031 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc); 4032 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 4033 DS, IdLoc, List, EllipsisLoc); 4034 } 4035 4036 namespace { 4037 4038 // Callback to only accept typo corrections that can be a valid C++ member 4039 // intializer: either a non-static field member or a base class. 4040 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback { 4041 public: 4042 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 4043 : ClassDecl(ClassDecl) {} 4044 4045 bool ValidateCandidate(const TypoCorrection &candidate) override { 4046 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 4047 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 4048 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 4049 return isa<TypeDecl>(ND); 4050 } 4051 return false; 4052 } 4053 4054 std::unique_ptr<CorrectionCandidateCallback> clone() override { 4055 return std::make_unique<MemInitializerValidatorCCC>(*this); 4056 } 4057 4058 private: 4059 CXXRecordDecl *ClassDecl; 4060 }; 4061 4062 } 4063 4064 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, 4065 CXXScopeSpec &SS, 4066 ParsedType TemplateTypeTy, 4067 IdentifierInfo *MemberOrBase) { 4068 if (SS.getScopeRep() || TemplateTypeTy) 4069 return nullptr; 4070 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase); 4071 if (Result.empty()) 4072 return nullptr; 4073 ValueDecl *Member; 4074 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 4075 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) 4076 return Member; 4077 return nullptr; 4078 } 4079 4080 /// Handle a C++ member initializer. 4081 MemInitResult 4082 Sema::BuildMemInitializer(Decl *ConstructorD, 4083 Scope *S, 4084 CXXScopeSpec &SS, 4085 IdentifierInfo *MemberOrBase, 4086 ParsedType TemplateTypeTy, 4087 const DeclSpec &DS, 4088 SourceLocation IdLoc, 4089 Expr *Init, 4090 SourceLocation EllipsisLoc) { 4091 ExprResult Res = CorrectDelayedTyposInExpr(Init); 4092 if (!Res.isUsable()) 4093 return true; 4094 Init = Res.get(); 4095 4096 if (!ConstructorD) 4097 return true; 4098 4099 AdjustDeclIfTemplate(ConstructorD); 4100 4101 CXXConstructorDecl *Constructor 4102 = dyn_cast<CXXConstructorDecl>(ConstructorD); 4103 if (!Constructor) { 4104 // The user wrote a constructor initializer on a function that is 4105 // not a C++ constructor. Ignore the error for now, because we may 4106 // have more member initializers coming; we'll diagnose it just 4107 // once in ActOnMemInitializers. 4108 return true; 4109 } 4110 4111 CXXRecordDecl *ClassDecl = Constructor->getParent(); 4112 4113 // C++ [class.base.init]p2: 4114 // Names in a mem-initializer-id are looked up in the scope of the 4115 // constructor's class and, if not found in that scope, are looked 4116 // up in the scope containing the constructor's definition. 4117 // [Note: if the constructor's class contains a member with the 4118 // same name as a direct or virtual base class of the class, a 4119 // mem-initializer-id naming the member or base class and composed 4120 // of a single identifier refers to the class member. A 4121 // mem-initializer-id for the hidden base class may be specified 4122 // using a qualified name. ] 4123 4124 // Look for a member, first. 4125 if (ValueDecl *Member = tryLookupCtorInitMemberDecl( 4126 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) { 4127 if (EllipsisLoc.isValid()) 4128 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 4129 << MemberOrBase 4130 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 4131 4132 return BuildMemberInitializer(Member, Init, IdLoc); 4133 } 4134 // It didn't name a member, so see if it names a class. 4135 QualType BaseType; 4136 TypeSourceInfo *TInfo = nullptr; 4137 4138 if (TemplateTypeTy) { 4139 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 4140 if (BaseType.isNull()) 4141 return true; 4142 } else if (DS.getTypeSpecType() == TST_decltype) { 4143 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 4144 } else if (DS.getTypeSpecType() == TST_decltype_auto) { 4145 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); 4146 return true; 4147 } else { 4148 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 4149 LookupParsedName(R, S, &SS); 4150 4151 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 4152 if (!TyD) { 4153 if (R.isAmbiguous()) return true; 4154 4155 // We don't want access-control diagnostics here. 4156 R.suppressDiagnostics(); 4157 4158 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 4159 bool NotUnknownSpecialization = false; 4160 DeclContext *DC = computeDeclContext(SS, false); 4161 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 4162 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 4163 4164 if (!NotUnknownSpecialization) { 4165 // When the scope specifier can refer to a member of an unknown 4166 // specialization, we take it as a type name. 4167 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 4168 SS.getWithLocInContext(Context), 4169 *MemberOrBase, IdLoc); 4170 if (BaseType.isNull()) 4171 return true; 4172 4173 TInfo = Context.CreateTypeSourceInfo(BaseType); 4174 DependentNameTypeLoc TL = 4175 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>(); 4176 if (!TL.isNull()) { 4177 TL.setNameLoc(IdLoc); 4178 TL.setElaboratedKeywordLoc(SourceLocation()); 4179 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4180 } 4181 4182 R.clear(); 4183 R.setLookupName(MemberOrBase); 4184 } 4185 } 4186 4187 // If no results were found, try to correct typos. 4188 TypoCorrection Corr; 4189 MemInitializerValidatorCCC CCC(ClassDecl); 4190 if (R.empty() && BaseType.isNull() && 4191 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 4192 CCC, CTK_ErrorRecovery, ClassDecl))) { 4193 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 4194 // We have found a non-static data member with a similar 4195 // name to what was typed; complain and initialize that 4196 // member. 4197 diagnoseTypo(Corr, 4198 PDiag(diag::err_mem_init_not_member_or_class_suggest) 4199 << MemberOrBase << true); 4200 return BuildMemberInitializer(Member, Init, IdLoc); 4201 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 4202 const CXXBaseSpecifier *DirectBaseSpec; 4203 const CXXBaseSpecifier *VirtualBaseSpec; 4204 if (FindBaseInitializer(*this, ClassDecl, 4205 Context.getTypeDeclType(Type), 4206 DirectBaseSpec, VirtualBaseSpec)) { 4207 // We have found a direct or virtual base class with a 4208 // similar name to what was typed; complain and initialize 4209 // that base class. 4210 diagnoseTypo(Corr, 4211 PDiag(diag::err_mem_init_not_member_or_class_suggest) 4212 << MemberOrBase << false, 4213 PDiag() /*Suppress note, we provide our own.*/); 4214 4215 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 4216 : VirtualBaseSpec; 4217 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here) 4218 << BaseSpec->getType() << BaseSpec->getSourceRange(); 4219 4220 TyD = Type; 4221 } 4222 } 4223 } 4224 4225 if (!TyD && BaseType.isNull()) { 4226 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 4227 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 4228 return true; 4229 } 4230 } 4231 4232 if (BaseType.isNull()) { 4233 BaseType = Context.getTypeDeclType(TyD); 4234 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); 4235 if (SS.isSet()) { 4236 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 4237 BaseType); 4238 TInfo = Context.CreateTypeSourceInfo(BaseType); 4239 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>(); 4240 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc); 4241 TL.setElaboratedKeywordLoc(SourceLocation()); 4242 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4243 } 4244 } 4245 } 4246 4247 if (!TInfo) 4248 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 4249 4250 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 4251 } 4252 4253 MemInitResult 4254 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 4255 SourceLocation IdLoc) { 4256 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 4257 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 4258 assert((DirectMember || IndirectMember) && 4259 "Member must be a FieldDecl or IndirectFieldDecl"); 4260 4261 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4262 return true; 4263 4264 if (Member->isInvalidDecl()) 4265 return true; 4266 4267 MultiExprArg Args; 4268 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4269 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4270 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 4271 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 4272 } else { 4273 // Template instantiation doesn't reconstruct ParenListExprs for us. 4274 Args = Init; 4275 } 4276 4277 SourceRange InitRange = Init->getSourceRange(); 4278 4279 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 4280 // Can't check initialization for a member of dependent type or when 4281 // any of the arguments are type-dependent expressions. 4282 DiscardCleanupsInEvaluationContext(); 4283 } else { 4284 bool InitList = false; 4285 if (isa<InitListExpr>(Init)) { 4286 InitList = true; 4287 Args = Init; 4288 } 4289 4290 // Initialize the member. 4291 InitializedEntity MemberEntity = 4292 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 4293 : InitializedEntity::InitializeMember(IndirectMember, 4294 nullptr); 4295 InitializationKind Kind = 4296 InitList ? InitializationKind::CreateDirectList( 4297 IdLoc, Init->getBeginLoc(), Init->getEndLoc()) 4298 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 4299 InitRange.getEnd()); 4300 4301 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 4302 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 4303 nullptr); 4304 if (MemberInit.isInvalid()) 4305 return true; 4306 4307 // C++11 [class.base.init]p7: 4308 // The initialization of each base and member constitutes a 4309 // full-expression. 4310 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(), 4311 /*DiscardedValue*/ false); 4312 if (MemberInit.isInvalid()) 4313 return true; 4314 4315 Init = MemberInit.get(); 4316 } 4317 4318 if (DirectMember) { 4319 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 4320 InitRange.getBegin(), Init, 4321 InitRange.getEnd()); 4322 } else { 4323 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 4324 InitRange.getBegin(), Init, 4325 InitRange.getEnd()); 4326 } 4327 } 4328 4329 MemInitResult 4330 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 4331 CXXRecordDecl *ClassDecl) { 4332 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4333 if (!LangOpts.CPlusPlus11) 4334 return Diag(NameLoc, diag::err_delegating_ctor) 4335 << TInfo->getTypeLoc().getLocalSourceRange(); 4336 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 4337 4338 bool InitList = true; 4339 MultiExprArg Args = Init; 4340 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4341 InitList = false; 4342 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4343 } 4344 4345 SourceRange InitRange = Init->getSourceRange(); 4346 // Initialize the object. 4347 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 4348 QualType(ClassDecl->getTypeForDecl(), 0)); 4349 InitializationKind Kind = 4350 InitList ? InitializationKind::CreateDirectList( 4351 NameLoc, Init->getBeginLoc(), Init->getEndLoc()) 4352 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 4353 InitRange.getEnd()); 4354 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 4355 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 4356 Args, nullptr); 4357 if (DelegationInit.isInvalid()) 4358 return true; 4359 4360 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 4361 "Delegating constructor with no target?"); 4362 4363 // C++11 [class.base.init]p7: 4364 // The initialization of each base and member constitutes a 4365 // full-expression. 4366 DelegationInit = ActOnFinishFullExpr( 4367 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false); 4368 if (DelegationInit.isInvalid()) 4369 return true; 4370 4371 // If we are in a dependent context, template instantiation will 4372 // perform this type-checking again. Just save the arguments that we 4373 // received in a ParenListExpr. 4374 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4375 // of the information that we have about the base 4376 // initializer. However, deconstructing the ASTs is a dicey process, 4377 // and this approach is far more likely to get the corner cases right. 4378 if (CurContext->isDependentContext()) 4379 DelegationInit = Init; 4380 4381 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 4382 DelegationInit.getAs<Expr>(), 4383 InitRange.getEnd()); 4384 } 4385 4386 MemInitResult 4387 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 4388 Expr *Init, CXXRecordDecl *ClassDecl, 4389 SourceLocation EllipsisLoc) { 4390 SourceLocation BaseLoc 4391 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4392 4393 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 4394 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 4395 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4396 4397 // C++ [class.base.init]p2: 4398 // [...] Unless the mem-initializer-id names a nonstatic data 4399 // member of the constructor's class or a direct or virtual base 4400 // of that class, the mem-initializer is ill-formed. A 4401 // mem-initializer-list can initialize a base class using any 4402 // name that denotes that base class type. 4403 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 4404 4405 SourceRange InitRange = Init->getSourceRange(); 4406 if (EllipsisLoc.isValid()) { 4407 // This is a pack expansion. 4408 if (!BaseType->containsUnexpandedParameterPack()) { 4409 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 4410 << SourceRange(BaseLoc, InitRange.getEnd()); 4411 4412 EllipsisLoc = SourceLocation(); 4413 } 4414 } else { 4415 // Check for any unexpanded parameter packs. 4416 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 4417 return true; 4418 4419 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4420 return true; 4421 } 4422 4423 // Check for direct and virtual base classes. 4424 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 4425 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 4426 if (!Dependent) { 4427 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 4428 BaseType)) 4429 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 4430 4431 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 4432 VirtualBaseSpec); 4433 4434 // C++ [base.class.init]p2: 4435 // Unless the mem-initializer-id names a nonstatic data member of the 4436 // constructor's class or a direct or virtual base of that class, the 4437 // mem-initializer is ill-formed. 4438 if (!DirectBaseSpec && !VirtualBaseSpec) { 4439 // If the class has any dependent bases, then it's possible that 4440 // one of those types will resolve to the same type as 4441 // BaseType. Therefore, just treat this as a dependent base 4442 // class initialization. FIXME: Should we try to check the 4443 // initialization anyway? It seems odd. 4444 if (ClassDecl->hasAnyDependentBases()) 4445 Dependent = true; 4446 else 4447 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 4448 << BaseType << Context.getTypeDeclType(ClassDecl) 4449 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4450 } 4451 } 4452 4453 if (Dependent) { 4454 DiscardCleanupsInEvaluationContext(); 4455 4456 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4457 /*IsVirtual=*/false, 4458 InitRange.getBegin(), Init, 4459 InitRange.getEnd(), EllipsisLoc); 4460 } 4461 4462 // C++ [base.class.init]p2: 4463 // If a mem-initializer-id is ambiguous because it designates both 4464 // a direct non-virtual base class and an inherited virtual base 4465 // class, the mem-initializer is ill-formed. 4466 if (DirectBaseSpec && VirtualBaseSpec) 4467 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 4468 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4469 4470 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 4471 if (!BaseSpec) 4472 BaseSpec = VirtualBaseSpec; 4473 4474 // Initialize the base. 4475 bool InitList = true; 4476 MultiExprArg Args = Init; 4477 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4478 InitList = false; 4479 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4480 } 4481 4482 InitializedEntity BaseEntity = 4483 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 4484 InitializationKind Kind = 4485 InitList ? InitializationKind::CreateDirectList(BaseLoc) 4486 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 4487 InitRange.getEnd()); 4488 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 4489 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 4490 if (BaseInit.isInvalid()) 4491 return true; 4492 4493 // C++11 [class.base.init]p7: 4494 // The initialization of each base and member constitutes a 4495 // full-expression. 4496 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(), 4497 /*DiscardedValue*/ false); 4498 if (BaseInit.isInvalid()) 4499 return true; 4500 4501 // If we are in a dependent context, template instantiation will 4502 // perform this type-checking again. Just save the arguments that we 4503 // received in a ParenListExpr. 4504 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4505 // of the information that we have about the base 4506 // initializer. However, deconstructing the ASTs is a dicey process, 4507 // and this approach is far more likely to get the corner cases right. 4508 if (CurContext->isDependentContext()) 4509 BaseInit = Init; 4510 4511 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4512 BaseSpec->isVirtual(), 4513 InitRange.getBegin(), 4514 BaseInit.getAs<Expr>(), 4515 InitRange.getEnd(), EllipsisLoc); 4516 } 4517 4518 // Create a static_cast\<T&&>(expr). 4519 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 4520 if (T.isNull()) T = E->getType(); 4521 QualType TargetType = SemaRef.BuildReferenceType( 4522 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 4523 SourceLocation ExprLoc = E->getBeginLoc(); 4524 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 4525 TargetType, ExprLoc); 4526 4527 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 4528 SourceRange(ExprLoc, ExprLoc), 4529 E->getSourceRange()).get(); 4530 } 4531 4532 /// ImplicitInitializerKind - How an implicit base or member initializer should 4533 /// initialize its base or member. 4534 enum ImplicitInitializerKind { 4535 IIK_Default, 4536 IIK_Copy, 4537 IIK_Move, 4538 IIK_Inherit 4539 }; 4540 4541 static bool 4542 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4543 ImplicitInitializerKind ImplicitInitKind, 4544 CXXBaseSpecifier *BaseSpec, 4545 bool IsInheritedVirtualBase, 4546 CXXCtorInitializer *&CXXBaseInit) { 4547 InitializedEntity InitEntity 4548 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 4549 IsInheritedVirtualBase); 4550 4551 ExprResult BaseInit; 4552 4553 switch (ImplicitInitKind) { 4554 case IIK_Inherit: 4555 case IIK_Default: { 4556 InitializationKind InitKind 4557 = InitializationKind::CreateDefault(Constructor->getLocation()); 4558 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4559 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4560 break; 4561 } 4562 4563 case IIK_Move: 4564 case IIK_Copy: { 4565 bool Moving = ImplicitInitKind == IIK_Move; 4566 ParmVarDecl *Param = Constructor->getParamDecl(0); 4567 QualType ParamType = Param->getType().getNonReferenceType(); 4568 4569 Expr *CopyCtorArg = 4570 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4571 SourceLocation(), Param, false, 4572 Constructor->getLocation(), ParamType, 4573 VK_LValue, nullptr); 4574 4575 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 4576 4577 // Cast to the base class to avoid ambiguities. 4578 QualType ArgTy = 4579 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 4580 ParamType.getQualifiers()); 4581 4582 if (Moving) { 4583 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 4584 } 4585 4586 CXXCastPath BasePath; 4587 BasePath.push_back(BaseSpec); 4588 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 4589 CK_UncheckedDerivedToBase, 4590 Moving ? VK_XValue : VK_LValue, 4591 &BasePath).get(); 4592 4593 InitializationKind InitKind 4594 = InitializationKind::CreateDirect(Constructor->getLocation(), 4595 SourceLocation(), SourceLocation()); 4596 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 4597 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 4598 break; 4599 } 4600 } 4601 4602 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 4603 if (BaseInit.isInvalid()) 4604 return true; 4605 4606 CXXBaseInit = 4607 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4608 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 4609 SourceLocation()), 4610 BaseSpec->isVirtual(), 4611 SourceLocation(), 4612 BaseInit.getAs<Expr>(), 4613 SourceLocation(), 4614 SourceLocation()); 4615 4616 return false; 4617 } 4618 4619 static bool RefersToRValueRef(Expr *MemRef) { 4620 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 4621 return Referenced->getType()->isRValueReferenceType(); 4622 } 4623 4624 static bool 4625 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4626 ImplicitInitializerKind ImplicitInitKind, 4627 FieldDecl *Field, IndirectFieldDecl *Indirect, 4628 CXXCtorInitializer *&CXXMemberInit) { 4629 if (Field->isInvalidDecl()) 4630 return true; 4631 4632 SourceLocation Loc = Constructor->getLocation(); 4633 4634 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 4635 bool Moving = ImplicitInitKind == IIK_Move; 4636 ParmVarDecl *Param = Constructor->getParamDecl(0); 4637 QualType ParamType = Param->getType().getNonReferenceType(); 4638 4639 // Suppress copying zero-width bitfields. 4640 if (Field->isZeroLengthBitField(SemaRef.Context)) 4641 return false; 4642 4643 Expr *MemberExprBase = 4644 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4645 SourceLocation(), Param, false, 4646 Loc, ParamType, VK_LValue, nullptr); 4647 4648 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 4649 4650 if (Moving) { 4651 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 4652 } 4653 4654 // Build a reference to this field within the parameter. 4655 CXXScopeSpec SS; 4656 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 4657 Sema::LookupMemberName); 4658 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 4659 : cast<ValueDecl>(Field), AS_public); 4660 MemberLookup.resolveKind(); 4661 ExprResult CtorArg 4662 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 4663 ParamType, Loc, 4664 /*IsArrow=*/false, 4665 SS, 4666 /*TemplateKWLoc=*/SourceLocation(), 4667 /*FirstQualifierInScope=*/nullptr, 4668 MemberLookup, 4669 /*TemplateArgs=*/nullptr, 4670 /*S*/nullptr); 4671 if (CtorArg.isInvalid()) 4672 return true; 4673 4674 // C++11 [class.copy]p15: 4675 // - if a member m has rvalue reference type T&&, it is direct-initialized 4676 // with static_cast<T&&>(x.m); 4677 if (RefersToRValueRef(CtorArg.get())) { 4678 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 4679 } 4680 4681 InitializedEntity Entity = 4682 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4683 /*Implicit*/ true) 4684 : InitializedEntity::InitializeMember(Field, nullptr, 4685 /*Implicit*/ true); 4686 4687 // Direct-initialize to use the copy constructor. 4688 InitializationKind InitKind = 4689 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 4690 4691 Expr *CtorArgE = CtorArg.getAs<Expr>(); 4692 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE); 4693 ExprResult MemberInit = 4694 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1)); 4695 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4696 if (MemberInit.isInvalid()) 4697 return true; 4698 4699 if (Indirect) 4700 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4701 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4702 else 4703 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4704 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4705 return false; 4706 } 4707 4708 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 4709 "Unhandled implicit init kind!"); 4710 4711 QualType FieldBaseElementType = 4712 SemaRef.Context.getBaseElementType(Field->getType()); 4713 4714 if (FieldBaseElementType->isRecordType()) { 4715 InitializedEntity InitEntity = 4716 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4717 /*Implicit*/ true) 4718 : InitializedEntity::InitializeMember(Field, nullptr, 4719 /*Implicit*/ true); 4720 InitializationKind InitKind = 4721 InitializationKind::CreateDefault(Loc); 4722 4723 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4724 ExprResult MemberInit = 4725 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4726 4727 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4728 if (MemberInit.isInvalid()) 4729 return true; 4730 4731 if (Indirect) 4732 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4733 Indirect, Loc, 4734 Loc, 4735 MemberInit.get(), 4736 Loc); 4737 else 4738 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4739 Field, Loc, Loc, 4740 MemberInit.get(), 4741 Loc); 4742 return false; 4743 } 4744 4745 if (!Field->getParent()->isUnion()) { 4746 if (FieldBaseElementType->isReferenceType()) { 4747 SemaRef.Diag(Constructor->getLocation(), 4748 diag::err_uninitialized_member_in_ctor) 4749 << (int)Constructor->isImplicit() 4750 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4751 << 0 << Field->getDeclName(); 4752 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4753 return true; 4754 } 4755 4756 if (FieldBaseElementType.isConstQualified()) { 4757 SemaRef.Diag(Constructor->getLocation(), 4758 diag::err_uninitialized_member_in_ctor) 4759 << (int)Constructor->isImplicit() 4760 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4761 << 1 << Field->getDeclName(); 4762 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4763 return true; 4764 } 4765 } 4766 4767 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) { 4768 // ARC and Weak: 4769 // Default-initialize Objective-C pointers to NULL. 4770 CXXMemberInit 4771 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 4772 Loc, Loc, 4773 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 4774 Loc); 4775 return false; 4776 } 4777 4778 // Nothing to initialize. 4779 CXXMemberInit = nullptr; 4780 return false; 4781 } 4782 4783 namespace { 4784 struct BaseAndFieldInfo { 4785 Sema &S; 4786 CXXConstructorDecl *Ctor; 4787 bool AnyErrorsInInits; 4788 ImplicitInitializerKind IIK; 4789 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 4790 SmallVector<CXXCtorInitializer*, 8> AllToInit; 4791 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 4792 4793 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 4794 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 4795 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 4796 if (Ctor->getInheritedConstructor()) 4797 IIK = IIK_Inherit; 4798 else if (Generated && Ctor->isCopyConstructor()) 4799 IIK = IIK_Copy; 4800 else if (Generated && Ctor->isMoveConstructor()) 4801 IIK = IIK_Move; 4802 else 4803 IIK = IIK_Default; 4804 } 4805 4806 bool isImplicitCopyOrMove() const { 4807 switch (IIK) { 4808 case IIK_Copy: 4809 case IIK_Move: 4810 return true; 4811 4812 case IIK_Default: 4813 case IIK_Inherit: 4814 return false; 4815 } 4816 4817 llvm_unreachable("Invalid ImplicitInitializerKind!"); 4818 } 4819 4820 bool addFieldInitializer(CXXCtorInitializer *Init) { 4821 AllToInit.push_back(Init); 4822 4823 // Check whether this initializer makes the field "used". 4824 if (Init->getInit()->HasSideEffects(S.Context)) 4825 S.UnusedPrivateFields.remove(Init->getAnyMember()); 4826 4827 return false; 4828 } 4829 4830 bool isInactiveUnionMember(FieldDecl *Field) { 4831 RecordDecl *Record = Field->getParent(); 4832 if (!Record->isUnion()) 4833 return false; 4834 4835 if (FieldDecl *Active = 4836 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 4837 return Active != Field->getCanonicalDecl(); 4838 4839 // In an implicit copy or move constructor, ignore any in-class initializer. 4840 if (isImplicitCopyOrMove()) 4841 return true; 4842 4843 // If there's no explicit initialization, the field is active only if it 4844 // has an in-class initializer... 4845 if (Field->hasInClassInitializer()) 4846 return false; 4847 // ... or it's an anonymous struct or union whose class has an in-class 4848 // initializer. 4849 if (!Field->isAnonymousStructOrUnion()) 4850 return true; 4851 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 4852 return !FieldRD->hasInClassInitializer(); 4853 } 4854 4855 /// Determine whether the given field is, or is within, a union member 4856 /// that is inactive (because there was an initializer given for a different 4857 /// member of the union, or because the union was not initialized at all). 4858 bool isWithinInactiveUnionMember(FieldDecl *Field, 4859 IndirectFieldDecl *Indirect) { 4860 if (!Indirect) 4861 return isInactiveUnionMember(Field); 4862 4863 for (auto *C : Indirect->chain()) { 4864 FieldDecl *Field = dyn_cast<FieldDecl>(C); 4865 if (Field && isInactiveUnionMember(Field)) 4866 return true; 4867 } 4868 return false; 4869 } 4870 }; 4871 } 4872 4873 /// Determine whether the given type is an incomplete or zero-lenfgth 4874 /// array type. 4875 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 4876 if (T->isIncompleteArrayType()) 4877 return true; 4878 4879 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 4880 if (!ArrayT->getSize()) 4881 return true; 4882 4883 T = ArrayT->getElementType(); 4884 } 4885 4886 return false; 4887 } 4888 4889 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 4890 FieldDecl *Field, 4891 IndirectFieldDecl *Indirect = nullptr) { 4892 if (Field->isInvalidDecl()) 4893 return false; 4894 4895 // Overwhelmingly common case: we have a direct initializer for this field. 4896 if (CXXCtorInitializer *Init = 4897 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 4898 return Info.addFieldInitializer(Init); 4899 4900 // C++11 [class.base.init]p8: 4901 // if the entity is a non-static data member that has a 4902 // brace-or-equal-initializer and either 4903 // -- the constructor's class is a union and no other variant member of that 4904 // union is designated by a mem-initializer-id or 4905 // -- the constructor's class is not a union, and, if the entity is a member 4906 // of an anonymous union, no other member of that union is designated by 4907 // a mem-initializer-id, 4908 // the entity is initialized as specified in [dcl.init]. 4909 // 4910 // We also apply the same rules to handle anonymous structs within anonymous 4911 // unions. 4912 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 4913 return false; 4914 4915 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 4916 ExprResult DIE = 4917 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); 4918 if (DIE.isInvalid()) 4919 return true; 4920 4921 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true); 4922 SemaRef.checkInitializerLifetime(Entity, DIE.get()); 4923 4924 CXXCtorInitializer *Init; 4925 if (Indirect) 4926 Init = new (SemaRef.Context) 4927 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), 4928 SourceLocation(), DIE.get(), SourceLocation()); 4929 else 4930 Init = new (SemaRef.Context) 4931 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), 4932 SourceLocation(), DIE.get(), SourceLocation()); 4933 return Info.addFieldInitializer(Init); 4934 } 4935 4936 // Don't initialize incomplete or zero-length arrays. 4937 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 4938 return false; 4939 4940 // Don't try to build an implicit initializer if there were semantic 4941 // errors in any of the initializers (and therefore we might be 4942 // missing some that the user actually wrote). 4943 if (Info.AnyErrorsInInits) 4944 return false; 4945 4946 CXXCtorInitializer *Init = nullptr; 4947 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 4948 Indirect, Init)) 4949 return true; 4950 4951 if (!Init) 4952 return false; 4953 4954 return Info.addFieldInitializer(Init); 4955 } 4956 4957 bool 4958 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 4959 CXXCtorInitializer *Initializer) { 4960 assert(Initializer->isDelegatingInitializer()); 4961 Constructor->setNumCtorInitializers(1); 4962 CXXCtorInitializer **initializer = 4963 new (Context) CXXCtorInitializer*[1]; 4964 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 4965 Constructor->setCtorInitializers(initializer); 4966 4967 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 4968 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 4969 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 4970 } 4971 4972 DelegatingCtorDecls.push_back(Constructor); 4973 4974 DiagnoseUninitializedFields(*this, Constructor); 4975 4976 return false; 4977 } 4978 4979 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 4980 ArrayRef<CXXCtorInitializer *> Initializers) { 4981 if (Constructor->isDependentContext()) { 4982 // Just store the initializers as written, they will be checked during 4983 // instantiation. 4984 if (!Initializers.empty()) { 4985 Constructor->setNumCtorInitializers(Initializers.size()); 4986 CXXCtorInitializer **baseOrMemberInitializers = 4987 new (Context) CXXCtorInitializer*[Initializers.size()]; 4988 memcpy(baseOrMemberInitializers, Initializers.data(), 4989 Initializers.size() * sizeof(CXXCtorInitializer*)); 4990 Constructor->setCtorInitializers(baseOrMemberInitializers); 4991 } 4992 4993 // Let template instantiation know whether we had errors. 4994 if (AnyErrors) 4995 Constructor->setInvalidDecl(); 4996 4997 return false; 4998 } 4999 5000 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 5001 5002 // We need to build the initializer AST according to order of construction 5003 // and not what user specified in the Initializers list. 5004 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 5005 if (!ClassDecl) 5006 return true; 5007 5008 bool HadError = false; 5009 5010 for (unsigned i = 0; i < Initializers.size(); i++) { 5011 CXXCtorInitializer *Member = Initializers[i]; 5012 5013 if (Member->isBaseInitializer()) 5014 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 5015 else { 5016 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 5017 5018 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 5019 for (auto *C : F->chain()) { 5020 FieldDecl *FD = dyn_cast<FieldDecl>(C); 5021 if (FD && FD->getParent()->isUnion()) 5022 Info.ActiveUnionMember.insert(std::make_pair( 5023 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 5024 } 5025 } else if (FieldDecl *FD = Member->getMember()) { 5026 if (FD->getParent()->isUnion()) 5027 Info.ActiveUnionMember.insert(std::make_pair( 5028 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 5029 } 5030 } 5031 } 5032 5033 // Keep track of the direct virtual bases. 5034 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 5035 for (auto &I : ClassDecl->bases()) { 5036 if (I.isVirtual()) 5037 DirectVBases.insert(&I); 5038 } 5039 5040 // Push virtual bases before others. 5041 for (auto &VBase : ClassDecl->vbases()) { 5042 if (CXXCtorInitializer *Value 5043 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 5044 // [class.base.init]p7, per DR257: 5045 // A mem-initializer where the mem-initializer-id names a virtual base 5046 // class is ignored during execution of a constructor of any class that 5047 // is not the most derived class. 5048 if (ClassDecl->isAbstract()) { 5049 // FIXME: Provide a fixit to remove the base specifier. This requires 5050 // tracking the location of the associated comma for a base specifier. 5051 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 5052 << VBase.getType() << ClassDecl; 5053 DiagnoseAbstractType(ClassDecl); 5054 } 5055 5056 Info.AllToInit.push_back(Value); 5057 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 5058 // [class.base.init]p8, per DR257: 5059 // If a given [...] base class is not named by a mem-initializer-id 5060 // [...] and the entity is not a virtual base class of an abstract 5061 // class, then [...] the entity is default-initialized. 5062 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 5063 CXXCtorInitializer *CXXBaseInit; 5064 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 5065 &VBase, IsInheritedVirtualBase, 5066 CXXBaseInit)) { 5067 HadError = true; 5068 continue; 5069 } 5070 5071 Info.AllToInit.push_back(CXXBaseInit); 5072 } 5073 } 5074 5075 // Non-virtual bases. 5076 for (auto &Base : ClassDecl->bases()) { 5077 // Virtuals are in the virtual base list and already constructed. 5078 if (Base.isVirtual()) 5079 continue; 5080 5081 if (CXXCtorInitializer *Value 5082 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 5083 Info.AllToInit.push_back(Value); 5084 } else if (!AnyErrors) { 5085 CXXCtorInitializer *CXXBaseInit; 5086 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 5087 &Base, /*IsInheritedVirtualBase=*/false, 5088 CXXBaseInit)) { 5089 HadError = true; 5090 continue; 5091 } 5092 5093 Info.AllToInit.push_back(CXXBaseInit); 5094 } 5095 } 5096 5097 // Fields. 5098 for (auto *Mem : ClassDecl->decls()) { 5099 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 5100 // C++ [class.bit]p2: 5101 // A declaration for a bit-field that omits the identifier declares an 5102 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 5103 // initialized. 5104 if (F->isUnnamedBitfield()) 5105 continue; 5106 5107 // If we're not generating the implicit copy/move constructor, then we'll 5108 // handle anonymous struct/union fields based on their individual 5109 // indirect fields. 5110 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 5111 continue; 5112 5113 if (CollectFieldInitializer(*this, Info, F)) 5114 HadError = true; 5115 continue; 5116 } 5117 5118 // Beyond this point, we only consider default initialization. 5119 if (Info.isImplicitCopyOrMove()) 5120 continue; 5121 5122 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 5123 if (F->getType()->isIncompleteArrayType()) { 5124 assert(ClassDecl->hasFlexibleArrayMember() && 5125 "Incomplete array type is not valid"); 5126 continue; 5127 } 5128 5129 // Initialize each field of an anonymous struct individually. 5130 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 5131 HadError = true; 5132 5133 continue; 5134 } 5135 } 5136 5137 unsigned NumInitializers = Info.AllToInit.size(); 5138 if (NumInitializers > 0) { 5139 Constructor->setNumCtorInitializers(NumInitializers); 5140 CXXCtorInitializer **baseOrMemberInitializers = 5141 new (Context) CXXCtorInitializer*[NumInitializers]; 5142 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 5143 NumInitializers * sizeof(CXXCtorInitializer*)); 5144 Constructor->setCtorInitializers(baseOrMemberInitializers); 5145 5146 // Constructors implicitly reference the base and member 5147 // destructors. 5148 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 5149 Constructor->getParent()); 5150 } 5151 5152 return HadError; 5153 } 5154 5155 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 5156 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 5157 const RecordDecl *RD = RT->getDecl(); 5158 if (RD->isAnonymousStructOrUnion()) { 5159 for (auto *Field : RD->fields()) 5160 PopulateKeysForFields(Field, IdealInits); 5161 return; 5162 } 5163 } 5164 IdealInits.push_back(Field->getCanonicalDecl()); 5165 } 5166 5167 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 5168 return Context.getCanonicalType(BaseType).getTypePtr(); 5169 } 5170 5171 static const void *GetKeyForMember(ASTContext &Context, 5172 CXXCtorInitializer *Member) { 5173 if (!Member->isAnyMemberInitializer()) 5174 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 5175 5176 return Member->getAnyMember()->getCanonicalDecl(); 5177 } 5178 5179 static void DiagnoseBaseOrMemInitializerOrder( 5180 Sema &SemaRef, const CXXConstructorDecl *Constructor, 5181 ArrayRef<CXXCtorInitializer *> Inits) { 5182 if (Constructor->getDeclContext()->isDependentContext()) 5183 return; 5184 5185 // Don't check initializers order unless the warning is enabled at the 5186 // location of at least one initializer. 5187 bool ShouldCheckOrder = false; 5188 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 5189 CXXCtorInitializer *Init = Inits[InitIndex]; 5190 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 5191 Init->getSourceLocation())) { 5192 ShouldCheckOrder = true; 5193 break; 5194 } 5195 } 5196 if (!ShouldCheckOrder) 5197 return; 5198 5199 // Build the list of bases and members in the order that they'll 5200 // actually be initialized. The explicit initializers should be in 5201 // this same order but may be missing things. 5202 SmallVector<const void*, 32> IdealInitKeys; 5203 5204 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 5205 5206 // 1. Virtual bases. 5207 for (const auto &VBase : ClassDecl->vbases()) 5208 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 5209 5210 // 2. Non-virtual bases. 5211 for (const auto &Base : ClassDecl->bases()) { 5212 if (Base.isVirtual()) 5213 continue; 5214 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 5215 } 5216 5217 // 3. Direct fields. 5218 for (auto *Field : ClassDecl->fields()) { 5219 if (Field->isUnnamedBitfield()) 5220 continue; 5221 5222 PopulateKeysForFields(Field, IdealInitKeys); 5223 } 5224 5225 unsigned NumIdealInits = IdealInitKeys.size(); 5226 unsigned IdealIndex = 0; 5227 5228 CXXCtorInitializer *PrevInit = nullptr; 5229 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 5230 CXXCtorInitializer *Init = Inits[InitIndex]; 5231 const void *InitKey = GetKeyForMember(SemaRef.Context, Init); 5232 5233 // Scan forward to try to find this initializer in the idealized 5234 // initializers list. 5235 for (; IdealIndex != NumIdealInits; ++IdealIndex) 5236 if (InitKey == IdealInitKeys[IdealIndex]) 5237 break; 5238 5239 // If we didn't find this initializer, it must be because we 5240 // scanned past it on a previous iteration. That can only 5241 // happen if we're out of order; emit a warning. 5242 if (IdealIndex == NumIdealInits && PrevInit) { 5243 Sema::SemaDiagnosticBuilder D = 5244 SemaRef.Diag(PrevInit->getSourceLocation(), 5245 diag::warn_initializer_out_of_order); 5246 5247 if (PrevInit->isAnyMemberInitializer()) 5248 D << 0 << PrevInit->getAnyMember()->getDeclName(); 5249 else 5250 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 5251 5252 if (Init->isAnyMemberInitializer()) 5253 D << 0 << Init->getAnyMember()->getDeclName(); 5254 else 5255 D << 1 << Init->getTypeSourceInfo()->getType(); 5256 5257 // Move back to the initializer's location in the ideal list. 5258 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 5259 if (InitKey == IdealInitKeys[IdealIndex]) 5260 break; 5261 5262 assert(IdealIndex < NumIdealInits && 5263 "initializer not found in initializer list"); 5264 } 5265 5266 PrevInit = Init; 5267 } 5268 } 5269 5270 namespace { 5271 bool CheckRedundantInit(Sema &S, 5272 CXXCtorInitializer *Init, 5273 CXXCtorInitializer *&PrevInit) { 5274 if (!PrevInit) { 5275 PrevInit = Init; 5276 return false; 5277 } 5278 5279 if (FieldDecl *Field = Init->getAnyMember()) 5280 S.Diag(Init->getSourceLocation(), 5281 diag::err_multiple_mem_initialization) 5282 << Field->getDeclName() 5283 << Init->getSourceRange(); 5284 else { 5285 const Type *BaseClass = Init->getBaseClass(); 5286 assert(BaseClass && "neither field nor base"); 5287 S.Diag(Init->getSourceLocation(), 5288 diag::err_multiple_base_initialization) 5289 << QualType(BaseClass, 0) 5290 << Init->getSourceRange(); 5291 } 5292 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 5293 << 0 << PrevInit->getSourceRange(); 5294 5295 return true; 5296 } 5297 5298 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 5299 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 5300 5301 bool CheckRedundantUnionInit(Sema &S, 5302 CXXCtorInitializer *Init, 5303 RedundantUnionMap &Unions) { 5304 FieldDecl *Field = Init->getAnyMember(); 5305 RecordDecl *Parent = Field->getParent(); 5306 NamedDecl *Child = Field; 5307 5308 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 5309 if (Parent->isUnion()) { 5310 UnionEntry &En = Unions[Parent]; 5311 if (En.first && En.first != Child) { 5312 S.Diag(Init->getSourceLocation(), 5313 diag::err_multiple_mem_union_initialization) 5314 << Field->getDeclName() 5315 << Init->getSourceRange(); 5316 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 5317 << 0 << En.second->getSourceRange(); 5318 return true; 5319 } 5320 if (!En.first) { 5321 En.first = Child; 5322 En.second = Init; 5323 } 5324 if (!Parent->isAnonymousStructOrUnion()) 5325 return false; 5326 } 5327 5328 Child = Parent; 5329 Parent = cast<RecordDecl>(Parent->getDeclContext()); 5330 } 5331 5332 return false; 5333 } 5334 } 5335 5336 /// ActOnMemInitializers - Handle the member initializers for a constructor. 5337 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 5338 SourceLocation ColonLoc, 5339 ArrayRef<CXXCtorInitializer*> MemInits, 5340 bool AnyErrors) { 5341 if (!ConstructorDecl) 5342 return; 5343 5344 AdjustDeclIfTemplate(ConstructorDecl); 5345 5346 CXXConstructorDecl *Constructor 5347 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 5348 5349 if (!Constructor) { 5350 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 5351 return; 5352 } 5353 5354 // Mapping for the duplicate initializers check. 5355 // For member initializers, this is keyed with a FieldDecl*. 5356 // For base initializers, this is keyed with a Type*. 5357 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 5358 5359 // Mapping for the inconsistent anonymous-union initializers check. 5360 RedundantUnionMap MemberUnions; 5361 5362 bool HadError = false; 5363 for (unsigned i = 0; i < MemInits.size(); i++) { 5364 CXXCtorInitializer *Init = MemInits[i]; 5365 5366 // Set the source order index. 5367 Init->setSourceOrder(i); 5368 5369 if (Init->isAnyMemberInitializer()) { 5370 const void *Key = GetKeyForMember(Context, Init); 5371 if (CheckRedundantInit(*this, Init, Members[Key]) || 5372 CheckRedundantUnionInit(*this, Init, MemberUnions)) 5373 HadError = true; 5374 } else if (Init->isBaseInitializer()) { 5375 const void *Key = GetKeyForMember(Context, Init); 5376 if (CheckRedundantInit(*this, Init, Members[Key])) 5377 HadError = true; 5378 } else { 5379 assert(Init->isDelegatingInitializer()); 5380 // This must be the only initializer 5381 if (MemInits.size() != 1) { 5382 Diag(Init->getSourceLocation(), 5383 diag::err_delegating_initializer_alone) 5384 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 5385 // We will treat this as being the only initializer. 5386 } 5387 SetDelegatingInitializer(Constructor, MemInits[i]); 5388 // Return immediately as the initializer is set. 5389 return; 5390 } 5391 } 5392 5393 if (HadError) 5394 return; 5395 5396 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 5397 5398 SetCtorInitializers(Constructor, AnyErrors, MemInits); 5399 5400 DiagnoseUninitializedFields(*this, Constructor); 5401 } 5402 5403 void 5404 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 5405 CXXRecordDecl *ClassDecl) { 5406 // Ignore dependent contexts. Also ignore unions, since their members never 5407 // have destructors implicitly called. 5408 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 5409 return; 5410 5411 // FIXME: all the access-control diagnostics are positioned on the 5412 // field/base declaration. That's probably good; that said, the 5413 // user might reasonably want to know why the destructor is being 5414 // emitted, and we currently don't say. 5415 5416 // Non-static data members. 5417 for (auto *Field : ClassDecl->fields()) { 5418 if (Field->isInvalidDecl()) 5419 continue; 5420 5421 // Don't destroy incomplete or zero-length arrays. 5422 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 5423 continue; 5424 5425 QualType FieldType = Context.getBaseElementType(Field->getType()); 5426 5427 const RecordType* RT = FieldType->getAs<RecordType>(); 5428 if (!RT) 5429 continue; 5430 5431 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5432 if (FieldClassDecl->isInvalidDecl()) 5433 continue; 5434 if (FieldClassDecl->hasIrrelevantDestructor()) 5435 continue; 5436 // The destructor for an implicit anonymous union member is never invoked. 5437 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 5438 continue; 5439 5440 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 5441 assert(Dtor && "No dtor found for FieldClassDecl!"); 5442 CheckDestructorAccess(Field->getLocation(), Dtor, 5443 PDiag(diag::err_access_dtor_field) 5444 << Field->getDeclName() 5445 << FieldType); 5446 5447 MarkFunctionReferenced(Location, Dtor); 5448 DiagnoseUseOfDecl(Dtor, Location); 5449 } 5450 5451 // We only potentially invoke the destructors of potentially constructed 5452 // subobjects. 5453 bool VisitVirtualBases = !ClassDecl->isAbstract(); 5454 5455 // If the destructor exists and has already been marked used in the MS ABI, 5456 // then virtual base destructors have already been checked and marked used. 5457 // Skip checking them again to avoid duplicate diagnostics. 5458 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 5459 CXXDestructorDecl *Dtor = ClassDecl->getDestructor(); 5460 if (Dtor && Dtor->isUsed()) 5461 VisitVirtualBases = false; 5462 } 5463 5464 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 5465 5466 // Bases. 5467 for (const auto &Base : ClassDecl->bases()) { 5468 // Bases are always records in a well-formed non-dependent class. 5469 const RecordType *RT = Base.getType()->getAs<RecordType>(); 5470 5471 // Remember direct virtual bases. 5472 if (Base.isVirtual()) { 5473 if (!VisitVirtualBases) 5474 continue; 5475 DirectVirtualBases.insert(RT); 5476 } 5477 5478 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5479 // If our base class is invalid, we probably can't get its dtor anyway. 5480 if (BaseClassDecl->isInvalidDecl()) 5481 continue; 5482 if (BaseClassDecl->hasIrrelevantDestructor()) 5483 continue; 5484 5485 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5486 assert(Dtor && "No dtor found for BaseClassDecl!"); 5487 5488 // FIXME: caret should be on the start of the class name 5489 CheckDestructorAccess(Base.getBeginLoc(), Dtor, 5490 PDiag(diag::err_access_dtor_base) 5491 << Base.getType() << Base.getSourceRange(), 5492 Context.getTypeDeclType(ClassDecl)); 5493 5494 MarkFunctionReferenced(Location, Dtor); 5495 DiagnoseUseOfDecl(Dtor, Location); 5496 } 5497 5498 if (VisitVirtualBases) 5499 MarkVirtualBaseDestructorsReferenced(Location, ClassDecl, 5500 &DirectVirtualBases); 5501 } 5502 5503 void Sema::MarkVirtualBaseDestructorsReferenced( 5504 SourceLocation Location, CXXRecordDecl *ClassDecl, 5505 llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) { 5506 // Virtual bases. 5507 for (const auto &VBase : ClassDecl->vbases()) { 5508 // Bases are always records in a well-formed non-dependent class. 5509 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 5510 5511 // Ignore already visited direct virtual bases. 5512 if (DirectVirtualBases && DirectVirtualBases->count(RT)) 5513 continue; 5514 5515 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5516 // If our base class is invalid, we probably can't get its dtor anyway. 5517 if (BaseClassDecl->isInvalidDecl()) 5518 continue; 5519 if (BaseClassDecl->hasIrrelevantDestructor()) 5520 continue; 5521 5522 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5523 assert(Dtor && "No dtor found for BaseClassDecl!"); 5524 if (CheckDestructorAccess( 5525 ClassDecl->getLocation(), Dtor, 5526 PDiag(diag::err_access_dtor_vbase) 5527 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 5528 Context.getTypeDeclType(ClassDecl)) == 5529 AR_accessible) { 5530 CheckDerivedToBaseConversion( 5531 Context.getTypeDeclType(ClassDecl), VBase.getType(), 5532 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 5533 SourceRange(), DeclarationName(), nullptr); 5534 } 5535 5536 MarkFunctionReferenced(Location, Dtor); 5537 DiagnoseUseOfDecl(Dtor, Location); 5538 } 5539 } 5540 5541 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 5542 if (!CDtorDecl) 5543 return; 5544 5545 if (CXXConstructorDecl *Constructor 5546 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 5547 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 5548 DiagnoseUninitializedFields(*this, Constructor); 5549 } 5550 } 5551 5552 bool Sema::isAbstractType(SourceLocation Loc, QualType T) { 5553 if (!getLangOpts().CPlusPlus) 5554 return false; 5555 5556 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl(); 5557 if (!RD) 5558 return false; 5559 5560 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a 5561 // class template specialization here, but doing so breaks a lot of code. 5562 5563 // We can't answer whether something is abstract until it has a 5564 // definition. If it's currently being defined, we'll walk back 5565 // over all the declarations when we have a full definition. 5566 const CXXRecordDecl *Def = RD->getDefinition(); 5567 if (!Def || Def->isBeingDefined()) 5568 return false; 5569 5570 return RD->isAbstract(); 5571 } 5572 5573 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 5574 TypeDiagnoser &Diagnoser) { 5575 if (!isAbstractType(Loc, T)) 5576 return false; 5577 5578 T = Context.getBaseElementType(T); 5579 Diagnoser.diagnose(*this, Loc, T); 5580 DiagnoseAbstractType(T->getAsCXXRecordDecl()); 5581 return true; 5582 } 5583 5584 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 5585 // Check if we've already emitted the list of pure virtual functions 5586 // for this class. 5587 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 5588 return; 5589 5590 // If the diagnostic is suppressed, don't emit the notes. We're only 5591 // going to emit them once, so try to attach them to a diagnostic we're 5592 // actually going to show. 5593 if (Diags.isLastDiagnosticIgnored()) 5594 return; 5595 5596 CXXFinalOverriderMap FinalOverriders; 5597 RD->getFinalOverriders(FinalOverriders); 5598 5599 // Keep a set of seen pure methods so we won't diagnose the same method 5600 // more than once. 5601 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 5602 5603 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 5604 MEnd = FinalOverriders.end(); 5605 M != MEnd; 5606 ++M) { 5607 for (OverridingMethods::iterator SO = M->second.begin(), 5608 SOEnd = M->second.end(); 5609 SO != SOEnd; ++SO) { 5610 // C++ [class.abstract]p4: 5611 // A class is abstract if it contains or inherits at least one 5612 // pure virtual function for which the final overrider is pure 5613 // virtual. 5614 5615 // 5616 if (SO->second.size() != 1) 5617 continue; 5618 5619 if (!SO->second.front().Method->isPure()) 5620 continue; 5621 5622 if (!SeenPureMethods.insert(SO->second.front().Method).second) 5623 continue; 5624 5625 Diag(SO->second.front().Method->getLocation(), 5626 diag::note_pure_virtual_function) 5627 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 5628 } 5629 } 5630 5631 if (!PureVirtualClassDiagSet) 5632 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 5633 PureVirtualClassDiagSet->insert(RD); 5634 } 5635 5636 namespace { 5637 struct AbstractUsageInfo { 5638 Sema &S; 5639 CXXRecordDecl *Record; 5640 CanQualType AbstractType; 5641 bool Invalid; 5642 5643 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 5644 : S(S), Record(Record), 5645 AbstractType(S.Context.getCanonicalType( 5646 S.Context.getTypeDeclType(Record))), 5647 Invalid(false) {} 5648 5649 void DiagnoseAbstractType() { 5650 if (Invalid) return; 5651 S.DiagnoseAbstractType(Record); 5652 Invalid = true; 5653 } 5654 5655 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 5656 }; 5657 5658 struct CheckAbstractUsage { 5659 AbstractUsageInfo &Info; 5660 const NamedDecl *Ctx; 5661 5662 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 5663 : Info(Info), Ctx(Ctx) {} 5664 5665 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5666 switch (TL.getTypeLocClass()) { 5667 #define ABSTRACT_TYPELOC(CLASS, PARENT) 5668 #define TYPELOC(CLASS, PARENT) \ 5669 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 5670 #include "clang/AST/TypeLocNodes.def" 5671 } 5672 } 5673 5674 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5675 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 5676 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 5677 if (!TL.getParam(I)) 5678 continue; 5679 5680 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 5681 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 5682 } 5683 } 5684 5685 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5686 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 5687 } 5688 5689 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5690 // Visit the type parameters from a permissive context. 5691 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 5692 TemplateArgumentLoc TAL = TL.getArgLoc(I); 5693 if (TAL.getArgument().getKind() == TemplateArgument::Type) 5694 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 5695 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 5696 // TODO: other template argument types? 5697 } 5698 } 5699 5700 // Visit pointee types from a permissive context. 5701 #define CheckPolymorphic(Type) \ 5702 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 5703 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 5704 } 5705 CheckPolymorphic(PointerTypeLoc) 5706 CheckPolymorphic(ReferenceTypeLoc) 5707 CheckPolymorphic(MemberPointerTypeLoc) 5708 CheckPolymorphic(BlockPointerTypeLoc) 5709 CheckPolymorphic(AtomicTypeLoc) 5710 5711 /// Handle all the types we haven't given a more specific 5712 /// implementation for above. 5713 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5714 // Every other kind of type that we haven't called out already 5715 // that has an inner type is either (1) sugar or (2) contains that 5716 // inner type in some way as a subobject. 5717 if (TypeLoc Next = TL.getNextTypeLoc()) 5718 return Visit(Next, Sel); 5719 5720 // If there's no inner type and we're in a permissive context, 5721 // don't diagnose. 5722 if (Sel == Sema::AbstractNone) return; 5723 5724 // Check whether the type matches the abstract type. 5725 QualType T = TL.getType(); 5726 if (T->isArrayType()) { 5727 Sel = Sema::AbstractArrayType; 5728 T = Info.S.Context.getBaseElementType(T); 5729 } 5730 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 5731 if (CT != Info.AbstractType) return; 5732 5733 // It matched; do some magic. 5734 if (Sel == Sema::AbstractArrayType) { 5735 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 5736 << T << TL.getSourceRange(); 5737 } else { 5738 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 5739 << Sel << T << TL.getSourceRange(); 5740 } 5741 Info.DiagnoseAbstractType(); 5742 } 5743 }; 5744 5745 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 5746 Sema::AbstractDiagSelID Sel) { 5747 CheckAbstractUsage(*this, D).Visit(TL, Sel); 5748 } 5749 5750 } 5751 5752 /// Check for invalid uses of an abstract type in a method declaration. 5753 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5754 CXXMethodDecl *MD) { 5755 // No need to do the check on definitions, which require that 5756 // the return/param types be complete. 5757 if (MD->doesThisDeclarationHaveABody()) 5758 return; 5759 5760 // For safety's sake, just ignore it if we don't have type source 5761 // information. This should never happen for non-implicit methods, 5762 // but... 5763 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 5764 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 5765 } 5766 5767 /// Check for invalid uses of an abstract type within a class definition. 5768 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5769 CXXRecordDecl *RD) { 5770 for (auto *D : RD->decls()) { 5771 if (D->isImplicit()) continue; 5772 5773 // Methods and method templates. 5774 if (isa<CXXMethodDecl>(D)) { 5775 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 5776 } else if (isa<FunctionTemplateDecl>(D)) { 5777 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 5778 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 5779 5780 // Fields and static variables. 5781 } else if (isa<FieldDecl>(D)) { 5782 FieldDecl *FD = cast<FieldDecl>(D); 5783 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 5784 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 5785 } else if (isa<VarDecl>(D)) { 5786 VarDecl *VD = cast<VarDecl>(D); 5787 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 5788 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 5789 5790 // Nested classes and class templates. 5791 } else if (isa<CXXRecordDecl>(D)) { 5792 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 5793 } else if (isa<ClassTemplateDecl>(D)) { 5794 CheckAbstractClassUsage(Info, 5795 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 5796 } 5797 } 5798 } 5799 5800 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) { 5801 Attr *ClassAttr = getDLLAttr(Class); 5802 if (!ClassAttr) 5803 return; 5804 5805 assert(ClassAttr->getKind() == attr::DLLExport); 5806 5807 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5808 5809 if (TSK == TSK_ExplicitInstantiationDeclaration) 5810 // Don't go any further if this is just an explicit instantiation 5811 // declaration. 5812 return; 5813 5814 // Add a context note to explain how we got to any diagnostics produced below. 5815 struct MarkingClassDllexported { 5816 Sema &S; 5817 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class, 5818 SourceLocation AttrLoc) 5819 : S(S) { 5820 Sema::CodeSynthesisContext Ctx; 5821 Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported; 5822 Ctx.PointOfInstantiation = AttrLoc; 5823 Ctx.Entity = Class; 5824 S.pushCodeSynthesisContext(Ctx); 5825 } 5826 ~MarkingClassDllexported() { 5827 S.popCodeSynthesisContext(); 5828 } 5829 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation()); 5830 5831 if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) 5832 S.MarkVTableUsed(Class->getLocation(), Class, true); 5833 5834 for (Decl *Member : Class->decls()) { 5835 // Defined static variables that are members of an exported base 5836 // class must be marked export too. 5837 auto *VD = dyn_cast<VarDecl>(Member); 5838 if (VD && Member->getAttr<DLLExportAttr>() && 5839 VD->getStorageClass() == SC_Static && 5840 TSK == TSK_ImplicitInstantiation) 5841 S.MarkVariableReferenced(VD->getLocation(), VD); 5842 5843 auto *MD = dyn_cast<CXXMethodDecl>(Member); 5844 if (!MD) 5845 continue; 5846 5847 if (Member->getAttr<DLLExportAttr>()) { 5848 if (MD->isUserProvided()) { 5849 // Instantiate non-default class member functions ... 5850 5851 // .. except for certain kinds of template specializations. 5852 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 5853 continue; 5854 5855 S.MarkFunctionReferenced(Class->getLocation(), MD); 5856 5857 // The function will be passed to the consumer when its definition is 5858 // encountered. 5859 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() || 5860 MD->isCopyAssignmentOperator() || 5861 MD->isMoveAssignmentOperator()) { 5862 // Synthesize and instantiate non-trivial implicit methods, explicitly 5863 // defaulted methods, and the copy and move assignment operators. The 5864 // latter are exported even if they are trivial, because the address of 5865 // an operator can be taken and should compare equal across libraries. 5866 S.MarkFunctionReferenced(Class->getLocation(), MD); 5867 5868 // There is no later point when we will see the definition of this 5869 // function, so pass it to the consumer now. 5870 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 5871 } 5872 } 5873 } 5874 } 5875 5876 static void checkForMultipleExportedDefaultConstructors(Sema &S, 5877 CXXRecordDecl *Class) { 5878 // Only the MS ABI has default constructor closures, so we don't need to do 5879 // this semantic checking anywhere else. 5880 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft()) 5881 return; 5882 5883 CXXConstructorDecl *LastExportedDefaultCtor = nullptr; 5884 for (Decl *Member : Class->decls()) { 5885 // Look for exported default constructors. 5886 auto *CD = dyn_cast<CXXConstructorDecl>(Member); 5887 if (!CD || !CD->isDefaultConstructor()) 5888 continue; 5889 auto *Attr = CD->getAttr<DLLExportAttr>(); 5890 if (!Attr) 5891 continue; 5892 5893 // If the class is non-dependent, mark the default arguments as ODR-used so 5894 // that we can properly codegen the constructor closure. 5895 if (!Class->isDependentContext()) { 5896 for (ParmVarDecl *PD : CD->parameters()) { 5897 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD); 5898 S.DiscardCleanupsInEvaluationContext(); 5899 } 5900 } 5901 5902 if (LastExportedDefaultCtor) { 5903 S.Diag(LastExportedDefaultCtor->getLocation(), 5904 diag::err_attribute_dll_ambiguous_default_ctor) 5905 << Class; 5906 S.Diag(CD->getLocation(), diag::note_entity_declared_at) 5907 << CD->getDeclName(); 5908 return; 5909 } 5910 LastExportedDefaultCtor = CD; 5911 } 5912 } 5913 5914 static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S, 5915 CXXRecordDecl *Class) { 5916 bool ErrorReported = false; 5917 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S, 5918 ClassTemplateDecl *TD) { 5919 if (ErrorReported) 5920 return; 5921 S.Diag(TD->getLocation(), 5922 diag::err_cuda_device_builtin_surftex_cls_template) 5923 << /*surface*/ 0 << TD; 5924 ErrorReported = true; 5925 }; 5926 5927 ClassTemplateDecl *TD = Class->getDescribedClassTemplate(); 5928 if (!TD) { 5929 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class); 5930 if (!SD) { 5931 S.Diag(Class->getLocation(), 5932 diag::err_cuda_device_builtin_surftex_ref_decl) 5933 << /*surface*/ 0 << Class; 5934 S.Diag(Class->getLocation(), 5935 diag::note_cuda_device_builtin_surftex_should_be_template_class) 5936 << Class; 5937 return; 5938 } 5939 TD = SD->getSpecializedTemplate(); 5940 } 5941 5942 TemplateParameterList *Params = TD->getTemplateParameters(); 5943 unsigned N = Params->size(); 5944 5945 if (N != 2) { 5946 reportIllegalClassTemplate(S, TD); 5947 S.Diag(TD->getLocation(), 5948 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args) 5949 << TD << 2; 5950 } 5951 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 5952 reportIllegalClassTemplate(S, TD); 5953 S.Diag(TD->getLocation(), 5954 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 5955 << TD << /*1st*/ 0 << /*type*/ 0; 5956 } 5957 if (N > 1) { 5958 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 5959 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 5960 reportIllegalClassTemplate(S, TD); 5961 S.Diag(TD->getLocation(), 5962 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 5963 << TD << /*2nd*/ 1 << /*integer*/ 1; 5964 } 5965 } 5966 } 5967 5968 static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S, 5969 CXXRecordDecl *Class) { 5970 bool ErrorReported = false; 5971 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S, 5972 ClassTemplateDecl *TD) { 5973 if (ErrorReported) 5974 return; 5975 S.Diag(TD->getLocation(), 5976 diag::err_cuda_device_builtin_surftex_cls_template) 5977 << /*texture*/ 1 << TD; 5978 ErrorReported = true; 5979 }; 5980 5981 ClassTemplateDecl *TD = Class->getDescribedClassTemplate(); 5982 if (!TD) { 5983 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class); 5984 if (!SD) { 5985 S.Diag(Class->getLocation(), 5986 diag::err_cuda_device_builtin_surftex_ref_decl) 5987 << /*texture*/ 1 << Class; 5988 S.Diag(Class->getLocation(), 5989 diag::note_cuda_device_builtin_surftex_should_be_template_class) 5990 << Class; 5991 return; 5992 } 5993 TD = SD->getSpecializedTemplate(); 5994 } 5995 5996 TemplateParameterList *Params = TD->getTemplateParameters(); 5997 unsigned N = Params->size(); 5998 5999 if (N != 3) { 6000 reportIllegalClassTemplate(S, TD); 6001 S.Diag(TD->getLocation(), 6002 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args) 6003 << TD << 3; 6004 } 6005 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 6006 reportIllegalClassTemplate(S, TD); 6007 S.Diag(TD->getLocation(), 6008 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6009 << TD << /*1st*/ 0 << /*type*/ 0; 6010 } 6011 if (N > 1) { 6012 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1)); 6013 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 6014 reportIllegalClassTemplate(S, TD); 6015 S.Diag(TD->getLocation(), 6016 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6017 << TD << /*2nd*/ 1 << /*integer*/ 1; 6018 } 6019 } 6020 if (N > 2) { 6021 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2)); 6022 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) { 6023 reportIllegalClassTemplate(S, TD); 6024 S.Diag(TD->getLocation(), 6025 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg) 6026 << TD << /*3rd*/ 2 << /*integer*/ 1; 6027 } 6028 } 6029 } 6030 6031 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) { 6032 // Mark any compiler-generated routines with the implicit code_seg attribute. 6033 for (auto *Method : Class->methods()) { 6034 if (Method->isUserProvided()) 6035 continue; 6036 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true)) 6037 Method->addAttr(A); 6038 } 6039 } 6040 6041 /// Check class-level dllimport/dllexport attribute. 6042 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) { 6043 Attr *ClassAttr = getDLLAttr(Class); 6044 6045 // MSVC inherits DLL attributes to partial class template specializations. 6046 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) { 6047 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 6048 if (Attr *TemplateAttr = 6049 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 6050 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext())); 6051 A->setInherited(true); 6052 ClassAttr = A; 6053 } 6054 } 6055 } 6056 6057 if (!ClassAttr) 6058 return; 6059 6060 if (!Class->isExternallyVisible()) { 6061 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) 6062 << Class << ClassAttr; 6063 return; 6064 } 6065 6066 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 6067 !ClassAttr->isInherited()) { 6068 // Diagnose dll attributes on members of class with dll attribute. 6069 for (Decl *Member : Class->decls()) { 6070 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 6071 continue; 6072 InheritableAttr *MemberAttr = getDLLAttr(Member); 6073 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 6074 continue; 6075 6076 Diag(MemberAttr->getLocation(), 6077 diag::err_attribute_dll_member_of_dll_class) 6078 << MemberAttr << ClassAttr; 6079 Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 6080 Member->setInvalidDecl(); 6081 } 6082 } 6083 6084 if (Class->getDescribedClassTemplate()) 6085 // Don't inherit dll attribute until the template is instantiated. 6086 return; 6087 6088 // The class is either imported or exported. 6089 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 6090 6091 // Check if this was a dllimport attribute propagated from a derived class to 6092 // a base class template specialization. We don't apply these attributes to 6093 // static data members. 6094 const bool PropagatedImport = 6095 !ClassExported && 6096 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate(); 6097 6098 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 6099 6100 // Ignore explicit dllexport on explicit class template instantiation 6101 // declarations, except in MinGW mode. 6102 if (ClassExported && !ClassAttr->isInherited() && 6103 TSK == TSK_ExplicitInstantiationDeclaration && 6104 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) { 6105 Class->dropAttr<DLLExportAttr>(); 6106 return; 6107 } 6108 6109 // Force declaration of implicit members so they can inherit the attribute. 6110 ForceDeclarationOfImplicitMembers(Class); 6111 6112 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 6113 // seem to be true in practice? 6114 6115 for (Decl *Member : Class->decls()) { 6116 VarDecl *VD = dyn_cast<VarDecl>(Member); 6117 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 6118 6119 // Only methods and static fields inherit the attributes. 6120 if (!VD && !MD) 6121 continue; 6122 6123 if (MD) { 6124 // Don't process deleted methods. 6125 if (MD->isDeleted()) 6126 continue; 6127 6128 if (MD->isInlined()) { 6129 // MinGW does not import or export inline methods. But do it for 6130 // template instantiations. 6131 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() && 6132 !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment() && 6133 TSK != TSK_ExplicitInstantiationDeclaration && 6134 TSK != TSK_ExplicitInstantiationDefinition) 6135 continue; 6136 6137 // MSVC versions before 2015 don't export the move assignment operators 6138 // and move constructor, so don't attempt to import/export them if 6139 // we have a definition. 6140 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD); 6141 if ((MD->isMoveAssignmentOperator() || 6142 (Ctor && Ctor->isMoveConstructor())) && 6143 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015)) 6144 continue; 6145 6146 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign 6147 // operator is exported anyway. 6148 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 6149 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial()) 6150 continue; 6151 } 6152 } 6153 6154 // Don't apply dllimport attributes to static data members of class template 6155 // instantiations when the attribute is propagated from a derived class. 6156 if (VD && PropagatedImport) 6157 continue; 6158 6159 if (!cast<NamedDecl>(Member)->isExternallyVisible()) 6160 continue; 6161 6162 if (!getDLLAttr(Member)) { 6163 InheritableAttr *NewAttr = nullptr; 6164 6165 // Do not export/import inline function when -fno-dllexport-inlines is 6166 // passed. But add attribute for later local static var check. 6167 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() && 6168 TSK != TSK_ExplicitInstantiationDeclaration && 6169 TSK != TSK_ExplicitInstantiationDefinition) { 6170 if (ClassExported) { 6171 NewAttr = ::new (getASTContext()) 6172 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr); 6173 } else { 6174 NewAttr = ::new (getASTContext()) 6175 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr); 6176 } 6177 } else { 6178 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6179 } 6180 6181 NewAttr->setInherited(true); 6182 Member->addAttr(NewAttr); 6183 6184 if (MD) { 6185 // Propagate DLLAttr to friend re-declarations of MD that have already 6186 // been constructed. 6187 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD; 6188 FD = FD->getPreviousDecl()) { 6189 if (FD->getFriendObjectKind() == Decl::FOK_None) 6190 continue; 6191 assert(!getDLLAttr(FD) && 6192 "friend re-decl should not already have a DLLAttr"); 6193 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6194 NewAttr->setInherited(true); 6195 FD->addAttr(NewAttr); 6196 } 6197 } 6198 } 6199 } 6200 6201 if (ClassExported) 6202 DelayedDllExportClasses.push_back(Class); 6203 } 6204 6205 /// Perform propagation of DLL attributes from a derived class to a 6206 /// templated base class for MS compatibility. 6207 void Sema::propagateDLLAttrToBaseClassTemplate( 6208 CXXRecordDecl *Class, Attr *ClassAttr, 6209 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 6210 if (getDLLAttr( 6211 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 6212 // If the base class template has a DLL attribute, don't try to change it. 6213 return; 6214 } 6215 6216 auto TSK = BaseTemplateSpec->getSpecializationKind(); 6217 if (!getDLLAttr(BaseTemplateSpec) && 6218 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration || 6219 TSK == TSK_ImplicitInstantiation)) { 6220 // The template hasn't been instantiated yet (or it has, but only as an 6221 // explicit instantiation declaration or implicit instantiation, which means 6222 // we haven't codegenned any members yet), so propagate the attribute. 6223 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6224 NewAttr->setInherited(true); 6225 BaseTemplateSpec->addAttr(NewAttr); 6226 6227 // If this was an import, mark that we propagated it from a derived class to 6228 // a base class template specialization. 6229 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr)) 6230 ImportAttr->setPropagatedToBaseTemplate(); 6231 6232 // If the template is already instantiated, checkDLLAttributeRedeclaration() 6233 // needs to be run again to work see the new attribute. Otherwise this will 6234 // get run whenever the template is instantiated. 6235 if (TSK != TSK_Undeclared) 6236 checkClassLevelDLLAttribute(BaseTemplateSpec); 6237 6238 return; 6239 } 6240 6241 if (getDLLAttr(BaseTemplateSpec)) { 6242 // The template has already been specialized or instantiated with an 6243 // attribute, explicitly or through propagation. We should not try to change 6244 // it. 6245 return; 6246 } 6247 6248 // The template was previously instantiated or explicitly specialized without 6249 // a dll attribute, It's too late for us to add an attribute, so warn that 6250 // this is unsupported. 6251 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 6252 << BaseTemplateSpec->isExplicitSpecialization(); 6253 Diag(ClassAttr->getLocation(), diag::note_attribute); 6254 if (BaseTemplateSpec->isExplicitSpecialization()) { 6255 Diag(BaseTemplateSpec->getLocation(), 6256 diag::note_template_class_explicit_specialization_was_here) 6257 << BaseTemplateSpec; 6258 } else { 6259 Diag(BaseTemplateSpec->getPointOfInstantiation(), 6260 diag::note_template_class_instantiation_was_here) 6261 << BaseTemplateSpec; 6262 } 6263 } 6264 6265 /// Determine the kind of defaulting that would be done for a given function. 6266 /// 6267 /// If the function is both a default constructor and a copy / move constructor 6268 /// (due to having a default argument for the first parameter), this picks 6269 /// CXXDefaultConstructor. 6270 /// 6271 /// FIXME: Check that case is properly handled by all callers. 6272 Sema::DefaultedFunctionKind 6273 Sema::getDefaultedFunctionKind(const FunctionDecl *FD) { 6274 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 6275 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 6276 if (Ctor->isDefaultConstructor()) 6277 return Sema::CXXDefaultConstructor; 6278 6279 if (Ctor->isCopyConstructor()) 6280 return Sema::CXXCopyConstructor; 6281 6282 if (Ctor->isMoveConstructor()) 6283 return Sema::CXXMoveConstructor; 6284 } 6285 6286 if (MD->isCopyAssignmentOperator()) 6287 return Sema::CXXCopyAssignment; 6288 6289 if (MD->isMoveAssignmentOperator()) 6290 return Sema::CXXMoveAssignment; 6291 6292 if (isa<CXXDestructorDecl>(FD)) 6293 return Sema::CXXDestructor; 6294 } 6295 6296 switch (FD->getDeclName().getCXXOverloadedOperator()) { 6297 case OO_EqualEqual: 6298 return DefaultedComparisonKind::Equal; 6299 6300 case OO_ExclaimEqual: 6301 return DefaultedComparisonKind::NotEqual; 6302 6303 case OO_Spaceship: 6304 // No point allowing this if <=> doesn't exist in the current language mode. 6305 if (!getLangOpts().CPlusPlus20) 6306 break; 6307 return DefaultedComparisonKind::ThreeWay; 6308 6309 case OO_Less: 6310 case OO_LessEqual: 6311 case OO_Greater: 6312 case OO_GreaterEqual: 6313 // No point allowing this if <=> doesn't exist in the current language mode. 6314 if (!getLangOpts().CPlusPlus20) 6315 break; 6316 return DefaultedComparisonKind::Relational; 6317 6318 default: 6319 break; 6320 } 6321 6322 // Not defaultable. 6323 return DefaultedFunctionKind(); 6324 } 6325 6326 static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD, 6327 SourceLocation DefaultLoc) { 6328 Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD); 6329 if (DFK.isComparison()) 6330 return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison()); 6331 6332 switch (DFK.asSpecialMember()) { 6333 case Sema::CXXDefaultConstructor: 6334 S.DefineImplicitDefaultConstructor(DefaultLoc, 6335 cast<CXXConstructorDecl>(FD)); 6336 break; 6337 case Sema::CXXCopyConstructor: 6338 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD)); 6339 break; 6340 case Sema::CXXCopyAssignment: 6341 S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD)); 6342 break; 6343 case Sema::CXXDestructor: 6344 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD)); 6345 break; 6346 case Sema::CXXMoveConstructor: 6347 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD)); 6348 break; 6349 case Sema::CXXMoveAssignment: 6350 S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD)); 6351 break; 6352 case Sema::CXXInvalid: 6353 llvm_unreachable("Invalid special member."); 6354 } 6355 } 6356 6357 /// Determine whether a type is permitted to be passed or returned in 6358 /// registers, per C++ [class.temporary]p3. 6359 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D, 6360 TargetInfo::CallingConvKind CCK) { 6361 if (D->isDependentType() || D->isInvalidDecl()) 6362 return false; 6363 6364 // Clang <= 4 used the pre-C++11 rule, which ignores move operations. 6365 // The PS4 platform ABI follows the behavior of Clang 3.2. 6366 if (CCK == TargetInfo::CCK_ClangABI4OrPS4) 6367 return !D->hasNonTrivialDestructorForCall() && 6368 !D->hasNonTrivialCopyConstructorForCall(); 6369 6370 if (CCK == TargetInfo::CCK_MicrosoftWin64) { 6371 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false; 6372 bool DtorIsTrivialForCall = false; 6373 6374 // If a class has at least one non-deleted, trivial copy constructor, it 6375 // is passed according to the C ABI. Otherwise, it is passed indirectly. 6376 // 6377 // Note: This permits classes with non-trivial copy or move ctors to be 6378 // passed in registers, so long as they *also* have a trivial copy ctor, 6379 // which is non-conforming. 6380 if (D->needsImplicitCopyConstructor()) { 6381 if (!D->defaultedCopyConstructorIsDeleted()) { 6382 if (D->hasTrivialCopyConstructor()) 6383 CopyCtorIsTrivial = true; 6384 if (D->hasTrivialCopyConstructorForCall()) 6385 CopyCtorIsTrivialForCall = true; 6386 } 6387 } else { 6388 for (const CXXConstructorDecl *CD : D->ctors()) { 6389 if (CD->isCopyConstructor() && !CD->isDeleted()) { 6390 if (CD->isTrivial()) 6391 CopyCtorIsTrivial = true; 6392 if (CD->isTrivialForCall()) 6393 CopyCtorIsTrivialForCall = true; 6394 } 6395 } 6396 } 6397 6398 if (D->needsImplicitDestructor()) { 6399 if (!D->defaultedDestructorIsDeleted() && 6400 D->hasTrivialDestructorForCall()) 6401 DtorIsTrivialForCall = true; 6402 } else if (const auto *DD = D->getDestructor()) { 6403 if (!DD->isDeleted() && DD->isTrivialForCall()) 6404 DtorIsTrivialForCall = true; 6405 } 6406 6407 // If the copy ctor and dtor are both trivial-for-calls, pass direct. 6408 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall) 6409 return true; 6410 6411 // If a class has a destructor, we'd really like to pass it indirectly 6412 // because it allows us to elide copies. Unfortunately, MSVC makes that 6413 // impossible for small types, which it will pass in a single register or 6414 // stack slot. Most objects with dtors are large-ish, so handle that early. 6415 // We can't call out all large objects as being indirect because there are 6416 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate 6417 // how we pass large POD types. 6418 6419 // Note: This permits small classes with nontrivial destructors to be 6420 // passed in registers, which is non-conforming. 6421 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64(); 6422 uint64_t TypeSize = isAArch64 ? 128 : 64; 6423 6424 if (CopyCtorIsTrivial && 6425 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize) 6426 return true; 6427 return false; 6428 } 6429 6430 // Per C++ [class.temporary]p3, the relevant condition is: 6431 // each copy constructor, move constructor, and destructor of X is 6432 // either trivial or deleted, and X has at least one non-deleted copy 6433 // or move constructor 6434 bool HasNonDeletedCopyOrMove = false; 6435 6436 if (D->needsImplicitCopyConstructor() && 6437 !D->defaultedCopyConstructorIsDeleted()) { 6438 if (!D->hasTrivialCopyConstructorForCall()) 6439 return false; 6440 HasNonDeletedCopyOrMove = true; 6441 } 6442 6443 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() && 6444 !D->defaultedMoveConstructorIsDeleted()) { 6445 if (!D->hasTrivialMoveConstructorForCall()) 6446 return false; 6447 HasNonDeletedCopyOrMove = true; 6448 } 6449 6450 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() && 6451 !D->hasTrivialDestructorForCall()) 6452 return false; 6453 6454 for (const CXXMethodDecl *MD : D->methods()) { 6455 if (MD->isDeleted()) 6456 continue; 6457 6458 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 6459 if (CD && CD->isCopyOrMoveConstructor()) 6460 HasNonDeletedCopyOrMove = true; 6461 else if (!isa<CXXDestructorDecl>(MD)) 6462 continue; 6463 6464 if (!MD->isTrivialForCall()) 6465 return false; 6466 } 6467 6468 return HasNonDeletedCopyOrMove; 6469 } 6470 6471 /// Report an error regarding overriding, along with any relevant 6472 /// overridden methods. 6473 /// 6474 /// \param DiagID the primary error to report. 6475 /// \param MD the overriding method. 6476 static bool 6477 ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD, 6478 llvm::function_ref<bool(const CXXMethodDecl *)> Report) { 6479 bool IssuedDiagnostic = false; 6480 for (const CXXMethodDecl *O : MD->overridden_methods()) { 6481 if (Report(O)) { 6482 if (!IssuedDiagnostic) { 6483 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 6484 IssuedDiagnostic = true; 6485 } 6486 S.Diag(O->getLocation(), diag::note_overridden_virtual_function); 6487 } 6488 } 6489 return IssuedDiagnostic; 6490 } 6491 6492 /// Perform semantic checks on a class definition that has been 6493 /// completing, introducing implicitly-declared members, checking for 6494 /// abstract types, etc. 6495 /// 6496 /// \param S The scope in which the class was parsed. Null if we didn't just 6497 /// parse a class definition. 6498 /// \param Record The completed class. 6499 void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) { 6500 if (!Record) 6501 return; 6502 6503 if (Record->isAbstract() && !Record->isInvalidDecl()) { 6504 AbstractUsageInfo Info(*this, Record); 6505 CheckAbstractClassUsage(Info, Record); 6506 } 6507 6508 // If this is not an aggregate type and has no user-declared constructor, 6509 // complain about any non-static data members of reference or const scalar 6510 // type, since they will never get initializers. 6511 if (!Record->isInvalidDecl() && !Record->isDependentType() && 6512 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 6513 !Record->isLambda()) { 6514 bool Complained = false; 6515 for (const auto *F : Record->fields()) { 6516 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 6517 continue; 6518 6519 if (F->getType()->isReferenceType() || 6520 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 6521 if (!Complained) { 6522 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 6523 << Record->getTagKind() << Record; 6524 Complained = true; 6525 } 6526 6527 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 6528 << F->getType()->isReferenceType() 6529 << F->getDeclName(); 6530 } 6531 } 6532 } 6533 6534 if (Record->getIdentifier()) { 6535 // C++ [class.mem]p13: 6536 // If T is the name of a class, then each of the following shall have a 6537 // name different from T: 6538 // - every member of every anonymous union that is a member of class T. 6539 // 6540 // C++ [class.mem]p14: 6541 // In addition, if class T has a user-declared constructor (12.1), every 6542 // non-static data member of class T shall have a name different from T. 6543 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 6544 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 6545 ++I) { 6546 NamedDecl *D = (*I)->getUnderlyingDecl(); 6547 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) && 6548 Record->hasUserDeclaredConstructor()) || 6549 isa<IndirectFieldDecl>(D)) { 6550 Diag((*I)->getLocation(), diag::err_member_name_of_class) 6551 << D->getDeclName(); 6552 break; 6553 } 6554 } 6555 } 6556 6557 // Warn if the class has virtual methods but non-virtual public destructor. 6558 if (Record->isPolymorphic() && !Record->isDependentType()) { 6559 CXXDestructorDecl *dtor = Record->getDestructor(); 6560 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 6561 !Record->hasAttr<FinalAttr>()) 6562 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 6563 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 6564 } 6565 6566 if (Record->isAbstract()) { 6567 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 6568 Diag(Record->getLocation(), diag::warn_abstract_final_class) 6569 << FA->isSpelledAsSealed(); 6570 DiagnoseAbstractType(Record); 6571 } 6572 } 6573 6574 // Warn if the class has a final destructor but is not itself marked final. 6575 if (!Record->hasAttr<FinalAttr>()) { 6576 if (const CXXDestructorDecl *dtor = Record->getDestructor()) { 6577 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) { 6578 Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class) 6579 << FA->isSpelledAsSealed() 6580 << FixItHint::CreateInsertion( 6581 getLocForEndOfToken(Record->getLocation()), 6582 (FA->isSpelledAsSealed() ? " sealed" : " final")); 6583 Diag(Record->getLocation(), 6584 diag::note_final_dtor_non_final_class_silence) 6585 << Context.getRecordType(Record) << FA->isSpelledAsSealed(); 6586 } 6587 } 6588 } 6589 6590 // See if trivial_abi has to be dropped. 6591 if (Record->hasAttr<TrivialABIAttr>()) 6592 checkIllFormedTrivialABIStruct(*Record); 6593 6594 // Set HasTrivialSpecialMemberForCall if the record has attribute 6595 // "trivial_abi". 6596 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>(); 6597 6598 if (HasTrivialABI) 6599 Record->setHasTrivialSpecialMemberForCall(); 6600 6601 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=). 6602 // We check these last because they can depend on the properties of the 6603 // primary comparison functions (==, <=>). 6604 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons; 6605 6606 // Perform checks that can't be done until we know all the properties of a 6607 // member function (whether it's defaulted, deleted, virtual, overriding, 6608 // ...). 6609 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) { 6610 // A static function cannot override anything. 6611 if (MD->getStorageClass() == SC_Static) { 6612 if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD, 6613 [](const CXXMethodDecl *) { return true; })) 6614 return; 6615 } 6616 6617 // A deleted function cannot override a non-deleted function and vice 6618 // versa. 6619 if (ReportOverrides(*this, 6620 MD->isDeleted() ? diag::err_deleted_override 6621 : diag::err_non_deleted_override, 6622 MD, [&](const CXXMethodDecl *V) { 6623 return MD->isDeleted() != V->isDeleted(); 6624 })) { 6625 if (MD->isDefaulted() && MD->isDeleted()) 6626 // Explain why this defaulted function was deleted. 6627 DiagnoseDeletedDefaultedFunction(MD); 6628 return; 6629 } 6630 6631 // A consteval function cannot override a non-consteval function and vice 6632 // versa. 6633 if (ReportOverrides(*this, 6634 MD->isConsteval() ? diag::err_consteval_override 6635 : diag::err_non_consteval_override, 6636 MD, [&](const CXXMethodDecl *V) { 6637 return MD->isConsteval() != V->isConsteval(); 6638 })) { 6639 if (MD->isDefaulted() && MD->isDeleted()) 6640 // Explain why this defaulted function was deleted. 6641 DiagnoseDeletedDefaultedFunction(MD); 6642 return; 6643 } 6644 }; 6645 6646 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool { 6647 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted()) 6648 return false; 6649 6650 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD); 6651 if (DFK.asComparison() == DefaultedComparisonKind::NotEqual || 6652 DFK.asComparison() == DefaultedComparisonKind::Relational) { 6653 DefaultedSecondaryComparisons.push_back(FD); 6654 return true; 6655 } 6656 6657 CheckExplicitlyDefaultedFunction(S, FD); 6658 return false; 6659 }; 6660 6661 auto CompleteMemberFunction = [&](CXXMethodDecl *M) { 6662 // Check whether the explicitly-defaulted members are valid. 6663 bool Incomplete = CheckForDefaultedFunction(M); 6664 6665 // Skip the rest of the checks for a member of a dependent class. 6666 if (Record->isDependentType()) 6667 return; 6668 6669 // For an explicitly defaulted or deleted special member, we defer 6670 // determining triviality until the class is complete. That time is now! 6671 CXXSpecialMember CSM = getSpecialMember(M); 6672 if (!M->isImplicit() && !M->isUserProvided()) { 6673 if (CSM != CXXInvalid) { 6674 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 6675 // Inform the class that we've finished declaring this member. 6676 Record->finishedDefaultedOrDeletedMember(M); 6677 M->setTrivialForCall( 6678 HasTrivialABI || 6679 SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI)); 6680 Record->setTrivialForCallFlags(M); 6681 } 6682 } 6683 6684 // Set triviality for the purpose of calls if this is a user-provided 6685 // copy/move constructor or destructor. 6686 if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor || 6687 CSM == CXXDestructor) && M->isUserProvided()) { 6688 M->setTrivialForCall(HasTrivialABI); 6689 Record->setTrivialForCallFlags(M); 6690 } 6691 6692 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() && 6693 M->hasAttr<DLLExportAttr>()) { 6694 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 6695 M->isTrivial() && 6696 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor || 6697 CSM == CXXDestructor)) 6698 M->dropAttr<DLLExportAttr>(); 6699 6700 if (M->hasAttr<DLLExportAttr>()) { 6701 // Define after any fields with in-class initializers have been parsed. 6702 DelayedDllExportMemberFunctions.push_back(M); 6703 } 6704 } 6705 6706 // Define defaulted constexpr virtual functions that override a base class 6707 // function right away. 6708 // FIXME: We can defer doing this until the vtable is marked as used. 6709 if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods()) 6710 DefineDefaultedFunction(*this, M, M->getLocation()); 6711 6712 if (!Incomplete) 6713 CheckCompletedMemberFunction(M); 6714 }; 6715 6716 // Check the destructor before any other member function. We need to 6717 // determine whether it's trivial in order to determine whether the claas 6718 // type is a literal type, which is a prerequisite for determining whether 6719 // other special member functions are valid and whether they're implicitly 6720 // 'constexpr'. 6721 if (CXXDestructorDecl *Dtor = Record->getDestructor()) 6722 CompleteMemberFunction(Dtor); 6723 6724 bool HasMethodWithOverrideControl = false, 6725 HasOverridingMethodWithoutOverrideControl = false; 6726 for (auto *D : Record->decls()) { 6727 if (auto *M = dyn_cast<CXXMethodDecl>(D)) { 6728 // FIXME: We could do this check for dependent types with non-dependent 6729 // bases. 6730 if (!Record->isDependentType()) { 6731 // See if a method overloads virtual methods in a base 6732 // class without overriding any. 6733 if (!M->isStatic()) 6734 DiagnoseHiddenVirtualMethods(M); 6735 if (M->hasAttr<OverrideAttr>()) 6736 HasMethodWithOverrideControl = true; 6737 else if (M->size_overridden_methods() > 0) 6738 HasOverridingMethodWithoutOverrideControl = true; 6739 } 6740 6741 if (!isa<CXXDestructorDecl>(M)) 6742 CompleteMemberFunction(M); 6743 } else if (auto *F = dyn_cast<FriendDecl>(D)) { 6744 CheckForDefaultedFunction( 6745 dyn_cast_or_null<FunctionDecl>(F->getFriendDecl())); 6746 } 6747 } 6748 6749 if (HasMethodWithOverrideControl && 6750 HasOverridingMethodWithoutOverrideControl) { 6751 // At least one method has the 'override' control declared. 6752 // Diagnose all other overridden methods which do not have 'override' 6753 // specified on them. 6754 for (auto *M : Record->methods()) 6755 DiagnoseAbsenceOfOverrideControl(M); 6756 } 6757 6758 // Check the defaulted secondary comparisons after any other member functions. 6759 for (FunctionDecl *FD : DefaultedSecondaryComparisons) { 6760 CheckExplicitlyDefaultedFunction(S, FD); 6761 6762 // If this is a member function, we deferred checking it until now. 6763 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) 6764 CheckCompletedMemberFunction(MD); 6765 } 6766 6767 // ms_struct is a request to use the same ABI rules as MSVC. Check 6768 // whether this class uses any C++ features that are implemented 6769 // completely differently in MSVC, and if so, emit a diagnostic. 6770 // That diagnostic defaults to an error, but we allow projects to 6771 // map it down to a warning (or ignore it). It's a fairly common 6772 // practice among users of the ms_struct pragma to mass-annotate 6773 // headers, sweeping up a bunch of types that the project doesn't 6774 // really rely on MSVC-compatible layout for. We must therefore 6775 // support "ms_struct except for C++ stuff" as a secondary ABI. 6776 if (Record->isMsStruct(Context) && 6777 (Record->isPolymorphic() || Record->getNumBases())) { 6778 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 6779 } 6780 6781 checkClassLevelDLLAttribute(Record); 6782 checkClassLevelCodeSegAttribute(Record); 6783 6784 bool ClangABICompat4 = 6785 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4; 6786 TargetInfo::CallingConvKind CCK = 6787 Context.getTargetInfo().getCallingConvKind(ClangABICompat4); 6788 bool CanPass = canPassInRegisters(*this, Record, CCK); 6789 6790 // Do not change ArgPassingRestrictions if it has already been set to 6791 // APK_CanNeverPassInRegs. 6792 if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs) 6793 Record->setArgPassingRestrictions(CanPass 6794 ? RecordDecl::APK_CanPassInRegs 6795 : RecordDecl::APK_CannotPassInRegs); 6796 6797 // If canPassInRegisters returns true despite the record having a non-trivial 6798 // destructor, the record is destructed in the callee. This happens only when 6799 // the record or one of its subobjects has a field annotated with trivial_abi 6800 // or a field qualified with ObjC __strong/__weak. 6801 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee()) 6802 Record->setParamDestroyedInCallee(true); 6803 else if (Record->hasNonTrivialDestructor()) 6804 Record->setParamDestroyedInCallee(CanPass); 6805 6806 if (getLangOpts().ForceEmitVTables) { 6807 // If we want to emit all the vtables, we need to mark it as used. This 6808 // is especially required for cases like vtable assumption loads. 6809 MarkVTableUsed(Record->getInnerLocStart(), Record); 6810 } 6811 6812 if (getLangOpts().CUDA) { 6813 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>()) 6814 checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record); 6815 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>()) 6816 checkCUDADeviceBuiltinTextureClassTemplate(*this, Record); 6817 } 6818 } 6819 6820 /// Look up the special member function that would be called by a special 6821 /// member function for a subobject of class type. 6822 /// 6823 /// \param Class The class type of the subobject. 6824 /// \param CSM The kind of special member function. 6825 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 6826 /// \param ConstRHS True if this is a copy operation with a const object 6827 /// on its RHS, that is, if the argument to the outer special member 6828 /// function is 'const' and this is not a field marked 'mutable'. 6829 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember( 6830 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 6831 unsigned FieldQuals, bool ConstRHS) { 6832 unsigned LHSQuals = 0; 6833 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 6834 LHSQuals = FieldQuals; 6835 6836 unsigned RHSQuals = FieldQuals; 6837 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 6838 RHSQuals = 0; 6839 else if (ConstRHS) 6840 RHSQuals |= Qualifiers::Const; 6841 6842 return S.LookupSpecialMember(Class, CSM, 6843 RHSQuals & Qualifiers::Const, 6844 RHSQuals & Qualifiers::Volatile, 6845 false, 6846 LHSQuals & Qualifiers::Const, 6847 LHSQuals & Qualifiers::Volatile); 6848 } 6849 6850 class Sema::InheritedConstructorInfo { 6851 Sema &S; 6852 SourceLocation UseLoc; 6853 6854 /// A mapping from the base classes through which the constructor was 6855 /// inherited to the using shadow declaration in that base class (or a null 6856 /// pointer if the constructor was declared in that base class). 6857 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *> 6858 InheritedFromBases; 6859 6860 public: 6861 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, 6862 ConstructorUsingShadowDecl *Shadow) 6863 : S(S), UseLoc(UseLoc) { 6864 bool DiagnosedMultipleConstructedBases = false; 6865 CXXRecordDecl *ConstructedBase = nullptr; 6866 UsingDecl *ConstructedBaseUsing = nullptr; 6867 6868 // Find the set of such base class subobjects and check that there's a 6869 // unique constructed subobject. 6870 for (auto *D : Shadow->redecls()) { 6871 auto *DShadow = cast<ConstructorUsingShadowDecl>(D); 6872 auto *DNominatedBase = DShadow->getNominatedBaseClass(); 6873 auto *DConstructedBase = DShadow->getConstructedBaseClass(); 6874 6875 InheritedFromBases.insert( 6876 std::make_pair(DNominatedBase->getCanonicalDecl(), 6877 DShadow->getNominatedBaseClassShadowDecl())); 6878 if (DShadow->constructsVirtualBase()) 6879 InheritedFromBases.insert( 6880 std::make_pair(DConstructedBase->getCanonicalDecl(), 6881 DShadow->getConstructedBaseClassShadowDecl())); 6882 else 6883 assert(DNominatedBase == DConstructedBase); 6884 6885 // [class.inhctor.init]p2: 6886 // If the constructor was inherited from multiple base class subobjects 6887 // of type B, the program is ill-formed. 6888 if (!ConstructedBase) { 6889 ConstructedBase = DConstructedBase; 6890 ConstructedBaseUsing = D->getUsingDecl(); 6891 } else if (ConstructedBase != DConstructedBase && 6892 !Shadow->isInvalidDecl()) { 6893 if (!DiagnosedMultipleConstructedBases) { 6894 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor) 6895 << Shadow->getTargetDecl(); 6896 S.Diag(ConstructedBaseUsing->getLocation(), 6897 diag::note_ambiguous_inherited_constructor_using) 6898 << ConstructedBase; 6899 DiagnosedMultipleConstructedBases = true; 6900 } 6901 S.Diag(D->getUsingDecl()->getLocation(), 6902 diag::note_ambiguous_inherited_constructor_using) 6903 << DConstructedBase; 6904 } 6905 } 6906 6907 if (DiagnosedMultipleConstructedBases) 6908 Shadow->setInvalidDecl(); 6909 } 6910 6911 /// Find the constructor to use for inherited construction of a base class, 6912 /// and whether that base class constructor inherits the constructor from a 6913 /// virtual base class (in which case it won't actually invoke it). 6914 std::pair<CXXConstructorDecl *, bool> 6915 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const { 6916 auto It = InheritedFromBases.find(Base->getCanonicalDecl()); 6917 if (It == InheritedFromBases.end()) 6918 return std::make_pair(nullptr, false); 6919 6920 // This is an intermediary class. 6921 if (It->second) 6922 return std::make_pair( 6923 S.findInheritingConstructor(UseLoc, Ctor, It->second), 6924 It->second->constructsVirtualBase()); 6925 6926 // This is the base class from which the constructor was inherited. 6927 return std::make_pair(Ctor, false); 6928 } 6929 }; 6930 6931 /// Is the special member function which would be selected to perform the 6932 /// specified operation on the specified class type a constexpr constructor? 6933 static bool 6934 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 6935 Sema::CXXSpecialMember CSM, unsigned Quals, 6936 bool ConstRHS, 6937 CXXConstructorDecl *InheritedCtor = nullptr, 6938 Sema::InheritedConstructorInfo *Inherited = nullptr) { 6939 // If we're inheriting a constructor, see if we need to call it for this base 6940 // class. 6941 if (InheritedCtor) { 6942 assert(CSM == Sema::CXXDefaultConstructor); 6943 auto BaseCtor = 6944 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first; 6945 if (BaseCtor) 6946 return BaseCtor->isConstexpr(); 6947 } 6948 6949 if (CSM == Sema::CXXDefaultConstructor) 6950 return ClassDecl->hasConstexprDefaultConstructor(); 6951 if (CSM == Sema::CXXDestructor) 6952 return ClassDecl->hasConstexprDestructor(); 6953 6954 Sema::SpecialMemberOverloadResult SMOR = 6955 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 6956 if (!SMOR.getMethod()) 6957 // A constructor we wouldn't select can't be "involved in initializing" 6958 // anything. 6959 return true; 6960 return SMOR.getMethod()->isConstexpr(); 6961 } 6962 6963 /// Determine whether the specified special member function would be constexpr 6964 /// if it were implicitly defined. 6965 static bool defaultedSpecialMemberIsConstexpr( 6966 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, 6967 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr, 6968 Sema::InheritedConstructorInfo *Inherited = nullptr) { 6969 if (!S.getLangOpts().CPlusPlus11) 6970 return false; 6971 6972 // C++11 [dcl.constexpr]p4: 6973 // In the definition of a constexpr constructor [...] 6974 bool Ctor = true; 6975 switch (CSM) { 6976 case Sema::CXXDefaultConstructor: 6977 if (Inherited) 6978 break; 6979 // Since default constructor lookup is essentially trivial (and cannot 6980 // involve, for instance, template instantiation), we compute whether a 6981 // defaulted default constructor is constexpr directly within CXXRecordDecl. 6982 // 6983 // This is important for performance; we need to know whether the default 6984 // constructor is constexpr to determine whether the type is a literal type. 6985 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 6986 6987 case Sema::CXXCopyConstructor: 6988 case Sema::CXXMoveConstructor: 6989 // For copy or move constructors, we need to perform overload resolution. 6990 break; 6991 6992 case Sema::CXXCopyAssignment: 6993 case Sema::CXXMoveAssignment: 6994 if (!S.getLangOpts().CPlusPlus14) 6995 return false; 6996 // In C++1y, we need to perform overload resolution. 6997 Ctor = false; 6998 break; 6999 7000 case Sema::CXXDestructor: 7001 return ClassDecl->defaultedDestructorIsConstexpr(); 7002 7003 case Sema::CXXInvalid: 7004 return false; 7005 } 7006 7007 // -- if the class is a non-empty union, or for each non-empty anonymous 7008 // union member of a non-union class, exactly one non-static data member 7009 // shall be initialized; [DR1359] 7010 // 7011 // If we squint, this is guaranteed, since exactly one non-static data member 7012 // will be initialized (if the constructor isn't deleted), we just don't know 7013 // which one. 7014 if (Ctor && ClassDecl->isUnion()) 7015 return CSM == Sema::CXXDefaultConstructor 7016 ? ClassDecl->hasInClassInitializer() || 7017 !ClassDecl->hasVariantMembers() 7018 : true; 7019 7020 // -- the class shall not have any virtual base classes; 7021 if (Ctor && ClassDecl->getNumVBases()) 7022 return false; 7023 7024 // C++1y [class.copy]p26: 7025 // -- [the class] is a literal type, and 7026 if (!Ctor && !ClassDecl->isLiteral()) 7027 return false; 7028 7029 // -- every constructor involved in initializing [...] base class 7030 // sub-objects shall be a constexpr constructor; 7031 // -- the assignment operator selected to copy/move each direct base 7032 // class is a constexpr function, and 7033 for (const auto &B : ClassDecl->bases()) { 7034 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 7035 if (!BaseType) continue; 7036 7037 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 7038 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg, 7039 InheritedCtor, Inherited)) 7040 return false; 7041 } 7042 7043 // -- every constructor involved in initializing non-static data members 7044 // [...] shall be a constexpr constructor; 7045 // -- every non-static data member and base class sub-object shall be 7046 // initialized 7047 // -- for each non-static data member of X that is of class type (or array 7048 // thereof), the assignment operator selected to copy/move that member is 7049 // a constexpr function 7050 for (const auto *F : ClassDecl->fields()) { 7051 if (F->isInvalidDecl()) 7052 continue; 7053 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer()) 7054 continue; 7055 QualType BaseType = S.Context.getBaseElementType(F->getType()); 7056 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 7057 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 7058 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 7059 BaseType.getCVRQualifiers(), 7060 ConstArg && !F->isMutable())) 7061 return false; 7062 } else if (CSM == Sema::CXXDefaultConstructor) { 7063 return false; 7064 } 7065 } 7066 7067 // All OK, it's constexpr! 7068 return true; 7069 } 7070 7071 namespace { 7072 /// RAII object to register a defaulted function as having its exception 7073 /// specification computed. 7074 struct ComputingExceptionSpec { 7075 Sema &S; 7076 7077 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc) 7078 : S(S) { 7079 Sema::CodeSynthesisContext Ctx; 7080 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation; 7081 Ctx.PointOfInstantiation = Loc; 7082 Ctx.Entity = FD; 7083 S.pushCodeSynthesisContext(Ctx); 7084 } 7085 ~ComputingExceptionSpec() { 7086 S.popCodeSynthesisContext(); 7087 } 7088 }; 7089 } 7090 7091 static Sema::ImplicitExceptionSpecification 7092 ComputeDefaultedSpecialMemberExceptionSpec( 7093 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 7094 Sema::InheritedConstructorInfo *ICI); 7095 7096 static Sema::ImplicitExceptionSpecification 7097 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, 7098 FunctionDecl *FD, 7099 Sema::DefaultedComparisonKind DCK); 7100 7101 static Sema::ImplicitExceptionSpecification 7102 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) { 7103 auto DFK = S.getDefaultedFunctionKind(FD); 7104 if (DFK.isSpecialMember()) 7105 return ComputeDefaultedSpecialMemberExceptionSpec( 7106 S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr); 7107 if (DFK.isComparison()) 7108 return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD, 7109 DFK.asComparison()); 7110 7111 auto *CD = cast<CXXConstructorDecl>(FD); 7112 assert(CD->getInheritedConstructor() && 7113 "only defaulted functions and inherited constructors have implicit " 7114 "exception specs"); 7115 Sema::InheritedConstructorInfo ICI( 7116 S, Loc, CD->getInheritedConstructor().getShadowDecl()); 7117 return ComputeDefaultedSpecialMemberExceptionSpec( 7118 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI); 7119 } 7120 7121 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 7122 CXXMethodDecl *MD) { 7123 FunctionProtoType::ExtProtoInfo EPI; 7124 7125 // Build an exception specification pointing back at this member. 7126 EPI.ExceptionSpec.Type = EST_Unevaluated; 7127 EPI.ExceptionSpec.SourceDecl = MD; 7128 7129 // Set the calling convention to the default for C++ instance methods. 7130 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 7131 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 7132 /*IsCXXMethod=*/true)); 7133 return EPI; 7134 } 7135 7136 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) { 7137 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>(); 7138 if (FPT->getExceptionSpecType() != EST_Unevaluated) 7139 return; 7140 7141 // Evaluate the exception specification. 7142 auto IES = computeImplicitExceptionSpec(*this, Loc, FD); 7143 auto ESI = IES.getExceptionSpec(); 7144 7145 // Update the type of the special member to use it. 7146 UpdateExceptionSpec(FD, ESI); 7147 } 7148 7149 void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) { 7150 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted"); 7151 7152 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD); 7153 if (!DefKind) { 7154 assert(FD->getDeclContext()->isDependentContext()); 7155 return; 7156 } 7157 7158 if (DefKind.isSpecialMember() 7159 ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD), 7160 DefKind.asSpecialMember()) 7161 : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison())) 7162 FD->setInvalidDecl(); 7163 } 7164 7165 bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD, 7166 CXXSpecialMember CSM) { 7167 CXXRecordDecl *RD = MD->getParent(); 7168 7169 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 7170 "not an explicitly-defaulted special member"); 7171 7172 // Defer all checking for special members of a dependent type. 7173 if (RD->isDependentType()) 7174 return false; 7175 7176 // Whether this was the first-declared instance of the constructor. 7177 // This affects whether we implicitly add an exception spec and constexpr. 7178 bool First = MD == MD->getCanonicalDecl(); 7179 7180 bool HadError = false; 7181 7182 // C++11 [dcl.fct.def.default]p1: 7183 // A function that is explicitly defaulted shall 7184 // -- be a special member function [...] (checked elsewhere), 7185 // -- have the same type (except for ref-qualifiers, and except that a 7186 // copy operation can take a non-const reference) as an implicit 7187 // declaration, and 7188 // -- not have default arguments. 7189 // C++2a changes the second bullet to instead delete the function if it's 7190 // defaulted on its first declaration, unless it's "an assignment operator, 7191 // and its return type differs or its parameter type is not a reference". 7192 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First; 7193 bool ShouldDeleteForTypeMismatch = false; 7194 unsigned ExpectedParams = 1; 7195 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 7196 ExpectedParams = 0; 7197 if (MD->getNumParams() != ExpectedParams) { 7198 // This checks for default arguments: a copy or move constructor with a 7199 // default argument is classified as a default constructor, and assignment 7200 // operations and destructors can't have default arguments. 7201 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 7202 << CSM << MD->getSourceRange(); 7203 HadError = true; 7204 } else if (MD->isVariadic()) { 7205 if (DeleteOnTypeMismatch) 7206 ShouldDeleteForTypeMismatch = true; 7207 else { 7208 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 7209 << CSM << MD->getSourceRange(); 7210 HadError = true; 7211 } 7212 } 7213 7214 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 7215 7216 bool CanHaveConstParam = false; 7217 if (CSM == CXXCopyConstructor) 7218 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 7219 else if (CSM == CXXCopyAssignment) 7220 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 7221 7222 QualType ReturnType = Context.VoidTy; 7223 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 7224 // Check for return type matching. 7225 ReturnType = Type->getReturnType(); 7226 7227 QualType DeclType = Context.getTypeDeclType(RD); 7228 DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace()); 7229 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType); 7230 7231 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 7232 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 7233 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 7234 HadError = true; 7235 } 7236 7237 // A defaulted special member cannot have cv-qualifiers. 7238 if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) { 7239 if (DeleteOnTypeMismatch) 7240 ShouldDeleteForTypeMismatch = true; 7241 else { 7242 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 7243 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 7244 HadError = true; 7245 } 7246 } 7247 } 7248 7249 // Check for parameter type matching. 7250 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 7251 bool HasConstParam = false; 7252 if (ExpectedParams && ArgType->isReferenceType()) { 7253 // Argument must be reference to possibly-const T. 7254 QualType ReferentType = ArgType->getPointeeType(); 7255 HasConstParam = ReferentType.isConstQualified(); 7256 7257 if (ReferentType.isVolatileQualified()) { 7258 if (DeleteOnTypeMismatch) 7259 ShouldDeleteForTypeMismatch = true; 7260 else { 7261 Diag(MD->getLocation(), 7262 diag::err_defaulted_special_member_volatile_param) << CSM; 7263 HadError = true; 7264 } 7265 } 7266 7267 if (HasConstParam && !CanHaveConstParam) { 7268 if (DeleteOnTypeMismatch) 7269 ShouldDeleteForTypeMismatch = true; 7270 else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 7271 Diag(MD->getLocation(), 7272 diag::err_defaulted_special_member_copy_const_param) 7273 << (CSM == CXXCopyAssignment); 7274 // FIXME: Explain why this special member can't be const. 7275 HadError = true; 7276 } else { 7277 Diag(MD->getLocation(), 7278 diag::err_defaulted_special_member_move_const_param) 7279 << (CSM == CXXMoveAssignment); 7280 HadError = true; 7281 } 7282 } 7283 } else if (ExpectedParams) { 7284 // A copy assignment operator can take its argument by value, but a 7285 // defaulted one cannot. 7286 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 7287 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 7288 HadError = true; 7289 } 7290 7291 // C++11 [dcl.fct.def.default]p2: 7292 // An explicitly-defaulted function may be declared constexpr only if it 7293 // would have been implicitly declared as constexpr, 7294 // Do not apply this rule to members of class templates, since core issue 1358 7295 // makes such functions always instantiate to constexpr functions. For 7296 // functions which cannot be constexpr (for non-constructors in C++11 and for 7297 // destructors in C++14 and C++17), this is checked elsewhere. 7298 // 7299 // FIXME: This should not apply if the member is deleted. 7300 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 7301 HasConstParam); 7302 if ((getLangOpts().CPlusPlus20 || 7303 (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 7304 : isa<CXXConstructorDecl>(MD))) && 7305 MD->isConstexpr() && !Constexpr && 7306 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 7307 Diag(MD->getBeginLoc(), MD->isConsteval() 7308 ? diag::err_incorrect_defaulted_consteval 7309 : diag::err_incorrect_defaulted_constexpr) 7310 << CSM; 7311 // FIXME: Explain why the special member can't be constexpr. 7312 HadError = true; 7313 } 7314 7315 if (First) { 7316 // C++2a [dcl.fct.def.default]p3: 7317 // If a function is explicitly defaulted on its first declaration, it is 7318 // implicitly considered to be constexpr if the implicit declaration 7319 // would be. 7320 MD->setConstexprKind( 7321 Constexpr ? (MD->isConsteval() ? CSK_consteval : CSK_constexpr) 7322 : CSK_unspecified); 7323 7324 if (!Type->hasExceptionSpec()) { 7325 // C++2a [except.spec]p3: 7326 // If a declaration of a function does not have a noexcept-specifier 7327 // [and] is defaulted on its first declaration, [...] the exception 7328 // specification is as specified below 7329 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 7330 EPI.ExceptionSpec.Type = EST_Unevaluated; 7331 EPI.ExceptionSpec.SourceDecl = MD; 7332 MD->setType(Context.getFunctionType(ReturnType, 7333 llvm::makeArrayRef(&ArgType, 7334 ExpectedParams), 7335 EPI)); 7336 } 7337 } 7338 7339 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) { 7340 if (First) { 7341 SetDeclDeleted(MD, MD->getLocation()); 7342 if (!inTemplateInstantiation() && !HadError) { 7343 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM; 7344 if (ShouldDeleteForTypeMismatch) { 7345 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM; 7346 } else { 7347 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 7348 } 7349 } 7350 if (ShouldDeleteForTypeMismatch && !HadError) { 7351 Diag(MD->getLocation(), 7352 diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM; 7353 } 7354 } else { 7355 // C++11 [dcl.fct.def.default]p4: 7356 // [For a] user-provided explicitly-defaulted function [...] if such a 7357 // function is implicitly defined as deleted, the program is ill-formed. 7358 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 7359 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl"); 7360 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 7361 HadError = true; 7362 } 7363 } 7364 7365 return HadError; 7366 } 7367 7368 namespace { 7369 /// Helper class for building and checking a defaulted comparison. 7370 /// 7371 /// Defaulted functions are built in two phases: 7372 /// 7373 /// * First, the set of operations that the function will perform are 7374 /// identified, and some of them are checked. If any of the checked 7375 /// operations is invalid in certain ways, the comparison function is 7376 /// defined as deleted and no body is built. 7377 /// * Then, if the function is not defined as deleted, the body is built. 7378 /// 7379 /// This is accomplished by performing two visitation steps over the eventual 7380 /// body of the function. 7381 template<typename Derived, typename ResultList, typename Result, 7382 typename Subobject> 7383 class DefaultedComparisonVisitor { 7384 public: 7385 using DefaultedComparisonKind = Sema::DefaultedComparisonKind; 7386 7387 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7388 DefaultedComparisonKind DCK) 7389 : S(S), RD(RD), FD(FD), DCK(DCK) { 7390 if (auto *Info = FD->getDefaultedFunctionInfo()) { 7391 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an 7392 // UnresolvedSet to avoid this copy. 7393 Fns.assign(Info->getUnqualifiedLookups().begin(), 7394 Info->getUnqualifiedLookups().end()); 7395 } 7396 } 7397 7398 ResultList visit() { 7399 // The type of an lvalue naming a parameter of this function. 7400 QualType ParamLvalType = 7401 FD->getParamDecl(0)->getType().getNonReferenceType(); 7402 7403 ResultList Results; 7404 7405 switch (DCK) { 7406 case DefaultedComparisonKind::None: 7407 llvm_unreachable("not a defaulted comparison"); 7408 7409 case DefaultedComparisonKind::Equal: 7410 case DefaultedComparisonKind::ThreeWay: 7411 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers()); 7412 return Results; 7413 7414 case DefaultedComparisonKind::NotEqual: 7415 case DefaultedComparisonKind::Relational: 7416 Results.add(getDerived().visitExpandedSubobject( 7417 ParamLvalType, getDerived().getCompleteObject())); 7418 return Results; 7419 } 7420 llvm_unreachable(""); 7421 } 7422 7423 protected: 7424 Derived &getDerived() { return static_cast<Derived&>(*this); } 7425 7426 /// Visit the expanded list of subobjects of the given type, as specified in 7427 /// C++2a [class.compare.default]. 7428 /// 7429 /// \return \c true if the ResultList object said we're done, \c false if not. 7430 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record, 7431 Qualifiers Quals) { 7432 // C++2a [class.compare.default]p4: 7433 // The direct base class subobjects of C 7434 for (CXXBaseSpecifier &Base : Record->bases()) 7435 if (Results.add(getDerived().visitSubobject( 7436 S.Context.getQualifiedType(Base.getType(), Quals), 7437 getDerived().getBase(&Base)))) 7438 return true; 7439 7440 // followed by the non-static data members of C 7441 for (FieldDecl *Field : Record->fields()) { 7442 // Recursively expand anonymous structs. 7443 if (Field->isAnonymousStructOrUnion()) { 7444 if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(), 7445 Quals)) 7446 return true; 7447 continue; 7448 } 7449 7450 // Figure out the type of an lvalue denoting this field. 7451 Qualifiers FieldQuals = Quals; 7452 if (Field->isMutable()) 7453 FieldQuals.removeConst(); 7454 QualType FieldType = 7455 S.Context.getQualifiedType(Field->getType(), FieldQuals); 7456 7457 if (Results.add(getDerived().visitSubobject( 7458 FieldType, getDerived().getField(Field)))) 7459 return true; 7460 } 7461 7462 // form a list of subobjects. 7463 return false; 7464 } 7465 7466 Result visitSubobject(QualType Type, Subobject Subobj) { 7467 // In that list, any subobject of array type is recursively expanded 7468 const ArrayType *AT = S.Context.getAsArrayType(Type); 7469 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT)) 7470 return getDerived().visitSubobjectArray(CAT->getElementType(), 7471 CAT->getSize(), Subobj); 7472 return getDerived().visitExpandedSubobject(Type, Subobj); 7473 } 7474 7475 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size, 7476 Subobject Subobj) { 7477 return getDerived().visitSubobject(Type, Subobj); 7478 } 7479 7480 protected: 7481 Sema &S; 7482 CXXRecordDecl *RD; 7483 FunctionDecl *FD; 7484 DefaultedComparisonKind DCK; 7485 UnresolvedSet<16> Fns; 7486 }; 7487 7488 /// Information about a defaulted comparison, as determined by 7489 /// DefaultedComparisonAnalyzer. 7490 struct DefaultedComparisonInfo { 7491 bool Deleted = false; 7492 bool Constexpr = true; 7493 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering; 7494 7495 static DefaultedComparisonInfo deleted() { 7496 DefaultedComparisonInfo Deleted; 7497 Deleted.Deleted = true; 7498 return Deleted; 7499 } 7500 7501 bool add(const DefaultedComparisonInfo &R) { 7502 Deleted |= R.Deleted; 7503 Constexpr &= R.Constexpr; 7504 Category = commonComparisonType(Category, R.Category); 7505 return Deleted; 7506 } 7507 }; 7508 7509 /// An element in the expanded list of subobjects of a defaulted comparison, as 7510 /// specified in C++2a [class.compare.default]p4. 7511 struct DefaultedComparisonSubobject { 7512 enum { CompleteObject, Member, Base } Kind; 7513 NamedDecl *Decl; 7514 SourceLocation Loc; 7515 }; 7516 7517 /// A visitor over the notional body of a defaulted comparison that determines 7518 /// whether that body would be deleted or constexpr. 7519 class DefaultedComparisonAnalyzer 7520 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer, 7521 DefaultedComparisonInfo, 7522 DefaultedComparisonInfo, 7523 DefaultedComparisonSubobject> { 7524 public: 7525 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr }; 7526 7527 private: 7528 DiagnosticKind Diagnose; 7529 7530 public: 7531 using Base = DefaultedComparisonVisitor; 7532 using Result = DefaultedComparisonInfo; 7533 using Subobject = DefaultedComparisonSubobject; 7534 7535 friend Base; 7536 7537 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7538 DefaultedComparisonKind DCK, 7539 DiagnosticKind Diagnose = NoDiagnostics) 7540 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {} 7541 7542 Result visit() { 7543 if ((DCK == DefaultedComparisonKind::Equal || 7544 DCK == DefaultedComparisonKind::ThreeWay) && 7545 RD->hasVariantMembers()) { 7546 // C++2a [class.compare.default]p2 [P2002R0]: 7547 // A defaulted comparison operator function for class C is defined as 7548 // deleted if [...] C has variant members. 7549 if (Diagnose == ExplainDeleted) { 7550 S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union) 7551 << FD << RD->isUnion() << RD; 7552 } 7553 return Result::deleted(); 7554 } 7555 7556 return Base::visit(); 7557 } 7558 7559 private: 7560 Subobject getCompleteObject() { 7561 return Subobject{Subobject::CompleteObject, nullptr, FD->getLocation()}; 7562 } 7563 7564 Subobject getBase(CXXBaseSpecifier *Base) { 7565 return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(), 7566 Base->getBaseTypeLoc()}; 7567 } 7568 7569 Subobject getField(FieldDecl *Field) { 7570 return Subobject{Subobject::Member, Field, Field->getLocation()}; 7571 } 7572 7573 Result visitExpandedSubobject(QualType Type, Subobject Subobj) { 7574 // C++2a [class.compare.default]p2 [P2002R0]: 7575 // A defaulted <=> or == operator function for class C is defined as 7576 // deleted if any non-static data member of C is of reference type 7577 if (Type->isReferenceType()) { 7578 if (Diagnose == ExplainDeleted) { 7579 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member) 7580 << FD << RD; 7581 } 7582 return Result::deleted(); 7583 } 7584 7585 // [...] Let xi be an lvalue denoting the ith element [...] 7586 OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue); 7587 Expr *Args[] = {&Xi, &Xi}; 7588 7589 // All operators start by trying to apply that same operator recursively. 7590 OverloadedOperatorKind OO = FD->getOverloadedOperator(); 7591 assert(OO != OO_None && "not an overloaded operator!"); 7592 return visitBinaryOperator(OO, Args, Subobj); 7593 } 7594 7595 Result 7596 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args, 7597 Subobject Subobj, 7598 OverloadCandidateSet *SpaceshipCandidates = nullptr) { 7599 // Note that there is no need to consider rewritten candidates here if 7600 // we've already found there is no viable 'operator<=>' candidate (and are 7601 // considering synthesizing a '<=>' from '==' and '<'). 7602 OverloadCandidateSet CandidateSet( 7603 FD->getLocation(), OverloadCandidateSet::CSK_Operator, 7604 OverloadCandidateSet::OperatorRewriteInfo( 7605 OO, /*AllowRewrittenCandidates=*/!SpaceshipCandidates)); 7606 7607 /// C++2a [class.compare.default]p1 [P2002R0]: 7608 /// [...] the defaulted function itself is never a candidate for overload 7609 /// resolution [...] 7610 CandidateSet.exclude(FD); 7611 7612 if (Args[0]->getType()->isOverloadableType()) 7613 S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args); 7614 else { 7615 // FIXME: We determine whether this is a valid expression by checking to 7616 // see if there's a viable builtin operator candidate for it. That isn't 7617 // really what the rules ask us to do, but should give the right results. 7618 S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet); 7619 } 7620 7621 Result R; 7622 7623 OverloadCandidateSet::iterator Best; 7624 switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) { 7625 case OR_Success: { 7626 // C++2a [class.compare.secondary]p2 [P2002R0]: 7627 // The operator function [...] is defined as deleted if [...] the 7628 // candidate selected by overload resolution is not a rewritten 7629 // candidate. 7630 if ((DCK == DefaultedComparisonKind::NotEqual || 7631 DCK == DefaultedComparisonKind::Relational) && 7632 !Best->RewriteKind) { 7633 if (Diagnose == ExplainDeleted) { 7634 S.Diag(Best->Function->getLocation(), 7635 diag::note_defaulted_comparison_not_rewritten_callee) 7636 << FD; 7637 } 7638 return Result::deleted(); 7639 } 7640 7641 // Throughout C++2a [class.compare]: if overload resolution does not 7642 // result in a usable function, the candidate function is defined as 7643 // deleted. This requires that we selected an accessible function. 7644 // 7645 // Note that this only considers the access of the function when named 7646 // within the type of the subobject, and not the access path for any 7647 // derived-to-base conversion. 7648 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl(); 7649 if (ArgClass && Best->FoundDecl.getDecl() && 7650 Best->FoundDecl.getDecl()->isCXXClassMember()) { 7651 QualType ObjectType = Subobj.Kind == Subobject::Member 7652 ? Args[0]->getType() 7653 : S.Context.getRecordType(RD); 7654 if (!S.isMemberAccessibleForDeletion( 7655 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc, 7656 Diagnose == ExplainDeleted 7657 ? S.PDiag(diag::note_defaulted_comparison_inaccessible) 7658 << FD << Subobj.Kind << Subobj.Decl 7659 : S.PDiag())) 7660 return Result::deleted(); 7661 } 7662 7663 // C++2a [class.compare.default]p3 [P2002R0]: 7664 // A defaulted comparison function is constexpr-compatible if [...] 7665 // no overlod resolution performed [...] results in a non-constexpr 7666 // function. 7667 if (FunctionDecl *BestFD = Best->Function) { 7668 assert(!BestFD->isDeleted() && "wrong overload resolution result"); 7669 // If it's not constexpr, explain why not. 7670 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) { 7671 if (Subobj.Kind != Subobject::CompleteObject) 7672 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr) 7673 << Subobj.Kind << Subobj.Decl; 7674 S.Diag(BestFD->getLocation(), 7675 diag::note_defaulted_comparison_not_constexpr_here); 7676 // Bail out after explaining; we don't want any more notes. 7677 return Result::deleted(); 7678 } 7679 R.Constexpr &= BestFD->isConstexpr(); 7680 } 7681 7682 if (OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType()) { 7683 if (auto *BestFD = Best->Function) { 7684 // If any callee has an undeduced return type, deduce it now. 7685 // FIXME: It's not clear how a failure here should be handled. For 7686 // now, we produce an eager diagnostic, because that is forward 7687 // compatible with most (all?) other reasonable options. 7688 if (BestFD->getReturnType()->isUndeducedType() && 7689 S.DeduceReturnType(BestFD, FD->getLocation(), 7690 /*Diagnose=*/false)) { 7691 // Don't produce a duplicate error when asked to explain why the 7692 // comparison is deleted: we diagnosed that when initially checking 7693 // the defaulted operator. 7694 if (Diagnose == NoDiagnostics) { 7695 S.Diag( 7696 FD->getLocation(), 7697 diag::err_defaulted_comparison_cannot_deduce_undeduced_auto) 7698 << Subobj.Kind << Subobj.Decl; 7699 S.Diag( 7700 Subobj.Loc, 7701 diag::note_defaulted_comparison_cannot_deduce_undeduced_auto) 7702 << Subobj.Kind << Subobj.Decl; 7703 S.Diag(BestFD->getLocation(), 7704 diag::note_defaulted_comparison_cannot_deduce_callee) 7705 << Subobj.Kind << Subobj.Decl; 7706 } 7707 return Result::deleted(); 7708 } 7709 if (auto *Info = S.Context.CompCategories.lookupInfoForType( 7710 BestFD->getCallResultType())) { 7711 R.Category = Info->Kind; 7712 } else { 7713 if (Diagnose == ExplainDeleted) { 7714 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce) 7715 << Subobj.Kind << Subobj.Decl 7716 << BestFD->getCallResultType().withoutLocalFastQualifiers(); 7717 S.Diag(BestFD->getLocation(), 7718 diag::note_defaulted_comparison_cannot_deduce_callee) 7719 << Subobj.Kind << Subobj.Decl; 7720 } 7721 return Result::deleted(); 7722 } 7723 } else { 7724 Optional<ComparisonCategoryType> Cat = 7725 getComparisonCategoryForBuiltinCmp(Args[0]->getType()); 7726 assert(Cat && "no category for builtin comparison?"); 7727 R.Category = *Cat; 7728 } 7729 } 7730 7731 // Note that we might be rewriting to a different operator. That call is 7732 // not considered until we come to actually build the comparison function. 7733 break; 7734 } 7735 7736 case OR_Ambiguous: 7737 if (Diagnose == ExplainDeleted) { 7738 unsigned Kind = 0; 7739 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship) 7740 Kind = OO == OO_EqualEqual ? 1 : 2; 7741 CandidateSet.NoteCandidates( 7742 PartialDiagnosticAt( 7743 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous) 7744 << FD << Kind << Subobj.Kind << Subobj.Decl), 7745 S, OCD_AmbiguousCandidates, Args); 7746 } 7747 R = Result::deleted(); 7748 break; 7749 7750 case OR_Deleted: 7751 if (Diagnose == ExplainDeleted) { 7752 if ((DCK == DefaultedComparisonKind::NotEqual || 7753 DCK == DefaultedComparisonKind::Relational) && 7754 !Best->RewriteKind) { 7755 S.Diag(Best->Function->getLocation(), 7756 diag::note_defaulted_comparison_not_rewritten_callee) 7757 << FD; 7758 } else { 7759 S.Diag(Subobj.Loc, 7760 diag::note_defaulted_comparison_calls_deleted) 7761 << FD << Subobj.Kind << Subobj.Decl; 7762 S.NoteDeletedFunction(Best->Function); 7763 } 7764 } 7765 R = Result::deleted(); 7766 break; 7767 7768 case OR_No_Viable_Function: 7769 // If there's no usable candidate, we're done unless we can rewrite a 7770 // '<=>' in terms of '==' and '<'. 7771 if (OO == OO_Spaceship && 7772 S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) { 7773 // For any kind of comparison category return type, we need a usable 7774 // '==' and a usable '<'. 7775 if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj, 7776 &CandidateSet))) 7777 R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet)); 7778 break; 7779 } 7780 7781 if (Diagnose == ExplainDeleted) { 7782 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function) 7783 << FD << Subobj.Kind << Subobj.Decl; 7784 7785 // For a three-way comparison, list both the candidates for the 7786 // original operator and the candidates for the synthesized operator. 7787 if (SpaceshipCandidates) { 7788 SpaceshipCandidates->NoteCandidates( 7789 S, Args, 7790 SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates, 7791 Args, FD->getLocation())); 7792 S.Diag(Subobj.Loc, 7793 diag::note_defaulted_comparison_no_viable_function_synthesized) 7794 << (OO == OO_EqualEqual ? 0 : 1); 7795 } 7796 7797 CandidateSet.NoteCandidates( 7798 S, Args, 7799 CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args, 7800 FD->getLocation())); 7801 } 7802 R = Result::deleted(); 7803 break; 7804 } 7805 7806 return R; 7807 } 7808 }; 7809 7810 /// A list of statements. 7811 struct StmtListResult { 7812 bool IsInvalid = false; 7813 llvm::SmallVector<Stmt*, 16> Stmts; 7814 7815 bool add(const StmtResult &S) { 7816 IsInvalid |= S.isInvalid(); 7817 if (IsInvalid) 7818 return true; 7819 Stmts.push_back(S.get()); 7820 return false; 7821 } 7822 }; 7823 7824 /// A visitor over the notional body of a defaulted comparison that synthesizes 7825 /// the actual body. 7826 class DefaultedComparisonSynthesizer 7827 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer, 7828 StmtListResult, StmtResult, 7829 std::pair<ExprResult, ExprResult>> { 7830 SourceLocation Loc; 7831 unsigned ArrayDepth = 0; 7832 7833 public: 7834 using Base = DefaultedComparisonVisitor; 7835 using ExprPair = std::pair<ExprResult, ExprResult>; 7836 7837 friend Base; 7838 7839 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7840 DefaultedComparisonKind DCK, 7841 SourceLocation BodyLoc) 7842 : Base(S, RD, FD, DCK), Loc(BodyLoc) {} 7843 7844 /// Build a suitable function body for this defaulted comparison operator. 7845 StmtResult build() { 7846 Sema::CompoundScopeRAII CompoundScope(S); 7847 7848 StmtListResult Stmts = visit(); 7849 if (Stmts.IsInvalid) 7850 return StmtError(); 7851 7852 ExprResult RetVal; 7853 switch (DCK) { 7854 case DefaultedComparisonKind::None: 7855 llvm_unreachable("not a defaulted comparison"); 7856 7857 case DefaultedComparisonKind::Equal: { 7858 // C++2a [class.eq]p3: 7859 // [...] compar[e] the corresponding elements [...] until the first 7860 // index i where xi == yi yields [...] false. If no such index exists, 7861 // V is true. Otherwise, V is false. 7862 // 7863 // Join the comparisons with '&&'s and return the result. Use a right 7864 // fold (traversing the conditions right-to-left), because that 7865 // short-circuits more naturally. 7866 auto OldStmts = std::move(Stmts.Stmts); 7867 Stmts.Stmts.clear(); 7868 ExprResult CmpSoFar; 7869 // Finish a particular comparison chain. 7870 auto FinishCmp = [&] { 7871 if (Expr *Prior = CmpSoFar.get()) { 7872 // Convert the last expression to 'return ...;' 7873 if (RetVal.isUnset() && Stmts.Stmts.empty()) 7874 RetVal = CmpSoFar; 7875 // Convert any prior comparison to 'if (!(...)) return false;' 7876 else if (Stmts.add(buildIfNotCondReturnFalse(Prior))) 7877 return true; 7878 CmpSoFar = ExprResult(); 7879 } 7880 return false; 7881 }; 7882 for (Stmt *EAsStmt : llvm::reverse(OldStmts)) { 7883 Expr *E = dyn_cast<Expr>(EAsStmt); 7884 if (!E) { 7885 // Found an array comparison. 7886 if (FinishCmp() || Stmts.add(EAsStmt)) 7887 return StmtError(); 7888 continue; 7889 } 7890 7891 if (CmpSoFar.isUnset()) { 7892 CmpSoFar = E; 7893 continue; 7894 } 7895 CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get()); 7896 if (CmpSoFar.isInvalid()) 7897 return StmtError(); 7898 } 7899 if (FinishCmp()) 7900 return StmtError(); 7901 std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end()); 7902 // If no such index exists, V is true. 7903 if (RetVal.isUnset()) 7904 RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true); 7905 break; 7906 } 7907 7908 case DefaultedComparisonKind::ThreeWay: { 7909 // Per C++2a [class.spaceship]p3, as a fallback add: 7910 // return static_cast<R>(std::strong_ordering::equal); 7911 QualType StrongOrdering = S.CheckComparisonCategoryType( 7912 ComparisonCategoryType::StrongOrdering, Loc, 7913 Sema::ComparisonCategoryUsage::DefaultedOperator); 7914 if (StrongOrdering.isNull()) 7915 return StmtError(); 7916 VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering) 7917 .getValueInfo(ComparisonCategoryResult::Equal) 7918 ->VD; 7919 RetVal = getDecl(EqualVD); 7920 if (RetVal.isInvalid()) 7921 return StmtError(); 7922 RetVal = buildStaticCastToR(RetVal.get()); 7923 break; 7924 } 7925 7926 case DefaultedComparisonKind::NotEqual: 7927 case DefaultedComparisonKind::Relational: 7928 RetVal = cast<Expr>(Stmts.Stmts.pop_back_val()); 7929 break; 7930 } 7931 7932 // Build the final return statement. 7933 if (RetVal.isInvalid()) 7934 return StmtError(); 7935 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get()); 7936 if (ReturnStmt.isInvalid()) 7937 return StmtError(); 7938 Stmts.Stmts.push_back(ReturnStmt.get()); 7939 7940 return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false); 7941 } 7942 7943 private: 7944 ExprResult getDecl(ValueDecl *VD) { 7945 return S.BuildDeclarationNameExpr( 7946 CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD); 7947 } 7948 7949 ExprResult getParam(unsigned I) { 7950 ParmVarDecl *PD = FD->getParamDecl(I); 7951 return getDecl(PD); 7952 } 7953 7954 ExprPair getCompleteObject() { 7955 unsigned Param = 0; 7956 ExprResult LHS; 7957 if (isa<CXXMethodDecl>(FD)) { 7958 // LHS is '*this'. 7959 LHS = S.ActOnCXXThis(Loc); 7960 if (!LHS.isInvalid()) 7961 LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get()); 7962 } else { 7963 LHS = getParam(Param++); 7964 } 7965 ExprResult RHS = getParam(Param++); 7966 assert(Param == FD->getNumParams()); 7967 return {LHS, RHS}; 7968 } 7969 7970 ExprPair getBase(CXXBaseSpecifier *Base) { 7971 ExprPair Obj = getCompleteObject(); 7972 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 7973 return {ExprError(), ExprError()}; 7974 CXXCastPath Path = {Base}; 7975 return {S.ImpCastExprToType(Obj.first.get(), Base->getType(), 7976 CK_DerivedToBase, VK_LValue, &Path), 7977 S.ImpCastExprToType(Obj.second.get(), Base->getType(), 7978 CK_DerivedToBase, VK_LValue, &Path)}; 7979 } 7980 7981 ExprPair getField(FieldDecl *Field) { 7982 ExprPair Obj = getCompleteObject(); 7983 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 7984 return {ExprError(), ExprError()}; 7985 7986 DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess()); 7987 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc); 7988 return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc, 7989 CXXScopeSpec(), Field, Found, NameInfo), 7990 S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc, 7991 CXXScopeSpec(), Field, Found, NameInfo)}; 7992 } 7993 7994 // FIXME: When expanding a subobject, register a note in the code synthesis 7995 // stack to say which subobject we're comparing. 7996 7997 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) { 7998 if (Cond.isInvalid()) 7999 return StmtError(); 8000 8001 ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get()); 8002 if (NotCond.isInvalid()) 8003 return StmtError(); 8004 8005 ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false); 8006 assert(!False.isInvalid() && "should never fail"); 8007 StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get()); 8008 if (ReturnFalse.isInvalid()) 8009 return StmtError(); 8010 8011 return S.ActOnIfStmt(Loc, false, nullptr, 8012 S.ActOnCondition(nullptr, Loc, NotCond.get(), 8013 Sema::ConditionKind::Boolean), 8014 ReturnFalse.get(), SourceLocation(), nullptr); 8015 } 8016 8017 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size, 8018 ExprPair Subobj) { 8019 QualType SizeType = S.Context.getSizeType(); 8020 Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType)); 8021 8022 // Build 'size_t i$n = 0'. 8023 IdentifierInfo *IterationVarName = nullptr; 8024 { 8025 SmallString<8> Str; 8026 llvm::raw_svector_ostream OS(Str); 8027 OS << "i" << ArrayDepth; 8028 IterationVarName = &S.Context.Idents.get(OS.str()); 8029 } 8030 VarDecl *IterationVar = VarDecl::Create( 8031 S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType, 8032 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None); 8033 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 8034 IterationVar->setInit( 8035 IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 8036 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc); 8037 8038 auto IterRef = [&] { 8039 ExprResult Ref = S.BuildDeclarationNameExpr( 8040 CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc), 8041 IterationVar); 8042 assert(!Ref.isInvalid() && "can't reference our own variable?"); 8043 return Ref.get(); 8044 }; 8045 8046 // Build 'i$n != Size'. 8047 ExprResult Cond = S.CreateBuiltinBinOp( 8048 Loc, BO_NE, IterRef(), 8049 IntegerLiteral::Create(S.Context, Size, SizeType, Loc)); 8050 assert(!Cond.isInvalid() && "should never fail"); 8051 8052 // Build '++i$n'. 8053 ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef()); 8054 assert(!Inc.isInvalid() && "should never fail"); 8055 8056 // Build 'a[i$n]' and 'b[i$n]'. 8057 auto Index = [&](ExprResult E) { 8058 if (E.isInvalid()) 8059 return ExprError(); 8060 return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc); 8061 }; 8062 Subobj.first = Index(Subobj.first); 8063 Subobj.second = Index(Subobj.second); 8064 8065 // Compare the array elements. 8066 ++ArrayDepth; 8067 StmtResult Substmt = visitSubobject(Type, Subobj); 8068 --ArrayDepth; 8069 8070 if (Substmt.isInvalid()) 8071 return StmtError(); 8072 8073 // For the inner level of an 'operator==', build 'if (!cmp) return false;'. 8074 // For outer levels or for an 'operator<=>' we already have a suitable 8075 // statement that returns as necessary. 8076 if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) { 8077 assert(DCK == DefaultedComparisonKind::Equal && 8078 "should have non-expression statement"); 8079 Substmt = buildIfNotCondReturnFalse(ElemCmp); 8080 if (Substmt.isInvalid()) 8081 return StmtError(); 8082 } 8083 8084 // Build 'for (...) ...' 8085 return S.ActOnForStmt(Loc, Loc, Init, 8086 S.ActOnCondition(nullptr, Loc, Cond.get(), 8087 Sema::ConditionKind::Boolean), 8088 S.MakeFullDiscardedValueExpr(Inc.get()), Loc, 8089 Substmt.get()); 8090 } 8091 8092 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) { 8093 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 8094 return StmtError(); 8095 8096 OverloadedOperatorKind OO = FD->getOverloadedOperator(); 8097 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO); 8098 ExprResult Op; 8099 if (Type->isOverloadableType()) 8100 Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(), 8101 Obj.second.get(), /*PerformADL=*/true, 8102 /*AllowRewrittenCandidates=*/true, FD); 8103 else 8104 Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get()); 8105 if (Op.isInvalid()) 8106 return StmtError(); 8107 8108 switch (DCK) { 8109 case DefaultedComparisonKind::None: 8110 llvm_unreachable("not a defaulted comparison"); 8111 8112 case DefaultedComparisonKind::Equal: 8113 // Per C++2a [class.eq]p2, each comparison is individually contextually 8114 // converted to bool. 8115 Op = S.PerformContextuallyConvertToBool(Op.get()); 8116 if (Op.isInvalid()) 8117 return StmtError(); 8118 return Op.get(); 8119 8120 case DefaultedComparisonKind::ThreeWay: { 8121 // Per C++2a [class.spaceship]p3, form: 8122 // if (R cmp = static_cast<R>(op); cmp != 0) 8123 // return cmp; 8124 QualType R = FD->getReturnType(); 8125 Op = buildStaticCastToR(Op.get()); 8126 if (Op.isInvalid()) 8127 return StmtError(); 8128 8129 // R cmp = ...; 8130 IdentifierInfo *Name = &S.Context.Idents.get("cmp"); 8131 VarDecl *VD = 8132 VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R, 8133 S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None); 8134 S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false); 8135 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc); 8136 8137 // cmp != 0 8138 ExprResult VDRef = getDecl(VD); 8139 if (VDRef.isInvalid()) 8140 return StmtError(); 8141 llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0); 8142 Expr *Zero = 8143 IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc); 8144 ExprResult Comp; 8145 if (VDRef.get()->getType()->isOverloadableType()) 8146 Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true, 8147 true, FD); 8148 else 8149 Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero); 8150 if (Comp.isInvalid()) 8151 return StmtError(); 8152 Sema::ConditionResult Cond = S.ActOnCondition( 8153 nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean); 8154 if (Cond.isInvalid()) 8155 return StmtError(); 8156 8157 // return cmp; 8158 VDRef = getDecl(VD); 8159 if (VDRef.isInvalid()) 8160 return StmtError(); 8161 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get()); 8162 if (ReturnStmt.isInvalid()) 8163 return StmtError(); 8164 8165 // if (...) 8166 return S.ActOnIfStmt(Loc, /*IsConstexpr=*/false, InitStmt, Cond, 8167 ReturnStmt.get(), /*ElseLoc=*/SourceLocation(), 8168 /*Else=*/nullptr); 8169 } 8170 8171 case DefaultedComparisonKind::NotEqual: 8172 case DefaultedComparisonKind::Relational: 8173 // C++2a [class.compare.secondary]p2: 8174 // Otherwise, the operator function yields x @ y. 8175 return Op.get(); 8176 } 8177 llvm_unreachable(""); 8178 } 8179 8180 /// Build "static_cast<R>(E)". 8181 ExprResult buildStaticCastToR(Expr *E) { 8182 QualType R = FD->getReturnType(); 8183 assert(!R->isUndeducedType() && "type should have been deduced already"); 8184 8185 // Don't bother forming a no-op cast in the common case. 8186 if (E->isRValue() && S.Context.hasSameType(E->getType(), R)) 8187 return E; 8188 return S.BuildCXXNamedCast(Loc, tok::kw_static_cast, 8189 S.Context.getTrivialTypeSourceInfo(R, Loc), E, 8190 SourceRange(Loc, Loc), SourceRange(Loc, Loc)); 8191 } 8192 }; 8193 } 8194 8195 /// Perform the unqualified lookups that might be needed to form a defaulted 8196 /// comparison function for the given operator. 8197 static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S, 8198 UnresolvedSetImpl &Operators, 8199 OverloadedOperatorKind Op) { 8200 auto Lookup = [&](OverloadedOperatorKind OO) { 8201 Self.LookupOverloadedOperatorName(OO, S, QualType(), QualType(), Operators); 8202 }; 8203 8204 // Every defaulted operator looks up itself. 8205 Lookup(Op); 8206 // ... and the rewritten form of itself, if any. 8207 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op)) 8208 Lookup(ExtraOp); 8209 8210 // For 'operator<=>', we also form a 'cmp != 0' expression, and might 8211 // synthesize a three-way comparison from '<' and '=='. In a dependent 8212 // context, we also need to look up '==' in case we implicitly declare a 8213 // defaulted 'operator=='. 8214 if (Op == OO_Spaceship) { 8215 Lookup(OO_ExclaimEqual); 8216 Lookup(OO_Less); 8217 Lookup(OO_EqualEqual); 8218 } 8219 } 8220 8221 bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD, 8222 DefaultedComparisonKind DCK) { 8223 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison"); 8224 8225 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()); 8226 assert(RD && "defaulted comparison is not defaulted in a class"); 8227 8228 // Perform any unqualified lookups we're going to need to default this 8229 // function. 8230 if (S) { 8231 UnresolvedSet<32> Operators; 8232 lookupOperatorsForDefaultedComparison(*this, S, Operators, 8233 FD->getOverloadedOperator()); 8234 FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create( 8235 Context, Operators.pairs())); 8236 } 8237 8238 // C++2a [class.compare.default]p1: 8239 // A defaulted comparison operator function for some class C shall be a 8240 // non-template function declared in the member-specification of C that is 8241 // -- a non-static const member of C having one parameter of type 8242 // const C&, or 8243 // -- a friend of C having two parameters of type const C& or two 8244 // parameters of type C. 8245 QualType ExpectedParmType1 = Context.getRecordType(RD); 8246 QualType ExpectedParmType2 = 8247 Context.getLValueReferenceType(ExpectedParmType1.withConst()); 8248 if (isa<CXXMethodDecl>(FD)) 8249 ExpectedParmType1 = ExpectedParmType2; 8250 for (const ParmVarDecl *Param : FD->parameters()) { 8251 if (!Param->getType()->isDependentType() && 8252 !Context.hasSameType(Param->getType(), ExpectedParmType1) && 8253 !Context.hasSameType(Param->getType(), ExpectedParmType2)) { 8254 // Don't diagnose an implicit 'operator=='; we will have diagnosed the 8255 // corresponding defaulted 'operator<=>' already. 8256 if (!FD->isImplicit()) { 8257 Diag(FD->getLocation(), diag::err_defaulted_comparison_param) 8258 << (int)DCK << Param->getType() << ExpectedParmType1 8259 << !isa<CXXMethodDecl>(FD) 8260 << ExpectedParmType2 << Param->getSourceRange(); 8261 } 8262 return true; 8263 } 8264 } 8265 if (FD->getNumParams() == 2 && 8266 !Context.hasSameType(FD->getParamDecl(0)->getType(), 8267 FD->getParamDecl(1)->getType())) { 8268 if (!FD->isImplicit()) { 8269 Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch) 8270 << (int)DCK 8271 << FD->getParamDecl(0)->getType() 8272 << FD->getParamDecl(0)->getSourceRange() 8273 << FD->getParamDecl(1)->getType() 8274 << FD->getParamDecl(1)->getSourceRange(); 8275 } 8276 return true; 8277 } 8278 8279 // ... non-static const member ... 8280 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 8281 assert(!MD->isStatic() && "comparison function cannot be a static member"); 8282 if (!MD->isConst()) { 8283 SourceLocation InsertLoc; 8284 if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc()) 8285 InsertLoc = getLocForEndOfToken(Loc.getRParenLoc()); 8286 // Don't diagnose an implicit 'operator=='; we will have diagnosed the 8287 // corresponding defaulted 'operator<=>' already. 8288 if (!MD->isImplicit()) { 8289 Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const) 8290 << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const"); 8291 } 8292 8293 // Add the 'const' to the type to recover. 8294 const auto *FPT = MD->getType()->castAs<FunctionProtoType>(); 8295 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8296 EPI.TypeQuals.addConst(); 8297 MD->setType(Context.getFunctionType(FPT->getReturnType(), 8298 FPT->getParamTypes(), EPI)); 8299 } 8300 } else { 8301 // A non-member function declared in a class must be a friend. 8302 assert(FD->getFriendObjectKind() && "expected a friend declaration"); 8303 } 8304 8305 // C++2a [class.eq]p1, [class.rel]p1: 8306 // A [defaulted comparison other than <=>] shall have a declared return 8307 // type bool. 8308 if (DCK != DefaultedComparisonKind::ThreeWay && 8309 !FD->getDeclaredReturnType()->isDependentType() && 8310 !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) { 8311 Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool) 8312 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy 8313 << FD->getReturnTypeSourceRange(); 8314 return true; 8315 } 8316 // C++2a [class.spaceship]p2 [P2002R0]: 8317 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise, 8318 // R shall not contain a placeholder type. 8319 if (DCK == DefaultedComparisonKind::ThreeWay && 8320 FD->getDeclaredReturnType()->getContainedDeducedType() && 8321 !Context.hasSameType(FD->getDeclaredReturnType(), 8322 Context.getAutoDeductType())) { 8323 Diag(FD->getLocation(), 8324 diag::err_defaulted_comparison_deduced_return_type_not_auto) 8325 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy 8326 << FD->getReturnTypeSourceRange(); 8327 return true; 8328 } 8329 8330 // For a defaulted function in a dependent class, defer all remaining checks 8331 // until instantiation. 8332 if (RD->isDependentType()) 8333 return false; 8334 8335 // Determine whether the function should be defined as deleted. 8336 DefaultedComparisonInfo Info = 8337 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit(); 8338 8339 bool First = FD == FD->getCanonicalDecl(); 8340 8341 // If we want to delete the function, then do so; there's nothing else to 8342 // check in that case. 8343 if (Info.Deleted) { 8344 if (!First) { 8345 // C++11 [dcl.fct.def.default]p4: 8346 // [For a] user-provided explicitly-defaulted function [...] if such a 8347 // function is implicitly defined as deleted, the program is ill-formed. 8348 // 8349 // This is really just a consequence of the general rule that you can 8350 // only delete a function on its first declaration. 8351 Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes) 8352 << FD->isImplicit() << (int)DCK; 8353 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8354 DefaultedComparisonAnalyzer::ExplainDeleted) 8355 .visit(); 8356 return true; 8357 } 8358 8359 SetDeclDeleted(FD, FD->getLocation()); 8360 if (!inTemplateInstantiation() && !FD->isImplicit()) { 8361 Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted) 8362 << (int)DCK; 8363 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8364 DefaultedComparisonAnalyzer::ExplainDeleted) 8365 .visit(); 8366 } 8367 return false; 8368 } 8369 8370 // C++2a [class.spaceship]p2: 8371 // The return type is deduced as the common comparison type of R0, R1, ... 8372 if (DCK == DefaultedComparisonKind::ThreeWay && 8373 FD->getDeclaredReturnType()->isUndeducedAutoType()) { 8374 SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin(); 8375 if (RetLoc.isInvalid()) 8376 RetLoc = FD->getBeginLoc(); 8377 // FIXME: Should we really care whether we have the complete type and the 8378 // 'enumerator' constants here? A forward declaration seems sufficient. 8379 QualType Cat = CheckComparisonCategoryType( 8380 Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator); 8381 if (Cat.isNull()) 8382 return true; 8383 Context.adjustDeducedFunctionResultType( 8384 FD, SubstAutoType(FD->getDeclaredReturnType(), Cat)); 8385 } 8386 8387 // C++2a [dcl.fct.def.default]p3 [P2002R0]: 8388 // An explicitly-defaulted function that is not defined as deleted may be 8389 // declared constexpr or consteval only if it is constexpr-compatible. 8390 // C++2a [class.compare.default]p3 [P2002R0]: 8391 // A defaulted comparison function is constexpr-compatible if it satisfies 8392 // the requirements for a constexpr function [...] 8393 // The only relevant requirements are that the parameter and return types are 8394 // literal types. The remaining conditions are checked by the analyzer. 8395 if (FD->isConstexpr()) { 8396 if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) && 8397 CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) && 8398 !Info.Constexpr) { 8399 Diag(FD->getBeginLoc(), 8400 diag::err_incorrect_defaulted_comparison_constexpr) 8401 << FD->isImplicit() << (int)DCK << FD->isConsteval(); 8402 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 8403 DefaultedComparisonAnalyzer::ExplainConstexpr) 8404 .visit(); 8405 } 8406 } 8407 8408 // C++2a [dcl.fct.def.default]p3 [P2002R0]: 8409 // If a constexpr-compatible function is explicitly defaulted on its first 8410 // declaration, it is implicitly considered to be constexpr. 8411 // FIXME: Only applying this to the first declaration seems problematic, as 8412 // simple reorderings can affect the meaning of the program. 8413 if (First && !FD->isConstexpr() && Info.Constexpr) 8414 FD->setConstexprKind(CSK_constexpr); 8415 8416 // C++2a [except.spec]p3: 8417 // If a declaration of a function does not have a noexcept-specifier 8418 // [and] is defaulted on its first declaration, [...] the exception 8419 // specification is as specified below 8420 if (FD->getExceptionSpecType() == EST_None) { 8421 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 8422 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8423 EPI.ExceptionSpec.Type = EST_Unevaluated; 8424 EPI.ExceptionSpec.SourceDecl = FD; 8425 FD->setType(Context.getFunctionType(FPT->getReturnType(), 8426 FPT->getParamTypes(), EPI)); 8427 } 8428 8429 return false; 8430 } 8431 8432 void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD, 8433 FunctionDecl *Spaceship) { 8434 Sema::CodeSynthesisContext Ctx; 8435 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison; 8436 Ctx.PointOfInstantiation = Spaceship->getEndLoc(); 8437 Ctx.Entity = Spaceship; 8438 pushCodeSynthesisContext(Ctx); 8439 8440 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship)) 8441 EqualEqual->setImplicit(); 8442 8443 popCodeSynthesisContext(); 8444 } 8445 8446 void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD, 8447 DefaultedComparisonKind DCK) { 8448 assert(FD->isDefaulted() && !FD->isDeleted() && 8449 !FD->doesThisDeclarationHaveABody()); 8450 if (FD->willHaveBody() || FD->isInvalidDecl()) 8451 return; 8452 8453 SynthesizedFunctionScope Scope(*this, FD); 8454 8455 // Add a context note for diagnostics produced after this point. 8456 Scope.addContextNote(UseLoc); 8457 8458 { 8459 // Build and set up the function body. 8460 CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent()); 8461 SourceLocation BodyLoc = 8462 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation(); 8463 StmtResult Body = 8464 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build(); 8465 if (Body.isInvalid()) { 8466 FD->setInvalidDecl(); 8467 return; 8468 } 8469 FD->setBody(Body.get()); 8470 FD->markUsed(Context); 8471 } 8472 8473 // The exception specification is needed because we are defining the 8474 // function. Note that this will reuse the body we just built. 8475 ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>()); 8476 8477 if (ASTMutationListener *L = getASTMutationListener()) 8478 L->CompletedImplicitDefinition(FD); 8479 } 8480 8481 static Sema::ImplicitExceptionSpecification 8482 ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc, 8483 FunctionDecl *FD, 8484 Sema::DefaultedComparisonKind DCK) { 8485 ComputingExceptionSpec CES(S, FD, Loc); 8486 Sema::ImplicitExceptionSpecification ExceptSpec(S); 8487 8488 if (FD->isInvalidDecl()) 8489 return ExceptSpec; 8490 8491 // The common case is that we just defined the comparison function. In that 8492 // case, just look at whether the body can throw. 8493 if (FD->hasBody()) { 8494 ExceptSpec.CalledStmt(FD->getBody()); 8495 } else { 8496 // Otherwise, build a body so we can check it. This should ideally only 8497 // happen when we're not actually marking the function referenced. (This is 8498 // only really important for efficiency: we don't want to build and throw 8499 // away bodies for comparison functions more than we strictly need to.) 8500 8501 // Pretend to synthesize the function body in an unevaluated context. 8502 // Note that we can't actually just go ahead and define the function here: 8503 // we are not permitted to mark its callees as referenced. 8504 Sema::SynthesizedFunctionScope Scope(S, FD); 8505 EnterExpressionEvaluationContext Context( 8506 S, Sema::ExpressionEvaluationContext::Unevaluated); 8507 8508 CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent()); 8509 SourceLocation BodyLoc = 8510 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation(); 8511 StmtResult Body = 8512 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build(); 8513 if (!Body.isInvalid()) 8514 ExceptSpec.CalledStmt(Body.get()); 8515 8516 // FIXME: Can we hold onto this body and just transform it to potentially 8517 // evaluated when we're asked to define the function rather than rebuilding 8518 // it? Either that, or we should only build the bits of the body that we 8519 // need (the expressions, not the statements). 8520 } 8521 8522 return ExceptSpec; 8523 } 8524 8525 void Sema::CheckDelayedMemberExceptionSpecs() { 8526 decltype(DelayedOverridingExceptionSpecChecks) Overriding; 8527 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent; 8528 8529 std::swap(Overriding, DelayedOverridingExceptionSpecChecks); 8530 std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks); 8531 8532 // Perform any deferred checking of exception specifications for virtual 8533 // destructors. 8534 for (auto &Check : Overriding) 8535 CheckOverridingFunctionExceptionSpec(Check.first, Check.second); 8536 8537 // Perform any deferred checking of exception specifications for befriended 8538 // special members. 8539 for (auto &Check : Equivalent) 8540 CheckEquivalentExceptionSpec(Check.second, Check.first); 8541 } 8542 8543 namespace { 8544 /// CRTP base class for visiting operations performed by a special member 8545 /// function (or inherited constructor). 8546 template<typename Derived> 8547 struct SpecialMemberVisitor { 8548 Sema &S; 8549 CXXMethodDecl *MD; 8550 Sema::CXXSpecialMember CSM; 8551 Sema::InheritedConstructorInfo *ICI; 8552 8553 // Properties of the special member, computed for convenience. 8554 bool IsConstructor = false, IsAssignment = false, ConstArg = false; 8555 8556 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 8557 Sema::InheritedConstructorInfo *ICI) 8558 : S(S), MD(MD), CSM(CSM), ICI(ICI) { 8559 switch (CSM) { 8560 case Sema::CXXDefaultConstructor: 8561 case Sema::CXXCopyConstructor: 8562 case Sema::CXXMoveConstructor: 8563 IsConstructor = true; 8564 break; 8565 case Sema::CXXCopyAssignment: 8566 case Sema::CXXMoveAssignment: 8567 IsAssignment = true; 8568 break; 8569 case Sema::CXXDestructor: 8570 break; 8571 case Sema::CXXInvalid: 8572 llvm_unreachable("invalid special member kind"); 8573 } 8574 8575 if (MD->getNumParams()) { 8576 if (const ReferenceType *RT = 8577 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 8578 ConstArg = RT->getPointeeType().isConstQualified(); 8579 } 8580 } 8581 8582 Derived &getDerived() { return static_cast<Derived&>(*this); } 8583 8584 /// Is this a "move" special member? 8585 bool isMove() const { 8586 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment; 8587 } 8588 8589 /// Look up the corresponding special member in the given class. 8590 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class, 8591 unsigned Quals, bool IsMutable) { 8592 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 8593 ConstArg && !IsMutable); 8594 } 8595 8596 /// Look up the constructor for the specified base class to see if it's 8597 /// overridden due to this being an inherited constructor. 8598 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) { 8599 if (!ICI) 8600 return {}; 8601 assert(CSM == Sema::CXXDefaultConstructor); 8602 auto *BaseCtor = 8603 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor(); 8604 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first) 8605 return MD; 8606 return {}; 8607 } 8608 8609 /// A base or member subobject. 8610 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 8611 8612 /// Get the location to use for a subobject in diagnostics. 8613 static SourceLocation getSubobjectLoc(Subobject Subobj) { 8614 // FIXME: For an indirect virtual base, the direct base leading to 8615 // the indirect virtual base would be a more useful choice. 8616 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>()) 8617 return B->getBaseTypeLoc(); 8618 else 8619 return Subobj.get<FieldDecl*>()->getLocation(); 8620 } 8621 8622 enum BasesToVisit { 8623 /// Visit all non-virtual (direct) bases. 8624 VisitNonVirtualBases, 8625 /// Visit all direct bases, virtual or not. 8626 VisitDirectBases, 8627 /// Visit all non-virtual bases, and all virtual bases if the class 8628 /// is not abstract. 8629 VisitPotentiallyConstructedBases, 8630 /// Visit all direct or virtual bases. 8631 VisitAllBases 8632 }; 8633 8634 // Visit the bases and members of the class. 8635 bool visit(BasesToVisit Bases) { 8636 CXXRecordDecl *RD = MD->getParent(); 8637 8638 if (Bases == VisitPotentiallyConstructedBases) 8639 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases; 8640 8641 for (auto &B : RD->bases()) 8642 if ((Bases == VisitDirectBases || !B.isVirtual()) && 8643 getDerived().visitBase(&B)) 8644 return true; 8645 8646 if (Bases == VisitAllBases) 8647 for (auto &B : RD->vbases()) 8648 if (getDerived().visitBase(&B)) 8649 return true; 8650 8651 for (auto *F : RD->fields()) 8652 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() && 8653 getDerived().visitField(F)) 8654 return true; 8655 8656 return false; 8657 } 8658 }; 8659 } 8660 8661 namespace { 8662 struct SpecialMemberDeletionInfo 8663 : SpecialMemberVisitor<SpecialMemberDeletionInfo> { 8664 bool Diagnose; 8665 8666 SourceLocation Loc; 8667 8668 bool AllFieldsAreConst; 8669 8670 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 8671 Sema::CXXSpecialMember CSM, 8672 Sema::InheritedConstructorInfo *ICI, bool Diagnose) 8673 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose), 8674 Loc(MD->getLocation()), AllFieldsAreConst(true) {} 8675 8676 bool inUnion() const { return MD->getParent()->isUnion(); } 8677 8678 Sema::CXXSpecialMember getEffectiveCSM() { 8679 return ICI ? Sema::CXXInvalid : CSM; 8680 } 8681 8682 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType); 8683 8684 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); } 8685 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); } 8686 8687 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 8688 bool shouldDeleteForField(FieldDecl *FD); 8689 bool shouldDeleteForAllConstMembers(); 8690 8691 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 8692 unsigned Quals); 8693 bool shouldDeleteForSubobjectCall(Subobject Subobj, 8694 Sema::SpecialMemberOverloadResult SMOR, 8695 bool IsDtorCallInCtor); 8696 8697 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 8698 }; 8699 } 8700 8701 /// Is the given special member inaccessible when used on the given 8702 /// sub-object. 8703 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 8704 CXXMethodDecl *target) { 8705 /// If we're operating on a base class, the object type is the 8706 /// type of this special member. 8707 QualType objectTy; 8708 AccessSpecifier access = target->getAccess(); 8709 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 8710 objectTy = S.Context.getTypeDeclType(MD->getParent()); 8711 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 8712 8713 // If we're operating on a field, the object type is the type of the field. 8714 } else { 8715 objectTy = S.Context.getTypeDeclType(target->getParent()); 8716 } 8717 8718 return S.isMemberAccessibleForDeletion( 8719 target->getParent(), DeclAccessPair::make(target, access), objectTy); 8720 } 8721 8722 /// Check whether we should delete a special member due to the implicit 8723 /// definition containing a call to a special member of a subobject. 8724 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 8725 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR, 8726 bool IsDtorCallInCtor) { 8727 CXXMethodDecl *Decl = SMOR.getMethod(); 8728 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 8729 8730 int DiagKind = -1; 8731 8732 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 8733 DiagKind = !Decl ? 0 : 1; 8734 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 8735 DiagKind = 2; 8736 else if (!isAccessible(Subobj, Decl)) 8737 DiagKind = 3; 8738 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 8739 !Decl->isTrivial()) { 8740 // A member of a union must have a trivial corresponding special member. 8741 // As a weird special case, a destructor call from a union's constructor 8742 // must be accessible and non-deleted, but need not be trivial. Such a 8743 // destructor is never actually called, but is semantically checked as 8744 // if it were. 8745 DiagKind = 4; 8746 } 8747 8748 if (DiagKind == -1) 8749 return false; 8750 8751 if (Diagnose) { 8752 if (Field) { 8753 S.Diag(Field->getLocation(), 8754 diag::note_deleted_special_member_class_subobject) 8755 << getEffectiveCSM() << MD->getParent() << /*IsField*/true 8756 << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false; 8757 } else { 8758 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 8759 S.Diag(Base->getBeginLoc(), 8760 diag::note_deleted_special_member_class_subobject) 8761 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 8762 << Base->getType() << DiagKind << IsDtorCallInCtor 8763 << /*IsObjCPtr*/false; 8764 } 8765 8766 if (DiagKind == 1) 8767 S.NoteDeletedFunction(Decl); 8768 // FIXME: Explain inaccessibility if DiagKind == 3. 8769 } 8770 8771 return true; 8772 } 8773 8774 /// Check whether we should delete a special member function due to having a 8775 /// direct or virtual base class or non-static data member of class type M. 8776 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 8777 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 8778 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 8779 bool IsMutable = Field && Field->isMutable(); 8780 8781 // C++11 [class.ctor]p5: 8782 // -- any direct or virtual base class, or non-static data member with no 8783 // brace-or-equal-initializer, has class type M (or array thereof) and 8784 // either M has no default constructor or overload resolution as applied 8785 // to M's default constructor results in an ambiguity or in a function 8786 // that is deleted or inaccessible 8787 // C++11 [class.copy]p11, C++11 [class.copy]p23: 8788 // -- a direct or virtual base class B that cannot be copied/moved because 8789 // overload resolution, as applied to B's corresponding special member, 8790 // results in an ambiguity or a function that is deleted or inaccessible 8791 // from the defaulted special member 8792 // C++11 [class.dtor]p5: 8793 // -- any direct or virtual base class [...] has a type with a destructor 8794 // that is deleted or inaccessible 8795 if (!(CSM == Sema::CXXDefaultConstructor && 8796 Field && Field->hasInClassInitializer()) && 8797 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 8798 false)) 8799 return true; 8800 8801 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 8802 // -- any direct or virtual base class or non-static data member has a 8803 // type with a destructor that is deleted or inaccessible 8804 if (IsConstructor) { 8805 Sema::SpecialMemberOverloadResult SMOR = 8806 S.LookupSpecialMember(Class, Sema::CXXDestructor, 8807 false, false, false, false, false); 8808 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 8809 return true; 8810 } 8811 8812 return false; 8813 } 8814 8815 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember( 8816 FieldDecl *FD, QualType FieldType) { 8817 // The defaulted special functions are defined as deleted if this is a variant 8818 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak 8819 // type under ARC. 8820 if (!FieldType.hasNonTrivialObjCLifetime()) 8821 return false; 8822 8823 // Don't make the defaulted default constructor defined as deleted if the 8824 // member has an in-class initializer. 8825 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) 8826 return false; 8827 8828 if (Diagnose) { 8829 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent()); 8830 S.Diag(FD->getLocation(), 8831 diag::note_deleted_special_member_class_subobject) 8832 << getEffectiveCSM() << ParentClass << /*IsField*/true 8833 << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true; 8834 } 8835 8836 return true; 8837 } 8838 8839 /// Check whether we should delete a special member function due to the class 8840 /// having a particular direct or virtual base class. 8841 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 8842 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 8843 // If program is correct, BaseClass cannot be null, but if it is, the error 8844 // must be reported elsewhere. 8845 if (!BaseClass) 8846 return false; 8847 // If we have an inheriting constructor, check whether we're calling an 8848 // inherited constructor instead of a default constructor. 8849 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 8850 if (auto *BaseCtor = SMOR.getMethod()) { 8851 // Note that we do not check access along this path; other than that, 8852 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false); 8853 // FIXME: Check that the base has a usable destructor! Sink this into 8854 // shouldDeleteForClassSubobject. 8855 if (BaseCtor->isDeleted() && Diagnose) { 8856 S.Diag(Base->getBeginLoc(), 8857 diag::note_deleted_special_member_class_subobject) 8858 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 8859 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false 8860 << /*IsObjCPtr*/false; 8861 S.NoteDeletedFunction(BaseCtor); 8862 } 8863 return BaseCtor->isDeleted(); 8864 } 8865 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 8866 } 8867 8868 /// Check whether we should delete a special member function due to the class 8869 /// having a particular non-static data member. 8870 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 8871 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 8872 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 8873 8874 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType)) 8875 return true; 8876 8877 if (CSM == Sema::CXXDefaultConstructor) { 8878 // For a default constructor, all references must be initialized in-class 8879 // and, if a union, it must have a non-const member. 8880 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 8881 if (Diagnose) 8882 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 8883 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0; 8884 return true; 8885 } 8886 // C++11 [class.ctor]p5: any non-variant non-static data member of 8887 // const-qualified type (or array thereof) with no 8888 // brace-or-equal-initializer does not have a user-provided default 8889 // constructor. 8890 if (!inUnion() && FieldType.isConstQualified() && 8891 !FD->hasInClassInitializer() && 8892 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 8893 if (Diagnose) 8894 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 8895 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1; 8896 return true; 8897 } 8898 8899 if (inUnion() && !FieldType.isConstQualified()) 8900 AllFieldsAreConst = false; 8901 } else if (CSM == Sema::CXXCopyConstructor) { 8902 // For a copy constructor, data members must not be of rvalue reference 8903 // type. 8904 if (FieldType->isRValueReferenceType()) { 8905 if (Diagnose) 8906 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 8907 << MD->getParent() << FD << FieldType; 8908 return true; 8909 } 8910 } else if (IsAssignment) { 8911 // For an assignment operator, data members must not be of reference type. 8912 if (FieldType->isReferenceType()) { 8913 if (Diagnose) 8914 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 8915 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0; 8916 return true; 8917 } 8918 if (!FieldRecord && FieldType.isConstQualified()) { 8919 // C++11 [class.copy]p23: 8920 // -- a non-static data member of const non-class type (or array thereof) 8921 if (Diagnose) 8922 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 8923 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1; 8924 return true; 8925 } 8926 } 8927 8928 if (FieldRecord) { 8929 // Some additional restrictions exist on the variant members. 8930 if (!inUnion() && FieldRecord->isUnion() && 8931 FieldRecord->isAnonymousStructOrUnion()) { 8932 bool AllVariantFieldsAreConst = true; 8933 8934 // FIXME: Handle anonymous unions declared within anonymous unions. 8935 for (auto *UI : FieldRecord->fields()) { 8936 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 8937 8938 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType)) 8939 return true; 8940 8941 if (!UnionFieldType.isConstQualified()) 8942 AllVariantFieldsAreConst = false; 8943 8944 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 8945 if (UnionFieldRecord && 8946 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 8947 UnionFieldType.getCVRQualifiers())) 8948 return true; 8949 } 8950 8951 // At least one member in each anonymous union must be non-const 8952 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 8953 !FieldRecord->field_empty()) { 8954 if (Diagnose) 8955 S.Diag(FieldRecord->getLocation(), 8956 diag::note_deleted_default_ctor_all_const) 8957 << !!ICI << MD->getParent() << /*anonymous union*/1; 8958 return true; 8959 } 8960 8961 // Don't check the implicit member of the anonymous union type. 8962 // This is technically non-conformant, but sanity demands it. 8963 return false; 8964 } 8965 8966 if (shouldDeleteForClassSubobject(FieldRecord, FD, 8967 FieldType.getCVRQualifiers())) 8968 return true; 8969 } 8970 8971 return false; 8972 } 8973 8974 /// C++11 [class.ctor] p5: 8975 /// A defaulted default constructor for a class X is defined as deleted if 8976 /// X is a union and all of its variant members are of const-qualified type. 8977 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 8978 // This is a silly definition, because it gives an empty union a deleted 8979 // default constructor. Don't do that. 8980 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) { 8981 bool AnyFields = false; 8982 for (auto *F : MD->getParent()->fields()) 8983 if ((AnyFields = !F->isUnnamedBitfield())) 8984 break; 8985 if (!AnyFields) 8986 return false; 8987 if (Diagnose) 8988 S.Diag(MD->getParent()->getLocation(), 8989 diag::note_deleted_default_ctor_all_const) 8990 << !!ICI << MD->getParent() << /*not anonymous union*/0; 8991 return true; 8992 } 8993 return false; 8994 } 8995 8996 /// Determine whether a defaulted special member function should be defined as 8997 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 8998 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 8999 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 9000 InheritedConstructorInfo *ICI, 9001 bool Diagnose) { 9002 if (MD->isInvalidDecl()) 9003 return false; 9004 CXXRecordDecl *RD = MD->getParent(); 9005 assert(!RD->isDependentType() && "do deletion after instantiation"); 9006 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 9007 return false; 9008 9009 // C++11 [expr.lambda.prim]p19: 9010 // The closure type associated with a lambda-expression has a 9011 // deleted (8.4.3) default constructor and a deleted copy 9012 // assignment operator. 9013 // C++2a adds back these operators if the lambda has no lambda-capture. 9014 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() && 9015 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 9016 if (Diagnose) 9017 Diag(RD->getLocation(), diag::note_lambda_decl); 9018 return true; 9019 } 9020 9021 // For an anonymous struct or union, the copy and assignment special members 9022 // will never be used, so skip the check. For an anonymous union declared at 9023 // namespace scope, the constructor and destructor are used. 9024 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 9025 RD->isAnonymousStructOrUnion()) 9026 return false; 9027 9028 // C++11 [class.copy]p7, p18: 9029 // If the class definition declares a move constructor or move assignment 9030 // operator, an implicitly declared copy constructor or copy assignment 9031 // operator is defined as deleted. 9032 if (MD->isImplicit() && 9033 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 9034 CXXMethodDecl *UserDeclaredMove = nullptr; 9035 9036 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the 9037 // deletion of the corresponding copy operation, not both copy operations. 9038 // MSVC 2015 has adopted the standards conforming behavior. 9039 bool DeletesOnlyMatchingCopy = 9040 getLangOpts().MSVCCompat && 9041 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015); 9042 9043 if (RD->hasUserDeclaredMoveConstructor() && 9044 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) { 9045 if (!Diagnose) return true; 9046 9047 // Find any user-declared move constructor. 9048 for (auto *I : RD->ctors()) { 9049 if (I->isMoveConstructor()) { 9050 UserDeclaredMove = I; 9051 break; 9052 } 9053 } 9054 assert(UserDeclaredMove); 9055 } else if (RD->hasUserDeclaredMoveAssignment() && 9056 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) { 9057 if (!Diagnose) return true; 9058 9059 // Find any user-declared move assignment operator. 9060 for (auto *I : RD->methods()) { 9061 if (I->isMoveAssignmentOperator()) { 9062 UserDeclaredMove = I; 9063 break; 9064 } 9065 } 9066 assert(UserDeclaredMove); 9067 } 9068 9069 if (UserDeclaredMove) { 9070 Diag(UserDeclaredMove->getLocation(), 9071 diag::note_deleted_copy_user_declared_move) 9072 << (CSM == CXXCopyAssignment) << RD 9073 << UserDeclaredMove->isMoveAssignmentOperator(); 9074 return true; 9075 } 9076 } 9077 9078 // Do access control from the special member function 9079 ContextRAII MethodContext(*this, MD); 9080 9081 // C++11 [class.dtor]p5: 9082 // -- for a virtual destructor, lookup of the non-array deallocation function 9083 // results in an ambiguity or in a function that is deleted or inaccessible 9084 if (CSM == CXXDestructor && MD->isVirtual()) { 9085 FunctionDecl *OperatorDelete = nullptr; 9086 DeclarationName Name = 9087 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 9088 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 9089 OperatorDelete, /*Diagnose*/false)) { 9090 if (Diagnose) 9091 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 9092 return true; 9093 } 9094 } 9095 9096 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose); 9097 9098 // Per DR1611, do not consider virtual bases of constructors of abstract 9099 // classes, since we are not going to construct them. 9100 // Per DR1658, do not consider virtual bases of destructors of abstract 9101 // classes either. 9102 // Per DR2180, for assignment operators we only assign (and thus only 9103 // consider) direct bases. 9104 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases 9105 : SMI.VisitPotentiallyConstructedBases)) 9106 return true; 9107 9108 if (SMI.shouldDeleteForAllConstMembers()) 9109 return true; 9110 9111 if (getLangOpts().CUDA) { 9112 // We should delete the special member in CUDA mode if target inference 9113 // failed. 9114 // For inherited constructors (non-null ICI), CSM may be passed so that MD 9115 // is treated as certain special member, which may not reflect what special 9116 // member MD really is. However inferCUDATargetForImplicitSpecialMember 9117 // expects CSM to match MD, therefore recalculate CSM. 9118 assert(ICI || CSM == getSpecialMember(MD)); 9119 auto RealCSM = CSM; 9120 if (ICI) 9121 RealCSM = getSpecialMember(MD); 9122 9123 return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD, 9124 SMI.ConstArg, Diagnose); 9125 } 9126 9127 return false; 9128 } 9129 9130 void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) { 9131 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD); 9132 assert(DFK && "not a defaultable function"); 9133 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted"); 9134 9135 if (DFK.isSpecialMember()) { 9136 ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), 9137 nullptr, /*Diagnose=*/true); 9138 } else { 9139 DefaultedComparisonAnalyzer( 9140 *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD, 9141 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted) 9142 .visit(); 9143 } 9144 } 9145 9146 /// Perform lookup for a special member of the specified kind, and determine 9147 /// whether it is trivial. If the triviality can be determined without the 9148 /// lookup, skip it. This is intended for use when determining whether a 9149 /// special member of a containing object is trivial, and thus does not ever 9150 /// perform overload resolution for default constructors. 9151 /// 9152 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 9153 /// member that was most likely to be intended to be trivial, if any. 9154 /// 9155 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to 9156 /// determine whether the special member is trivial. 9157 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 9158 Sema::CXXSpecialMember CSM, unsigned Quals, 9159 bool ConstRHS, 9160 Sema::TrivialABIHandling TAH, 9161 CXXMethodDecl **Selected) { 9162 if (Selected) 9163 *Selected = nullptr; 9164 9165 switch (CSM) { 9166 case Sema::CXXInvalid: 9167 llvm_unreachable("not a special member"); 9168 9169 case Sema::CXXDefaultConstructor: 9170 // C++11 [class.ctor]p5: 9171 // A default constructor is trivial if: 9172 // - all the [direct subobjects] have trivial default constructors 9173 // 9174 // Note, no overload resolution is performed in this case. 9175 if (RD->hasTrivialDefaultConstructor()) 9176 return true; 9177 9178 if (Selected) { 9179 // If there's a default constructor which could have been trivial, dig it 9180 // out. Otherwise, if there's any user-provided default constructor, point 9181 // to that as an example of why there's not a trivial one. 9182 CXXConstructorDecl *DefCtor = nullptr; 9183 if (RD->needsImplicitDefaultConstructor()) 9184 S.DeclareImplicitDefaultConstructor(RD); 9185 for (auto *CI : RD->ctors()) { 9186 if (!CI->isDefaultConstructor()) 9187 continue; 9188 DefCtor = CI; 9189 if (!DefCtor->isUserProvided()) 9190 break; 9191 } 9192 9193 *Selected = DefCtor; 9194 } 9195 9196 return false; 9197 9198 case Sema::CXXDestructor: 9199 // C++11 [class.dtor]p5: 9200 // A destructor is trivial if: 9201 // - all the direct [subobjects] have trivial destructors 9202 if (RD->hasTrivialDestructor() || 9203 (TAH == Sema::TAH_ConsiderTrivialABI && 9204 RD->hasTrivialDestructorForCall())) 9205 return true; 9206 9207 if (Selected) { 9208 if (RD->needsImplicitDestructor()) 9209 S.DeclareImplicitDestructor(RD); 9210 *Selected = RD->getDestructor(); 9211 } 9212 9213 return false; 9214 9215 case Sema::CXXCopyConstructor: 9216 // C++11 [class.copy]p12: 9217 // A copy constructor is trivial if: 9218 // - the constructor selected to copy each direct [subobject] is trivial 9219 if (RD->hasTrivialCopyConstructor() || 9220 (TAH == Sema::TAH_ConsiderTrivialABI && 9221 RD->hasTrivialCopyConstructorForCall())) { 9222 if (Quals == Qualifiers::Const) 9223 // We must either select the trivial copy constructor or reach an 9224 // ambiguity; no need to actually perform overload resolution. 9225 return true; 9226 } else if (!Selected) { 9227 return false; 9228 } 9229 // In C++98, we are not supposed to perform overload resolution here, but we 9230 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 9231 // cases like B as having a non-trivial copy constructor: 9232 // struct A { template<typename T> A(T&); }; 9233 // struct B { mutable A a; }; 9234 goto NeedOverloadResolution; 9235 9236 case Sema::CXXCopyAssignment: 9237 // C++11 [class.copy]p25: 9238 // A copy assignment operator is trivial if: 9239 // - the assignment operator selected to copy each direct [subobject] is 9240 // trivial 9241 if (RD->hasTrivialCopyAssignment()) { 9242 if (Quals == Qualifiers::Const) 9243 return true; 9244 } else if (!Selected) { 9245 return false; 9246 } 9247 // In C++98, we are not supposed to perform overload resolution here, but we 9248 // treat that as a language defect. 9249 goto NeedOverloadResolution; 9250 9251 case Sema::CXXMoveConstructor: 9252 case Sema::CXXMoveAssignment: 9253 NeedOverloadResolution: 9254 Sema::SpecialMemberOverloadResult SMOR = 9255 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 9256 9257 // The standard doesn't describe how to behave if the lookup is ambiguous. 9258 // We treat it as not making the member non-trivial, just like the standard 9259 // mandates for the default constructor. This should rarely matter, because 9260 // the member will also be deleted. 9261 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 9262 return true; 9263 9264 if (!SMOR.getMethod()) { 9265 assert(SMOR.getKind() == 9266 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 9267 return false; 9268 } 9269 9270 // We deliberately don't check if we found a deleted special member. We're 9271 // not supposed to! 9272 if (Selected) 9273 *Selected = SMOR.getMethod(); 9274 9275 if (TAH == Sema::TAH_ConsiderTrivialABI && 9276 (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor)) 9277 return SMOR.getMethod()->isTrivialForCall(); 9278 return SMOR.getMethod()->isTrivial(); 9279 } 9280 9281 llvm_unreachable("unknown special method kind"); 9282 } 9283 9284 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 9285 for (auto *CI : RD->ctors()) 9286 if (!CI->isImplicit()) 9287 return CI; 9288 9289 // Look for constructor templates. 9290 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 9291 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 9292 if (CXXConstructorDecl *CD = 9293 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 9294 return CD; 9295 } 9296 9297 return nullptr; 9298 } 9299 9300 /// The kind of subobject we are checking for triviality. The values of this 9301 /// enumeration are used in diagnostics. 9302 enum TrivialSubobjectKind { 9303 /// The subobject is a base class. 9304 TSK_BaseClass, 9305 /// The subobject is a non-static data member. 9306 TSK_Field, 9307 /// The object is actually the complete object. 9308 TSK_CompleteObject 9309 }; 9310 9311 /// Check whether the special member selected for a given type would be trivial. 9312 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 9313 QualType SubType, bool ConstRHS, 9314 Sema::CXXSpecialMember CSM, 9315 TrivialSubobjectKind Kind, 9316 Sema::TrivialABIHandling TAH, bool Diagnose) { 9317 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 9318 if (!SubRD) 9319 return true; 9320 9321 CXXMethodDecl *Selected; 9322 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 9323 ConstRHS, TAH, Diagnose ? &Selected : nullptr)) 9324 return true; 9325 9326 if (Diagnose) { 9327 if (ConstRHS) 9328 SubType.addConst(); 9329 9330 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 9331 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 9332 << Kind << SubType.getUnqualifiedType(); 9333 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 9334 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 9335 } else if (!Selected) 9336 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 9337 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 9338 else if (Selected->isUserProvided()) { 9339 if (Kind == TSK_CompleteObject) 9340 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 9341 << Kind << SubType.getUnqualifiedType() << CSM; 9342 else { 9343 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 9344 << Kind << SubType.getUnqualifiedType() << CSM; 9345 S.Diag(Selected->getLocation(), diag::note_declared_at); 9346 } 9347 } else { 9348 if (Kind != TSK_CompleteObject) 9349 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 9350 << Kind << SubType.getUnqualifiedType() << CSM; 9351 9352 // Explain why the defaulted or deleted special member isn't trivial. 9353 S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI, 9354 Diagnose); 9355 } 9356 } 9357 9358 return false; 9359 } 9360 9361 /// Check whether the members of a class type allow a special member to be 9362 /// trivial. 9363 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 9364 Sema::CXXSpecialMember CSM, 9365 bool ConstArg, 9366 Sema::TrivialABIHandling TAH, 9367 bool Diagnose) { 9368 for (const auto *FI : RD->fields()) { 9369 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 9370 continue; 9371 9372 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 9373 9374 // Pretend anonymous struct or union members are members of this class. 9375 if (FI->isAnonymousStructOrUnion()) { 9376 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 9377 CSM, ConstArg, TAH, Diagnose)) 9378 return false; 9379 continue; 9380 } 9381 9382 // C++11 [class.ctor]p5: 9383 // A default constructor is trivial if [...] 9384 // -- no non-static data member of its class has a 9385 // brace-or-equal-initializer 9386 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 9387 if (Diagnose) 9388 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI; 9389 return false; 9390 } 9391 9392 // Objective C ARC 4.3.5: 9393 // [...] nontrivally ownership-qualified types are [...] not trivially 9394 // default constructible, copy constructible, move constructible, copy 9395 // assignable, move assignable, or destructible [...] 9396 if (FieldType.hasNonTrivialObjCLifetime()) { 9397 if (Diagnose) 9398 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 9399 << RD << FieldType.getObjCLifetime(); 9400 return false; 9401 } 9402 9403 bool ConstRHS = ConstArg && !FI->isMutable(); 9404 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 9405 CSM, TSK_Field, TAH, Diagnose)) 9406 return false; 9407 } 9408 9409 return true; 9410 } 9411 9412 /// Diagnose why the specified class does not have a trivial special member of 9413 /// the given kind. 9414 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 9415 QualType Ty = Context.getRecordType(RD); 9416 9417 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 9418 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 9419 TSK_CompleteObject, TAH_IgnoreTrivialABI, 9420 /*Diagnose*/true); 9421 } 9422 9423 /// Determine whether a defaulted or deleted special member function is trivial, 9424 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 9425 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 9426 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 9427 TrivialABIHandling TAH, bool Diagnose) { 9428 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 9429 9430 CXXRecordDecl *RD = MD->getParent(); 9431 9432 bool ConstArg = false; 9433 9434 // C++11 [class.copy]p12, p25: [DR1593] 9435 // A [special member] is trivial if [...] its parameter-type-list is 9436 // equivalent to the parameter-type-list of an implicit declaration [...] 9437 switch (CSM) { 9438 case CXXDefaultConstructor: 9439 case CXXDestructor: 9440 // Trivial default constructors and destructors cannot have parameters. 9441 break; 9442 9443 case CXXCopyConstructor: 9444 case CXXCopyAssignment: { 9445 // Trivial copy operations always have const, non-volatile parameter types. 9446 ConstArg = true; 9447 const ParmVarDecl *Param0 = MD->getParamDecl(0); 9448 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 9449 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 9450 if (Diagnose) 9451 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 9452 << Param0->getSourceRange() << Param0->getType() 9453 << Context.getLValueReferenceType( 9454 Context.getRecordType(RD).withConst()); 9455 return false; 9456 } 9457 break; 9458 } 9459 9460 case CXXMoveConstructor: 9461 case CXXMoveAssignment: { 9462 // Trivial move operations always have non-cv-qualified parameters. 9463 const ParmVarDecl *Param0 = MD->getParamDecl(0); 9464 const RValueReferenceType *RT = 9465 Param0->getType()->getAs<RValueReferenceType>(); 9466 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 9467 if (Diagnose) 9468 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 9469 << Param0->getSourceRange() << Param0->getType() 9470 << Context.getRValueReferenceType(Context.getRecordType(RD)); 9471 return false; 9472 } 9473 break; 9474 } 9475 9476 case CXXInvalid: 9477 llvm_unreachable("not a special member"); 9478 } 9479 9480 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 9481 if (Diagnose) 9482 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 9483 diag::note_nontrivial_default_arg) 9484 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 9485 return false; 9486 } 9487 if (MD->isVariadic()) { 9488 if (Diagnose) 9489 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 9490 return false; 9491 } 9492 9493 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 9494 // A copy/move [constructor or assignment operator] is trivial if 9495 // -- the [member] selected to copy/move each direct base class subobject 9496 // is trivial 9497 // 9498 // C++11 [class.copy]p12, C++11 [class.copy]p25: 9499 // A [default constructor or destructor] is trivial if 9500 // -- all the direct base classes have trivial [default constructors or 9501 // destructors] 9502 for (const auto &BI : RD->bases()) 9503 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(), 9504 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose)) 9505 return false; 9506 9507 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 9508 // A copy/move [constructor or assignment operator] for a class X is 9509 // trivial if 9510 // -- for each non-static data member of X that is of class type (or array 9511 // thereof), the constructor selected to copy/move that member is 9512 // trivial 9513 // 9514 // C++11 [class.copy]p12, C++11 [class.copy]p25: 9515 // A [default constructor or destructor] is trivial if 9516 // -- for all of the non-static data members of its class that are of class 9517 // type (or array thereof), each such class has a trivial [default 9518 // constructor or destructor] 9519 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose)) 9520 return false; 9521 9522 // C++11 [class.dtor]p5: 9523 // A destructor is trivial if [...] 9524 // -- the destructor is not virtual 9525 if (CSM == CXXDestructor && MD->isVirtual()) { 9526 if (Diagnose) 9527 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 9528 return false; 9529 } 9530 9531 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 9532 // A [special member] for class X is trivial if [...] 9533 // -- class X has no virtual functions and no virtual base classes 9534 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 9535 if (!Diagnose) 9536 return false; 9537 9538 if (RD->getNumVBases()) { 9539 // Check for virtual bases. We already know that the corresponding 9540 // member in all bases is trivial, so vbases must all be direct. 9541 CXXBaseSpecifier &BS = *RD->vbases_begin(); 9542 assert(BS.isVirtual()); 9543 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1; 9544 return false; 9545 } 9546 9547 // Must have a virtual method. 9548 for (const auto *MI : RD->methods()) { 9549 if (MI->isVirtual()) { 9550 SourceLocation MLoc = MI->getBeginLoc(); 9551 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 9552 return false; 9553 } 9554 } 9555 9556 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 9557 } 9558 9559 // Looks like it's trivial! 9560 return true; 9561 } 9562 9563 namespace { 9564 struct FindHiddenVirtualMethod { 9565 Sema *S; 9566 CXXMethodDecl *Method; 9567 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 9568 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 9569 9570 private: 9571 /// Check whether any most overridden method from MD in Methods 9572 static bool CheckMostOverridenMethods( 9573 const CXXMethodDecl *MD, 9574 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) { 9575 if (MD->size_overridden_methods() == 0) 9576 return Methods.count(MD->getCanonicalDecl()); 9577 for (const CXXMethodDecl *O : MD->overridden_methods()) 9578 if (CheckMostOverridenMethods(O, Methods)) 9579 return true; 9580 return false; 9581 } 9582 9583 public: 9584 /// Member lookup function that determines whether a given C++ 9585 /// method overloads virtual methods in a base class without overriding any, 9586 /// to be used with CXXRecordDecl::lookupInBases(). 9587 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 9588 RecordDecl *BaseRecord = 9589 Specifier->getType()->castAs<RecordType>()->getDecl(); 9590 9591 DeclarationName Name = Method->getDeclName(); 9592 assert(Name.getNameKind() == DeclarationName::Identifier); 9593 9594 bool foundSameNameMethod = false; 9595 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 9596 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 9597 Path.Decls = Path.Decls.slice(1)) { 9598 NamedDecl *D = Path.Decls.front(); 9599 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 9600 MD = MD->getCanonicalDecl(); 9601 foundSameNameMethod = true; 9602 // Interested only in hidden virtual methods. 9603 if (!MD->isVirtual()) 9604 continue; 9605 // If the method we are checking overrides a method from its base 9606 // don't warn about the other overloaded methods. Clang deviates from 9607 // GCC by only diagnosing overloads of inherited virtual functions that 9608 // do not override any other virtual functions in the base. GCC's 9609 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 9610 // function from a base class. These cases may be better served by a 9611 // warning (not specific to virtual functions) on call sites when the 9612 // call would select a different function from the base class, were it 9613 // visible. 9614 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 9615 if (!S->IsOverload(Method, MD, false)) 9616 return true; 9617 // Collect the overload only if its hidden. 9618 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods)) 9619 overloadedMethods.push_back(MD); 9620 } 9621 } 9622 9623 if (foundSameNameMethod) 9624 OverloadedMethods.append(overloadedMethods.begin(), 9625 overloadedMethods.end()); 9626 return foundSameNameMethod; 9627 } 9628 }; 9629 } // end anonymous namespace 9630 9631 /// Add the most overriden methods from MD to Methods 9632 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 9633 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 9634 if (MD->size_overridden_methods() == 0) 9635 Methods.insert(MD->getCanonicalDecl()); 9636 else 9637 for (const CXXMethodDecl *O : MD->overridden_methods()) 9638 AddMostOverridenMethods(O, Methods); 9639 } 9640 9641 /// Check if a method overloads virtual methods in a base class without 9642 /// overriding any. 9643 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 9644 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 9645 if (!MD->getDeclName().isIdentifier()) 9646 return; 9647 9648 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 9649 /*bool RecordPaths=*/false, 9650 /*bool DetectVirtual=*/false); 9651 FindHiddenVirtualMethod FHVM; 9652 FHVM.Method = MD; 9653 FHVM.S = this; 9654 9655 // Keep the base methods that were overridden or introduced in the subclass 9656 // by 'using' in a set. A base method not in this set is hidden. 9657 CXXRecordDecl *DC = MD->getParent(); 9658 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 9659 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 9660 NamedDecl *ND = *I; 9661 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 9662 ND = shad->getTargetDecl(); 9663 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 9664 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods); 9665 } 9666 9667 if (DC->lookupInBases(FHVM, Paths)) 9668 OverloadedMethods = FHVM.OverloadedMethods; 9669 } 9670 9671 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 9672 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 9673 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 9674 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 9675 PartialDiagnostic PD = PDiag( 9676 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 9677 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 9678 Diag(overloadedMD->getLocation(), PD); 9679 } 9680 } 9681 9682 /// Diagnose methods which overload virtual methods in a base class 9683 /// without overriding any. 9684 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 9685 if (MD->isInvalidDecl()) 9686 return; 9687 9688 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 9689 return; 9690 9691 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 9692 FindHiddenVirtualMethods(MD, OverloadedMethods); 9693 if (!OverloadedMethods.empty()) { 9694 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 9695 << MD << (OverloadedMethods.size() > 1); 9696 9697 NoteHiddenVirtualMethods(MD, OverloadedMethods); 9698 } 9699 } 9700 9701 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) { 9702 auto PrintDiagAndRemoveAttr = [&](unsigned N) { 9703 // No diagnostics if this is a template instantiation. 9704 if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) { 9705 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), 9706 diag::ext_cannot_use_trivial_abi) << &RD; 9707 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), 9708 diag::note_cannot_use_trivial_abi_reason) << &RD << N; 9709 } 9710 RD.dropAttr<TrivialABIAttr>(); 9711 }; 9712 9713 // Ill-formed if the copy and move constructors are deleted. 9714 auto HasNonDeletedCopyOrMoveConstructor = [&]() { 9715 if (RD.needsImplicitCopyConstructor() && 9716 !RD.defaultedCopyConstructorIsDeleted()) 9717 return true; 9718 if (RD.needsImplicitMoveConstructor() && 9719 !RD.defaultedMoveConstructorIsDeleted()) 9720 return true; 9721 for (const CXXConstructorDecl *CD : RD.ctors()) 9722 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted()) 9723 return true; 9724 return false; 9725 }; 9726 9727 if (!HasNonDeletedCopyOrMoveConstructor()) { 9728 PrintDiagAndRemoveAttr(0); 9729 return; 9730 } 9731 9732 // Ill-formed if the struct has virtual functions. 9733 if (RD.isPolymorphic()) { 9734 PrintDiagAndRemoveAttr(1); 9735 return; 9736 } 9737 9738 for (const auto &B : RD.bases()) { 9739 // Ill-formed if the base class is non-trivial for the purpose of calls or a 9740 // virtual base. 9741 if (!B.getType()->isDependentType() && 9742 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) { 9743 PrintDiagAndRemoveAttr(2); 9744 return; 9745 } 9746 9747 if (B.isVirtual()) { 9748 PrintDiagAndRemoveAttr(3); 9749 return; 9750 } 9751 } 9752 9753 for (const auto *FD : RD.fields()) { 9754 // Ill-formed if the field is an ObjectiveC pointer or of a type that is 9755 // non-trivial for the purpose of calls. 9756 QualType FT = FD->getType(); 9757 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) { 9758 PrintDiagAndRemoveAttr(4); 9759 return; 9760 } 9761 9762 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>()) 9763 if (!RT->isDependentType() && 9764 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) { 9765 PrintDiagAndRemoveAttr(5); 9766 return; 9767 } 9768 } 9769 } 9770 9771 void Sema::ActOnFinishCXXMemberSpecification( 9772 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, 9773 SourceLocation RBrac, const ParsedAttributesView &AttrList) { 9774 if (!TagDecl) 9775 return; 9776 9777 AdjustDeclIfTemplate(TagDecl); 9778 9779 for (const ParsedAttr &AL : AttrList) { 9780 if (AL.getKind() != ParsedAttr::AT_Visibility) 9781 continue; 9782 AL.setInvalid(); 9783 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL; 9784 } 9785 9786 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 9787 // strict aliasing violation! 9788 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 9789 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 9790 9791 CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl)); 9792 } 9793 9794 /// Find the equality comparison functions that should be implicitly declared 9795 /// in a given class definition, per C++2a [class.compare.default]p3. 9796 static void findImplicitlyDeclaredEqualityComparisons( 9797 ASTContext &Ctx, CXXRecordDecl *RD, 9798 llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) { 9799 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual); 9800 if (!RD->lookup(EqEq).empty()) 9801 // Member operator== explicitly declared: no implicit operator==s. 9802 return; 9803 9804 // Traverse friends looking for an '==' or a '<=>'. 9805 for (FriendDecl *Friend : RD->friends()) { 9806 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl()); 9807 if (!FD) continue; 9808 9809 if (FD->getOverloadedOperator() == OO_EqualEqual) { 9810 // Friend operator== explicitly declared: no implicit operator==s. 9811 Spaceships.clear(); 9812 return; 9813 } 9814 9815 if (FD->getOverloadedOperator() == OO_Spaceship && 9816 FD->isExplicitlyDefaulted()) 9817 Spaceships.push_back(FD); 9818 } 9819 9820 // Look for members named 'operator<=>'. 9821 DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship); 9822 for (NamedDecl *ND : RD->lookup(Cmp)) { 9823 // Note that we could find a non-function here (either a function template 9824 // or a using-declaration). Neither case results in an implicit 9825 // 'operator=='. 9826 if (auto *FD = dyn_cast<FunctionDecl>(ND)) 9827 if (FD->isExplicitlyDefaulted()) 9828 Spaceships.push_back(FD); 9829 } 9830 } 9831 9832 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 9833 /// special functions, such as the default constructor, copy 9834 /// constructor, or destructor, to the given C++ class (C++ 9835 /// [special]p1). This routine can only be executed just before the 9836 /// definition of the class is complete. 9837 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 9838 if (ClassDecl->needsImplicitDefaultConstructor()) { 9839 ++getASTContext().NumImplicitDefaultConstructors; 9840 9841 if (ClassDecl->hasInheritedConstructor()) 9842 DeclareImplicitDefaultConstructor(ClassDecl); 9843 } 9844 9845 if (ClassDecl->needsImplicitCopyConstructor()) { 9846 ++getASTContext().NumImplicitCopyConstructors; 9847 9848 // If the properties or semantics of the copy constructor couldn't be 9849 // determined while the class was being declared, force a declaration 9850 // of it now. 9851 if (ClassDecl->needsOverloadResolutionForCopyConstructor() || 9852 ClassDecl->hasInheritedConstructor()) 9853 DeclareImplicitCopyConstructor(ClassDecl); 9854 // For the MS ABI we need to know whether the copy ctor is deleted. A 9855 // prerequisite for deleting the implicit copy ctor is that the class has a 9856 // move ctor or move assignment that is either user-declared or whose 9857 // semantics are inherited from a subobject. FIXME: We should provide a more 9858 // direct way for CodeGen to ask whether the constructor was deleted. 9859 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 9860 (ClassDecl->hasUserDeclaredMoveConstructor() || 9861 ClassDecl->needsOverloadResolutionForMoveConstructor() || 9862 ClassDecl->hasUserDeclaredMoveAssignment() || 9863 ClassDecl->needsOverloadResolutionForMoveAssignment())) 9864 DeclareImplicitCopyConstructor(ClassDecl); 9865 } 9866 9867 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 9868 ++getASTContext().NumImplicitMoveConstructors; 9869 9870 if (ClassDecl->needsOverloadResolutionForMoveConstructor() || 9871 ClassDecl->hasInheritedConstructor()) 9872 DeclareImplicitMoveConstructor(ClassDecl); 9873 } 9874 9875 if (ClassDecl->needsImplicitCopyAssignment()) { 9876 ++getASTContext().NumImplicitCopyAssignmentOperators; 9877 9878 // If we have a dynamic class, then the copy assignment operator may be 9879 // virtual, so we have to declare it immediately. This ensures that, e.g., 9880 // it shows up in the right place in the vtable and that we diagnose 9881 // problems with the implicit exception specification. 9882 if (ClassDecl->isDynamicClass() || 9883 ClassDecl->needsOverloadResolutionForCopyAssignment() || 9884 ClassDecl->hasInheritedAssignment()) 9885 DeclareImplicitCopyAssignment(ClassDecl); 9886 } 9887 9888 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 9889 ++getASTContext().NumImplicitMoveAssignmentOperators; 9890 9891 // Likewise for the move assignment operator. 9892 if (ClassDecl->isDynamicClass() || 9893 ClassDecl->needsOverloadResolutionForMoveAssignment() || 9894 ClassDecl->hasInheritedAssignment()) 9895 DeclareImplicitMoveAssignment(ClassDecl); 9896 } 9897 9898 if (ClassDecl->needsImplicitDestructor()) { 9899 ++getASTContext().NumImplicitDestructors; 9900 9901 // If we have a dynamic class, then the destructor may be virtual, so we 9902 // have to declare the destructor immediately. This ensures that, e.g., it 9903 // shows up in the right place in the vtable and that we diagnose problems 9904 // with the implicit exception specification. 9905 if (ClassDecl->isDynamicClass() || 9906 ClassDecl->needsOverloadResolutionForDestructor()) 9907 DeclareImplicitDestructor(ClassDecl); 9908 } 9909 9910 // C++2a [class.compare.default]p3: 9911 // If the member-specification does not explicitly declare any member or 9912 // friend named operator==, an == operator function is declared implicitly 9913 // for each defaulted three-way comparison operator function defined in the 9914 // member-specification 9915 // FIXME: Consider doing this lazily. 9916 if (getLangOpts().CPlusPlus20) { 9917 llvm::SmallVector<FunctionDecl*, 4> DefaultedSpaceships; 9918 findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl, 9919 DefaultedSpaceships); 9920 for (auto *FD : DefaultedSpaceships) 9921 DeclareImplicitEqualityComparison(ClassDecl, FD); 9922 } 9923 } 9924 9925 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 9926 if (!D) 9927 return 0; 9928 9929 // The order of template parameters is not important here. All names 9930 // get added to the same scope. 9931 SmallVector<TemplateParameterList *, 4> ParameterLists; 9932 9933 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 9934 D = TD->getTemplatedDecl(); 9935 9936 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 9937 ParameterLists.push_back(PSD->getTemplateParameters()); 9938 9939 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 9940 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 9941 ParameterLists.push_back(DD->getTemplateParameterList(i)); 9942 9943 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 9944 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 9945 ParameterLists.push_back(FTD->getTemplateParameters()); 9946 } 9947 } 9948 9949 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 9950 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 9951 ParameterLists.push_back(TD->getTemplateParameterList(i)); 9952 9953 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 9954 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 9955 ParameterLists.push_back(CTD->getTemplateParameters()); 9956 } 9957 } 9958 9959 unsigned Count = 0; 9960 for (TemplateParameterList *Params : ParameterLists) { 9961 if (Params->size() > 0) 9962 // Ignore explicit specializations; they don't contribute to the template 9963 // depth. 9964 ++Count; 9965 for (NamedDecl *Param : *Params) { 9966 if (Param->getDeclName()) { 9967 S->AddDecl(Param); 9968 IdResolver.AddDecl(Param); 9969 } 9970 } 9971 } 9972 9973 return Count; 9974 } 9975 9976 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 9977 if (!RecordD) return; 9978 AdjustDeclIfTemplate(RecordD); 9979 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 9980 PushDeclContext(S, Record); 9981 } 9982 9983 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 9984 if (!RecordD) return; 9985 PopDeclContext(); 9986 } 9987 9988 /// This is used to implement the constant expression evaluation part of the 9989 /// attribute enable_if extension. There is nothing in standard C++ which would 9990 /// require reentering parameters. 9991 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 9992 if (!Param) 9993 return; 9994 9995 S->AddDecl(Param); 9996 if (Param->getDeclName()) 9997 IdResolver.AddDecl(Param); 9998 } 9999 10000 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 10001 /// parsing a top-level (non-nested) C++ class, and we are now 10002 /// parsing those parts of the given Method declaration that could 10003 /// not be parsed earlier (C++ [class.mem]p2), such as default 10004 /// arguments. This action should enter the scope of the given 10005 /// Method declaration as if we had just parsed the qualified method 10006 /// name. However, it should not bring the parameters into scope; 10007 /// that will be performed by ActOnDelayedCXXMethodParameter. 10008 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 10009 } 10010 10011 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 10012 /// C++ method declaration. We're (re-)introducing the given 10013 /// function parameter into scope for use in parsing later parts of 10014 /// the method declaration. For example, we could see an 10015 /// ActOnParamDefaultArgument event for this parameter. 10016 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 10017 if (!ParamD) 10018 return; 10019 10020 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 10021 10022 S->AddDecl(Param); 10023 if (Param->getDeclName()) 10024 IdResolver.AddDecl(Param); 10025 } 10026 10027 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 10028 /// processing the delayed method declaration for Method. The method 10029 /// declaration is now considered finished. There may be a separate 10030 /// ActOnStartOfFunctionDef action later (not necessarily 10031 /// immediately!) for this method, if it was also defined inside the 10032 /// class body. 10033 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 10034 if (!MethodD) 10035 return; 10036 10037 AdjustDeclIfTemplate(MethodD); 10038 10039 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 10040 10041 // Now that we have our default arguments, check the constructor 10042 // again. It could produce additional diagnostics or affect whether 10043 // the class has implicitly-declared destructors, among other 10044 // things. 10045 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 10046 CheckConstructor(Constructor); 10047 10048 // Check the default arguments, which we may have added. 10049 if (!Method->isInvalidDecl()) 10050 CheckCXXDefaultArguments(Method); 10051 } 10052 10053 // Emit the given diagnostic for each non-address-space qualifier. 10054 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator. 10055 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) { 10056 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10057 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) { 10058 bool DiagOccured = false; 10059 FTI.MethodQualifiers->forEachQualifier( 10060 [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName, 10061 SourceLocation SL) { 10062 // This diagnostic should be emitted on any qualifier except an addr 10063 // space qualifier. However, forEachQualifier currently doesn't visit 10064 // addr space qualifiers, so there's no way to write this condition 10065 // right now; we just diagnose on everything. 10066 S.Diag(SL, DiagID) << QualName << SourceRange(SL); 10067 DiagOccured = true; 10068 }); 10069 if (DiagOccured) 10070 D.setInvalidType(); 10071 } 10072 } 10073 10074 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 10075 /// the well-formedness of the constructor declarator @p D with type @p 10076 /// R. If there are any errors in the declarator, this routine will 10077 /// emit diagnostics and set the invalid bit to true. In any case, the type 10078 /// will be updated to reflect a well-formed type for the constructor and 10079 /// returned. 10080 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 10081 StorageClass &SC) { 10082 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 10083 10084 // C++ [class.ctor]p3: 10085 // A constructor shall not be virtual (10.3) or static (9.4). A 10086 // constructor can be invoked for a const, volatile or const 10087 // volatile object. A constructor shall not be declared const, 10088 // volatile, or const volatile (9.3.2). 10089 if (isVirtual) { 10090 if (!D.isInvalidType()) 10091 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 10092 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 10093 << SourceRange(D.getIdentifierLoc()); 10094 D.setInvalidType(); 10095 } 10096 if (SC == SC_Static) { 10097 if (!D.isInvalidType()) 10098 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 10099 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10100 << SourceRange(D.getIdentifierLoc()); 10101 D.setInvalidType(); 10102 SC = SC_None; 10103 } 10104 10105 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 10106 diagnoseIgnoredQualifiers( 10107 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 10108 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 10109 D.getDeclSpec().getRestrictSpecLoc(), 10110 D.getDeclSpec().getAtomicSpecLoc()); 10111 D.setInvalidType(); 10112 } 10113 10114 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor); 10115 10116 // C++0x [class.ctor]p4: 10117 // A constructor shall not be declared with a ref-qualifier. 10118 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10119 if (FTI.hasRefQualifier()) { 10120 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 10121 << FTI.RefQualifierIsLValueRef 10122 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 10123 D.setInvalidType(); 10124 } 10125 10126 // Rebuild the function type "R" without any type qualifiers (in 10127 // case any of the errors above fired) and with "void" as the 10128 // return type, since constructors don't have return types. 10129 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>(); 10130 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 10131 return R; 10132 10133 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 10134 EPI.TypeQuals = Qualifiers(); 10135 EPI.RefQualifier = RQ_None; 10136 10137 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 10138 } 10139 10140 /// CheckConstructor - Checks a fully-formed constructor for 10141 /// well-formedness, issuing any diagnostics required. Returns true if 10142 /// the constructor declarator is invalid. 10143 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 10144 CXXRecordDecl *ClassDecl 10145 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 10146 if (!ClassDecl) 10147 return Constructor->setInvalidDecl(); 10148 10149 // C++ [class.copy]p3: 10150 // A declaration of a constructor for a class X is ill-formed if 10151 // its first parameter is of type (optionally cv-qualified) X and 10152 // either there are no other parameters or else all other 10153 // parameters have default arguments. 10154 if (!Constructor->isInvalidDecl() && 10155 Constructor->hasOneParamOrDefaultArgs() && 10156 Constructor->getTemplateSpecializationKind() != 10157 TSK_ImplicitInstantiation) { 10158 QualType ParamType = Constructor->getParamDecl(0)->getType(); 10159 QualType ClassTy = Context.getTagDeclType(ClassDecl); 10160 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 10161 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 10162 const char *ConstRef 10163 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 10164 : " const &"; 10165 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 10166 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 10167 10168 // FIXME: Rather that making the constructor invalid, we should endeavor 10169 // to fix the type. 10170 Constructor->setInvalidDecl(); 10171 } 10172 } 10173 } 10174 10175 /// CheckDestructor - Checks a fully-formed destructor definition for 10176 /// well-formedness, issuing any diagnostics required. Returns true 10177 /// on error. 10178 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 10179 CXXRecordDecl *RD = Destructor->getParent(); 10180 10181 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 10182 SourceLocation Loc; 10183 10184 if (!Destructor->isImplicit()) 10185 Loc = Destructor->getLocation(); 10186 else 10187 Loc = RD->getLocation(); 10188 10189 // If we have a virtual destructor, look up the deallocation function 10190 if (FunctionDecl *OperatorDelete = 10191 FindDeallocationFunctionForDestructor(Loc, RD)) { 10192 Expr *ThisArg = nullptr; 10193 10194 // If the notional 'delete this' expression requires a non-trivial 10195 // conversion from 'this' to the type of a destroying operator delete's 10196 // first parameter, perform that conversion now. 10197 if (OperatorDelete->isDestroyingOperatorDelete()) { 10198 QualType ParamType = OperatorDelete->getParamDecl(0)->getType(); 10199 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) { 10200 // C++ [class.dtor]p13: 10201 // ... as if for the expression 'delete this' appearing in a 10202 // non-virtual destructor of the destructor's class. 10203 ContextRAII SwitchContext(*this, Destructor); 10204 ExprResult This = 10205 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation()); 10206 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?"); 10207 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing); 10208 if (This.isInvalid()) { 10209 // FIXME: Register this as a context note so that it comes out 10210 // in the right order. 10211 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here); 10212 return true; 10213 } 10214 ThisArg = This.get(); 10215 } 10216 } 10217 10218 DiagnoseUseOfDecl(OperatorDelete, Loc); 10219 MarkFunctionReferenced(Loc, OperatorDelete); 10220 Destructor->setOperatorDelete(OperatorDelete, ThisArg); 10221 } 10222 } 10223 10224 return false; 10225 } 10226 10227 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 10228 /// the well-formednes of the destructor declarator @p D with type @p 10229 /// R. If there are any errors in the declarator, this routine will 10230 /// emit diagnostics and set the declarator to invalid. Even if this happens, 10231 /// will be updated to reflect a well-formed type for the destructor and 10232 /// returned. 10233 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 10234 StorageClass& SC) { 10235 // C++ [class.dtor]p1: 10236 // [...] A typedef-name that names a class is a class-name 10237 // (7.1.3); however, a typedef-name that names a class shall not 10238 // be used as the identifier in the declarator for a destructor 10239 // declaration. 10240 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 10241 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 10242 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name) 10243 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 10244 else if (const TemplateSpecializationType *TST = 10245 DeclaratorType->getAs<TemplateSpecializationType>()) 10246 if (TST->isTypeAlias()) 10247 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name) 10248 << DeclaratorType << 1; 10249 10250 // C++ [class.dtor]p2: 10251 // A destructor is used to destroy objects of its class type. A 10252 // destructor takes no parameters, and no return type can be 10253 // specified for it (not even void). The address of a destructor 10254 // shall not be taken. A destructor shall not be static. A 10255 // destructor can be invoked for a const, volatile or const 10256 // volatile object. A destructor shall not be declared const, 10257 // volatile or const volatile (9.3.2). 10258 if (SC == SC_Static) { 10259 if (!D.isInvalidType()) 10260 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 10261 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10262 << SourceRange(D.getIdentifierLoc()) 10263 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 10264 10265 SC = SC_None; 10266 } 10267 if (!D.isInvalidType()) { 10268 // Destructors don't have return types, but the parser will 10269 // happily parse something like: 10270 // 10271 // class X { 10272 // float ~X(); 10273 // }; 10274 // 10275 // The return type will be eliminated later. 10276 if (D.getDeclSpec().hasTypeSpecifier()) 10277 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 10278 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 10279 << SourceRange(D.getIdentifierLoc()); 10280 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 10281 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 10282 SourceLocation(), 10283 D.getDeclSpec().getConstSpecLoc(), 10284 D.getDeclSpec().getVolatileSpecLoc(), 10285 D.getDeclSpec().getRestrictSpecLoc(), 10286 D.getDeclSpec().getAtomicSpecLoc()); 10287 D.setInvalidType(); 10288 } 10289 } 10290 10291 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor); 10292 10293 // C++0x [class.dtor]p2: 10294 // A destructor shall not be declared with a ref-qualifier. 10295 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10296 if (FTI.hasRefQualifier()) { 10297 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 10298 << FTI.RefQualifierIsLValueRef 10299 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 10300 D.setInvalidType(); 10301 } 10302 10303 // Make sure we don't have any parameters. 10304 if (FTIHasNonVoidParameters(FTI)) { 10305 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 10306 10307 // Delete the parameters. 10308 FTI.freeParams(); 10309 D.setInvalidType(); 10310 } 10311 10312 // Make sure the destructor isn't variadic. 10313 if (FTI.isVariadic) { 10314 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 10315 D.setInvalidType(); 10316 } 10317 10318 // Rebuild the function type "R" without any type qualifiers or 10319 // parameters (in case any of the errors above fired) and with 10320 // "void" as the return type, since destructors don't have return 10321 // types. 10322 if (!D.isInvalidType()) 10323 return R; 10324 10325 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>(); 10326 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 10327 EPI.Variadic = false; 10328 EPI.TypeQuals = Qualifiers(); 10329 EPI.RefQualifier = RQ_None; 10330 return Context.getFunctionType(Context.VoidTy, None, EPI); 10331 } 10332 10333 static void extendLeft(SourceRange &R, SourceRange Before) { 10334 if (Before.isInvalid()) 10335 return; 10336 R.setBegin(Before.getBegin()); 10337 if (R.getEnd().isInvalid()) 10338 R.setEnd(Before.getEnd()); 10339 } 10340 10341 static void extendRight(SourceRange &R, SourceRange After) { 10342 if (After.isInvalid()) 10343 return; 10344 if (R.getBegin().isInvalid()) 10345 R.setBegin(After.getBegin()); 10346 R.setEnd(After.getEnd()); 10347 } 10348 10349 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 10350 /// well-formednes of the conversion function declarator @p D with 10351 /// type @p R. If there are any errors in the declarator, this routine 10352 /// will emit diagnostics and return true. Otherwise, it will return 10353 /// false. Either way, the type @p R will be updated to reflect a 10354 /// well-formed type for the conversion operator. 10355 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 10356 StorageClass& SC) { 10357 // C++ [class.conv.fct]p1: 10358 // Neither parameter types nor return type can be specified. The 10359 // type of a conversion function (8.3.5) is "function taking no 10360 // parameter returning conversion-type-id." 10361 if (SC == SC_Static) { 10362 if (!D.isInvalidType()) 10363 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 10364 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 10365 << D.getName().getSourceRange(); 10366 D.setInvalidType(); 10367 SC = SC_None; 10368 } 10369 10370 TypeSourceInfo *ConvTSI = nullptr; 10371 QualType ConvType = 10372 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); 10373 10374 const DeclSpec &DS = D.getDeclSpec(); 10375 if (DS.hasTypeSpecifier() && !D.isInvalidType()) { 10376 // Conversion functions don't have return types, but the parser will 10377 // happily parse something like: 10378 // 10379 // class X { 10380 // float operator bool(); 10381 // }; 10382 // 10383 // The return type will be changed later anyway. 10384 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 10385 << SourceRange(DS.getTypeSpecTypeLoc()) 10386 << SourceRange(D.getIdentifierLoc()); 10387 D.setInvalidType(); 10388 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) { 10389 // It's also plausible that the user writes type qualifiers in the wrong 10390 // place, such as: 10391 // struct S { const operator int(); }; 10392 // FIXME: we could provide a fixit to move the qualifiers onto the 10393 // conversion type. 10394 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 10395 << SourceRange(D.getIdentifierLoc()) << 0; 10396 D.setInvalidType(); 10397 } 10398 10399 const auto *Proto = R->castAs<FunctionProtoType>(); 10400 10401 // Make sure we don't have any parameters. 10402 if (Proto->getNumParams() > 0) { 10403 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 10404 10405 // Delete the parameters. 10406 D.getFunctionTypeInfo().freeParams(); 10407 D.setInvalidType(); 10408 } else if (Proto->isVariadic()) { 10409 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 10410 D.setInvalidType(); 10411 } 10412 10413 // Diagnose "&operator bool()" and other such nonsense. This 10414 // is actually a gcc extension which we don't support. 10415 if (Proto->getReturnType() != ConvType) { 10416 bool NeedsTypedef = false; 10417 SourceRange Before, After; 10418 10419 // Walk the chunks and extract information on them for our diagnostic. 10420 bool PastFunctionChunk = false; 10421 for (auto &Chunk : D.type_objects()) { 10422 switch (Chunk.Kind) { 10423 case DeclaratorChunk::Function: 10424 if (!PastFunctionChunk) { 10425 if (Chunk.Fun.HasTrailingReturnType) { 10426 TypeSourceInfo *TRT = nullptr; 10427 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); 10428 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); 10429 } 10430 PastFunctionChunk = true; 10431 break; 10432 } 10433 LLVM_FALLTHROUGH; 10434 case DeclaratorChunk::Array: 10435 NeedsTypedef = true; 10436 extendRight(After, Chunk.getSourceRange()); 10437 break; 10438 10439 case DeclaratorChunk::Pointer: 10440 case DeclaratorChunk::BlockPointer: 10441 case DeclaratorChunk::Reference: 10442 case DeclaratorChunk::MemberPointer: 10443 case DeclaratorChunk::Pipe: 10444 extendLeft(Before, Chunk.getSourceRange()); 10445 break; 10446 10447 case DeclaratorChunk::Paren: 10448 extendLeft(Before, Chunk.Loc); 10449 extendRight(After, Chunk.EndLoc); 10450 break; 10451 } 10452 } 10453 10454 SourceLocation Loc = Before.isValid() ? Before.getBegin() : 10455 After.isValid() ? After.getBegin() : 10456 D.getIdentifierLoc(); 10457 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); 10458 DB << Before << After; 10459 10460 if (!NeedsTypedef) { 10461 DB << /*don't need a typedef*/0; 10462 10463 // If we can provide a correct fix-it hint, do so. 10464 if (After.isInvalid() && ConvTSI) { 10465 SourceLocation InsertLoc = 10466 getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc()); 10467 DB << FixItHint::CreateInsertion(InsertLoc, " ") 10468 << FixItHint::CreateInsertionFromRange( 10469 InsertLoc, CharSourceRange::getTokenRange(Before)) 10470 << FixItHint::CreateRemoval(Before); 10471 } 10472 } else if (!Proto->getReturnType()->isDependentType()) { 10473 DB << /*typedef*/1 << Proto->getReturnType(); 10474 } else if (getLangOpts().CPlusPlus11) { 10475 DB << /*alias template*/2 << Proto->getReturnType(); 10476 } else { 10477 DB << /*might not be fixable*/3; 10478 } 10479 10480 // Recover by incorporating the other type chunks into the result type. 10481 // Note, this does *not* change the name of the function. This is compatible 10482 // with the GCC extension: 10483 // struct S { &operator int(); } s; 10484 // int &r = s.operator int(); // ok in GCC 10485 // S::operator int&() {} // error in GCC, function name is 'operator int'. 10486 ConvType = Proto->getReturnType(); 10487 } 10488 10489 // C++ [class.conv.fct]p4: 10490 // The conversion-type-id shall not represent a function type nor 10491 // an array type. 10492 if (ConvType->isArrayType()) { 10493 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 10494 ConvType = Context.getPointerType(ConvType); 10495 D.setInvalidType(); 10496 } else if (ConvType->isFunctionType()) { 10497 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 10498 ConvType = Context.getPointerType(ConvType); 10499 D.setInvalidType(); 10500 } 10501 10502 // Rebuild the function type "R" without any parameters (in case any 10503 // of the errors above fired) and with the conversion type as the 10504 // return type. 10505 if (D.isInvalidType()) 10506 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 10507 10508 // C++0x explicit conversion operators. 10509 if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20) 10510 Diag(DS.getExplicitSpecLoc(), 10511 getLangOpts().CPlusPlus11 10512 ? diag::warn_cxx98_compat_explicit_conversion_functions 10513 : diag::ext_explicit_conversion_functions) 10514 << SourceRange(DS.getExplicitSpecRange()); 10515 } 10516 10517 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 10518 /// the declaration of the given C++ conversion function. This routine 10519 /// is responsible for recording the conversion function in the C++ 10520 /// class, if possible. 10521 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 10522 assert(Conversion && "Expected to receive a conversion function declaration"); 10523 10524 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 10525 10526 // Make sure we aren't redeclaring the conversion function. 10527 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 10528 // C++ [class.conv.fct]p1: 10529 // [...] A conversion function is never used to convert a 10530 // (possibly cv-qualified) object to the (possibly cv-qualified) 10531 // same object type (or a reference to it), to a (possibly 10532 // cv-qualified) base class of that type (or a reference to it), 10533 // or to (possibly cv-qualified) void. 10534 QualType ClassType 10535 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 10536 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 10537 ConvType = ConvTypeRef->getPointeeType(); 10538 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 10539 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 10540 /* Suppress diagnostics for instantiations. */; 10541 else if (Conversion->size_overridden_methods() != 0) 10542 /* Suppress diagnostics for overriding virtual function in a base class. */; 10543 else if (ConvType->isRecordType()) { 10544 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 10545 if (ConvType == ClassType) 10546 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 10547 << ClassType; 10548 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType)) 10549 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 10550 << ClassType << ConvType; 10551 } else if (ConvType->isVoidType()) { 10552 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 10553 << ClassType << ConvType; 10554 } 10555 10556 if (FunctionTemplateDecl *ConversionTemplate 10557 = Conversion->getDescribedFunctionTemplate()) 10558 return ConversionTemplate; 10559 10560 return Conversion; 10561 } 10562 10563 namespace { 10564 /// Utility class to accumulate and print a diagnostic listing the invalid 10565 /// specifier(s) on a declaration. 10566 struct BadSpecifierDiagnoser { 10567 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID) 10568 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {} 10569 ~BadSpecifierDiagnoser() { 10570 Diagnostic << Specifiers; 10571 } 10572 10573 template<typename T> void check(SourceLocation SpecLoc, T Spec) { 10574 return check(SpecLoc, DeclSpec::getSpecifierName(Spec)); 10575 } 10576 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) { 10577 return check(SpecLoc, 10578 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy())); 10579 } 10580 void check(SourceLocation SpecLoc, const char *Spec) { 10581 if (SpecLoc.isInvalid()) return; 10582 Diagnostic << SourceRange(SpecLoc, SpecLoc); 10583 if (!Specifiers.empty()) Specifiers += " "; 10584 Specifiers += Spec; 10585 } 10586 10587 Sema &S; 10588 Sema::SemaDiagnosticBuilder Diagnostic; 10589 std::string Specifiers; 10590 }; 10591 } 10592 10593 /// Check the validity of a declarator that we parsed for a deduction-guide. 10594 /// These aren't actually declarators in the grammar, so we need to check that 10595 /// the user didn't specify any pieces that are not part of the deduction-guide 10596 /// grammar. 10597 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R, 10598 StorageClass &SC) { 10599 TemplateName GuidedTemplate = D.getName().TemplateName.get().get(); 10600 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl(); 10601 assert(GuidedTemplateDecl && "missing template decl for deduction guide"); 10602 10603 // C++ [temp.deduct.guide]p3: 10604 // A deduction-gide shall be declared in the same scope as the 10605 // corresponding class template. 10606 if (!CurContext->getRedeclContext()->Equals( 10607 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) { 10608 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope) 10609 << GuidedTemplateDecl; 10610 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here); 10611 } 10612 10613 auto &DS = D.getMutableDeclSpec(); 10614 // We leave 'friend' and 'virtual' to be rejected in the normal way. 10615 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() || 10616 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() || 10617 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) { 10618 BadSpecifierDiagnoser Diagnoser( 10619 *this, D.getIdentifierLoc(), 10620 diag::err_deduction_guide_invalid_specifier); 10621 10622 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec()); 10623 DS.ClearStorageClassSpecs(); 10624 SC = SC_None; 10625 10626 // 'explicit' is permitted. 10627 Diagnoser.check(DS.getInlineSpecLoc(), "inline"); 10628 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn"); 10629 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr"); 10630 DS.ClearConstexprSpec(); 10631 10632 Diagnoser.check(DS.getConstSpecLoc(), "const"); 10633 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict"); 10634 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile"); 10635 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic"); 10636 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned"); 10637 DS.ClearTypeQualifiers(); 10638 10639 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex()); 10640 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign()); 10641 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth()); 10642 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType()); 10643 DS.ClearTypeSpecType(); 10644 } 10645 10646 if (D.isInvalidType()) 10647 return; 10648 10649 // Check the declarator is simple enough. 10650 bool FoundFunction = false; 10651 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) { 10652 if (Chunk.Kind == DeclaratorChunk::Paren) 10653 continue; 10654 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) { 10655 Diag(D.getDeclSpec().getBeginLoc(), 10656 diag::err_deduction_guide_with_complex_decl) 10657 << D.getSourceRange(); 10658 break; 10659 } 10660 if (!Chunk.Fun.hasTrailingReturnType()) { 10661 Diag(D.getName().getBeginLoc(), 10662 diag::err_deduction_guide_no_trailing_return_type); 10663 break; 10664 } 10665 10666 // Check that the return type is written as a specialization of 10667 // the template specified as the deduction-guide's name. 10668 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType(); 10669 TypeSourceInfo *TSI = nullptr; 10670 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI); 10671 assert(TSI && "deduction guide has valid type but invalid return type?"); 10672 bool AcceptableReturnType = false; 10673 bool MightInstantiateToSpecialization = false; 10674 if (auto RetTST = 10675 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) { 10676 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName(); 10677 bool TemplateMatches = 10678 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate); 10679 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches) 10680 AcceptableReturnType = true; 10681 else { 10682 // This could still instantiate to the right type, unless we know it 10683 // names the wrong class template. 10684 auto *TD = SpecifiedName.getAsTemplateDecl(); 10685 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) && 10686 !TemplateMatches); 10687 } 10688 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) { 10689 MightInstantiateToSpecialization = true; 10690 } 10691 10692 if (!AcceptableReturnType) { 10693 Diag(TSI->getTypeLoc().getBeginLoc(), 10694 diag::err_deduction_guide_bad_trailing_return_type) 10695 << GuidedTemplate << TSI->getType() 10696 << MightInstantiateToSpecialization 10697 << TSI->getTypeLoc().getSourceRange(); 10698 } 10699 10700 // Keep going to check that we don't have any inner declarator pieces (we 10701 // could still have a function returning a pointer to a function). 10702 FoundFunction = true; 10703 } 10704 10705 if (D.isFunctionDefinition()) 10706 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function); 10707 } 10708 10709 //===----------------------------------------------------------------------===// 10710 // Namespace Handling 10711 //===----------------------------------------------------------------------===// 10712 10713 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is 10714 /// reopened. 10715 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 10716 SourceLocation Loc, 10717 IdentifierInfo *II, bool *IsInline, 10718 NamespaceDecl *PrevNS) { 10719 assert(*IsInline != PrevNS->isInline()); 10720 10721 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 10722 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 10723 // inline namespaces, with the intention of bringing names into namespace std. 10724 // 10725 // We support this just well enough to get that case working; this is not 10726 // sufficient to support reopening namespaces as inline in general. 10727 if (*IsInline && II && II->getName().startswith("__atomic") && 10728 S.getSourceManager().isInSystemHeader(Loc)) { 10729 // Mark all prior declarations of the namespace as inline. 10730 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 10731 NS = NS->getPreviousDecl()) 10732 NS->setInline(*IsInline); 10733 // Patch up the lookup table for the containing namespace. This isn't really 10734 // correct, but it's good enough for this particular case. 10735 for (auto *I : PrevNS->decls()) 10736 if (auto *ND = dyn_cast<NamedDecl>(I)) 10737 PrevNS->getParent()->makeDeclVisibleInContext(ND); 10738 return; 10739 } 10740 10741 if (PrevNS->isInline()) 10742 // The user probably just forgot the 'inline', so suggest that it 10743 // be added back. 10744 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 10745 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 10746 else 10747 S.Diag(Loc, diag::err_inline_namespace_mismatch); 10748 10749 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 10750 *IsInline = PrevNS->isInline(); 10751 } 10752 10753 /// ActOnStartNamespaceDef - This is called at the start of a namespace 10754 /// definition. 10755 Decl *Sema::ActOnStartNamespaceDef( 10756 Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc, 10757 SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace, 10758 const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) { 10759 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 10760 // For anonymous namespace, take the location of the left brace. 10761 SourceLocation Loc = II ? IdentLoc : LBrace; 10762 bool IsInline = InlineLoc.isValid(); 10763 bool IsInvalid = false; 10764 bool IsStd = false; 10765 bool AddToKnown = false; 10766 Scope *DeclRegionScope = NamespcScope->getParent(); 10767 10768 NamespaceDecl *PrevNS = nullptr; 10769 if (II) { 10770 // C++ [namespace.def]p2: 10771 // The identifier in an original-namespace-definition shall not 10772 // have been previously defined in the declarative region in 10773 // which the original-namespace-definition appears. The 10774 // identifier in an original-namespace-definition is the name of 10775 // the namespace. Subsequently in that declarative region, it is 10776 // treated as an original-namespace-name. 10777 // 10778 // Since namespace names are unique in their scope, and we don't 10779 // look through using directives, just look for any ordinary names 10780 // as if by qualified name lookup. 10781 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, 10782 ForExternalRedeclaration); 10783 LookupQualifiedName(R, CurContext->getRedeclContext()); 10784 NamedDecl *PrevDecl = 10785 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr; 10786 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 10787 10788 if (PrevNS) { 10789 // This is an extended namespace definition. 10790 if (IsInline != PrevNS->isInline()) 10791 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 10792 &IsInline, PrevNS); 10793 } else if (PrevDecl) { 10794 // This is an invalid name redefinition. 10795 Diag(Loc, diag::err_redefinition_different_kind) 10796 << II; 10797 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 10798 IsInvalid = true; 10799 // Continue on to push Namespc as current DeclContext and return it. 10800 } else if (II->isStr("std") && 10801 CurContext->getRedeclContext()->isTranslationUnit()) { 10802 // This is the first "real" definition of the namespace "std", so update 10803 // our cache of the "std" namespace to point at this definition. 10804 PrevNS = getStdNamespace(); 10805 IsStd = true; 10806 AddToKnown = !IsInline; 10807 } else { 10808 // We've seen this namespace for the first time. 10809 AddToKnown = !IsInline; 10810 } 10811 } else { 10812 // Anonymous namespaces. 10813 10814 // Determine whether the parent already has an anonymous namespace. 10815 DeclContext *Parent = CurContext->getRedeclContext(); 10816 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 10817 PrevNS = TU->getAnonymousNamespace(); 10818 } else { 10819 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 10820 PrevNS = ND->getAnonymousNamespace(); 10821 } 10822 10823 if (PrevNS && IsInline != PrevNS->isInline()) 10824 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 10825 &IsInline, PrevNS); 10826 } 10827 10828 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 10829 StartLoc, Loc, II, PrevNS); 10830 if (IsInvalid) 10831 Namespc->setInvalidDecl(); 10832 10833 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 10834 AddPragmaAttributes(DeclRegionScope, Namespc); 10835 10836 // FIXME: Should we be merging attributes? 10837 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 10838 PushNamespaceVisibilityAttr(Attr, Loc); 10839 10840 if (IsStd) 10841 StdNamespace = Namespc; 10842 if (AddToKnown) 10843 KnownNamespaces[Namespc] = false; 10844 10845 if (II) { 10846 PushOnScopeChains(Namespc, DeclRegionScope); 10847 } else { 10848 // Link the anonymous namespace into its parent. 10849 DeclContext *Parent = CurContext->getRedeclContext(); 10850 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 10851 TU->setAnonymousNamespace(Namespc); 10852 } else { 10853 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 10854 } 10855 10856 CurContext->addDecl(Namespc); 10857 10858 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 10859 // behaves as if it were replaced by 10860 // namespace unique { /* empty body */ } 10861 // using namespace unique; 10862 // namespace unique { namespace-body } 10863 // where all occurrences of 'unique' in a translation unit are 10864 // replaced by the same identifier and this identifier differs 10865 // from all other identifiers in the entire program. 10866 10867 // We just create the namespace with an empty name and then add an 10868 // implicit using declaration, just like the standard suggests. 10869 // 10870 // CodeGen enforces the "universally unique" aspect by giving all 10871 // declarations semantically contained within an anonymous 10872 // namespace internal linkage. 10873 10874 if (!PrevNS) { 10875 UD = UsingDirectiveDecl::Create(Context, Parent, 10876 /* 'using' */ LBrace, 10877 /* 'namespace' */ SourceLocation(), 10878 /* qualifier */ NestedNameSpecifierLoc(), 10879 /* identifier */ SourceLocation(), 10880 Namespc, 10881 /* Ancestor */ Parent); 10882 UD->setImplicit(); 10883 Parent->addDecl(UD); 10884 } 10885 } 10886 10887 ActOnDocumentableDecl(Namespc); 10888 10889 // Although we could have an invalid decl (i.e. the namespace name is a 10890 // redefinition), push it as current DeclContext and try to continue parsing. 10891 // FIXME: We should be able to push Namespc here, so that the each DeclContext 10892 // for the namespace has the declarations that showed up in that particular 10893 // namespace definition. 10894 PushDeclContext(NamespcScope, Namespc); 10895 return Namespc; 10896 } 10897 10898 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 10899 /// is a namespace alias, returns the namespace it points to. 10900 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 10901 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 10902 return AD->getNamespace(); 10903 return dyn_cast_or_null<NamespaceDecl>(D); 10904 } 10905 10906 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 10907 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 10908 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 10909 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 10910 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 10911 Namespc->setRBraceLoc(RBrace); 10912 PopDeclContext(); 10913 if (Namespc->hasAttr<VisibilityAttr>()) 10914 PopPragmaVisibility(true, RBrace); 10915 // If this namespace contains an export-declaration, export it now. 10916 if (DeferredExportedNamespaces.erase(Namespc)) 10917 Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported); 10918 } 10919 10920 CXXRecordDecl *Sema::getStdBadAlloc() const { 10921 return cast_or_null<CXXRecordDecl>( 10922 StdBadAlloc.get(Context.getExternalSource())); 10923 } 10924 10925 EnumDecl *Sema::getStdAlignValT() const { 10926 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource())); 10927 } 10928 10929 NamespaceDecl *Sema::getStdNamespace() const { 10930 return cast_or_null<NamespaceDecl>( 10931 StdNamespace.get(Context.getExternalSource())); 10932 } 10933 10934 NamespaceDecl *Sema::lookupStdExperimentalNamespace() { 10935 if (!StdExperimentalNamespaceCache) { 10936 if (auto Std = getStdNamespace()) { 10937 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"), 10938 SourceLocation(), LookupNamespaceName); 10939 if (!LookupQualifiedName(Result, Std) || 10940 !(StdExperimentalNamespaceCache = 10941 Result.getAsSingle<NamespaceDecl>())) 10942 Result.suppressDiagnostics(); 10943 } 10944 } 10945 return StdExperimentalNamespaceCache; 10946 } 10947 10948 namespace { 10949 10950 enum UnsupportedSTLSelect { 10951 USS_InvalidMember, 10952 USS_MissingMember, 10953 USS_NonTrivial, 10954 USS_Other 10955 }; 10956 10957 struct InvalidSTLDiagnoser { 10958 Sema &S; 10959 SourceLocation Loc; 10960 QualType TyForDiags; 10961 10962 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "", 10963 const VarDecl *VD = nullptr) { 10964 { 10965 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported) 10966 << TyForDiags << ((int)Sel); 10967 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) { 10968 assert(!Name.empty()); 10969 D << Name; 10970 } 10971 } 10972 if (Sel == USS_InvalidMember) { 10973 S.Diag(VD->getLocation(), diag::note_var_declared_here) 10974 << VD << VD->getSourceRange(); 10975 } 10976 return QualType(); 10977 } 10978 }; 10979 } // namespace 10980 10981 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind, 10982 SourceLocation Loc, 10983 ComparisonCategoryUsage Usage) { 10984 assert(getLangOpts().CPlusPlus && 10985 "Looking for comparison category type outside of C++."); 10986 10987 // Use an elaborated type for diagnostics which has a name containing the 10988 // prepended 'std' namespace but not any inline namespace names. 10989 auto TyForDiags = [&](ComparisonCategoryInfo *Info) { 10990 auto *NNS = 10991 NestedNameSpecifier::Create(Context, nullptr, getStdNamespace()); 10992 return Context.getElaboratedType(ETK_None, NNS, Info->getType()); 10993 }; 10994 10995 // Check if we've already successfully checked the comparison category type 10996 // before. If so, skip checking it again. 10997 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind); 10998 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) { 10999 // The only thing we need to check is that the type has a reachable 11000 // definition in the current context. 11001 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type)) 11002 return QualType(); 11003 11004 return Info->getType(); 11005 } 11006 11007 // If lookup failed 11008 if (!Info) { 11009 std::string NameForDiags = "std::"; 11010 NameForDiags += ComparisonCategories::getCategoryString(Kind); 11011 Diag(Loc, diag::err_implied_comparison_category_type_not_found) 11012 << NameForDiags << (int)Usage; 11013 return QualType(); 11014 } 11015 11016 assert(Info->Kind == Kind); 11017 assert(Info->Record); 11018 11019 // Update the Record decl in case we encountered a forward declaration on our 11020 // first pass. FIXME: This is a bit of a hack. 11021 if (Info->Record->hasDefinition()) 11022 Info->Record = Info->Record->getDefinition(); 11023 11024 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type)) 11025 return QualType(); 11026 11027 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)}; 11028 11029 if (!Info->Record->isTriviallyCopyable()) 11030 return UnsupportedSTLError(USS_NonTrivial); 11031 11032 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) { 11033 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl(); 11034 // Tolerate empty base classes. 11035 if (Base->isEmpty()) 11036 continue; 11037 // Reject STL implementations which have at least one non-empty base. 11038 return UnsupportedSTLError(); 11039 } 11040 11041 // Check that the STL has implemented the types using a single integer field. 11042 // This expectation allows better codegen for builtin operators. We require: 11043 // (1) The class has exactly one field. 11044 // (2) The field is an integral or enumeration type. 11045 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end(); 11046 if (std::distance(FIt, FEnd) != 1 || 11047 !FIt->getType()->isIntegralOrEnumerationType()) { 11048 return UnsupportedSTLError(); 11049 } 11050 11051 // Build each of the require values and store them in Info. 11052 for (ComparisonCategoryResult CCR : 11053 ComparisonCategories::getPossibleResultsForType(Kind)) { 11054 StringRef MemName = ComparisonCategories::getResultString(CCR); 11055 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR); 11056 11057 if (!ValInfo) 11058 return UnsupportedSTLError(USS_MissingMember, MemName); 11059 11060 VarDecl *VD = ValInfo->VD; 11061 assert(VD && "should not be null!"); 11062 11063 // Attempt to diagnose reasons why the STL definition of this type 11064 // might be foobar, including it failing to be a constant expression. 11065 // TODO Handle more ways the lookup or result can be invalid. 11066 if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() || 11067 !VD->checkInitIsICE()) 11068 return UnsupportedSTLError(USS_InvalidMember, MemName, VD); 11069 11070 // Attempt to evaluate the var decl as a constant expression and extract 11071 // the value of its first field as a ICE. If this fails, the STL 11072 // implementation is not supported. 11073 if (!ValInfo->hasValidIntValue()) 11074 return UnsupportedSTLError(); 11075 11076 MarkVariableReferenced(Loc, VD); 11077 } 11078 11079 // We've successfully built the required types and expressions. Update 11080 // the cache and return the newly cached value. 11081 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true; 11082 return Info->getType(); 11083 } 11084 11085 /// Retrieve the special "std" namespace, which may require us to 11086 /// implicitly define the namespace. 11087 NamespaceDecl *Sema::getOrCreateStdNamespace() { 11088 if (!StdNamespace) { 11089 // The "std" namespace has not yet been defined, so build one implicitly. 11090 StdNamespace = NamespaceDecl::Create(Context, 11091 Context.getTranslationUnitDecl(), 11092 /*Inline=*/false, 11093 SourceLocation(), SourceLocation(), 11094 &PP.getIdentifierTable().get("std"), 11095 /*PrevDecl=*/nullptr); 11096 getStdNamespace()->setImplicit(true); 11097 } 11098 11099 return getStdNamespace(); 11100 } 11101 11102 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 11103 assert(getLangOpts().CPlusPlus && 11104 "Looking for std::initializer_list outside of C++."); 11105 11106 // We're looking for implicit instantiations of 11107 // template <typename E> class std::initializer_list. 11108 11109 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 11110 return false; 11111 11112 ClassTemplateDecl *Template = nullptr; 11113 const TemplateArgument *Arguments = nullptr; 11114 11115 if (const RecordType *RT = Ty->getAs<RecordType>()) { 11116 11117 ClassTemplateSpecializationDecl *Specialization = 11118 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 11119 if (!Specialization) 11120 return false; 11121 11122 Template = Specialization->getSpecializedTemplate(); 11123 Arguments = Specialization->getTemplateArgs().data(); 11124 } else if (const TemplateSpecializationType *TST = 11125 Ty->getAs<TemplateSpecializationType>()) { 11126 Template = dyn_cast_or_null<ClassTemplateDecl>( 11127 TST->getTemplateName().getAsTemplateDecl()); 11128 Arguments = TST->getArgs(); 11129 } 11130 if (!Template) 11131 return false; 11132 11133 if (!StdInitializerList) { 11134 // Haven't recognized std::initializer_list yet, maybe this is it. 11135 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 11136 if (TemplateClass->getIdentifier() != 11137 &PP.getIdentifierTable().get("initializer_list") || 11138 !getStdNamespace()->InEnclosingNamespaceSetOf( 11139 TemplateClass->getDeclContext())) 11140 return false; 11141 // This is a template called std::initializer_list, but is it the right 11142 // template? 11143 TemplateParameterList *Params = Template->getTemplateParameters(); 11144 if (Params->getMinRequiredArguments() != 1) 11145 return false; 11146 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 11147 return false; 11148 11149 // It's the right template. 11150 StdInitializerList = Template; 11151 } 11152 11153 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) 11154 return false; 11155 11156 // This is an instance of std::initializer_list. Find the argument type. 11157 if (Element) 11158 *Element = Arguments[0].getAsType(); 11159 return true; 11160 } 11161 11162 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 11163 NamespaceDecl *Std = S.getStdNamespace(); 11164 if (!Std) { 11165 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 11166 return nullptr; 11167 } 11168 11169 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 11170 Loc, Sema::LookupOrdinaryName); 11171 if (!S.LookupQualifiedName(Result, Std)) { 11172 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 11173 return nullptr; 11174 } 11175 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 11176 if (!Template) { 11177 Result.suppressDiagnostics(); 11178 // We found something weird. Complain about the first thing we found. 11179 NamedDecl *Found = *Result.begin(); 11180 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 11181 return nullptr; 11182 } 11183 11184 // We found some template called std::initializer_list. Now verify that it's 11185 // correct. 11186 TemplateParameterList *Params = Template->getTemplateParameters(); 11187 if (Params->getMinRequiredArguments() != 1 || 11188 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 11189 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 11190 return nullptr; 11191 } 11192 11193 return Template; 11194 } 11195 11196 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 11197 if (!StdInitializerList) { 11198 StdInitializerList = LookupStdInitializerList(*this, Loc); 11199 if (!StdInitializerList) 11200 return QualType(); 11201 } 11202 11203 TemplateArgumentListInfo Args(Loc, Loc); 11204 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 11205 Context.getTrivialTypeSourceInfo(Element, 11206 Loc))); 11207 return Context.getCanonicalType( 11208 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 11209 } 11210 11211 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) { 11212 // C++ [dcl.init.list]p2: 11213 // A constructor is an initializer-list constructor if its first parameter 11214 // is of type std::initializer_list<E> or reference to possibly cv-qualified 11215 // std::initializer_list<E> for some type E, and either there are no other 11216 // parameters or else all other parameters have default arguments. 11217 if (!Ctor->hasOneParamOrDefaultArgs()) 11218 return false; 11219 11220 QualType ArgType = Ctor->getParamDecl(0)->getType(); 11221 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 11222 ArgType = RT->getPointeeType().getUnqualifiedType(); 11223 11224 return isStdInitializerList(ArgType, nullptr); 11225 } 11226 11227 /// Determine whether a using statement is in a context where it will be 11228 /// apply in all contexts. 11229 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 11230 switch (CurContext->getDeclKind()) { 11231 case Decl::TranslationUnit: 11232 return true; 11233 case Decl::LinkageSpec: 11234 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 11235 default: 11236 return false; 11237 } 11238 } 11239 11240 namespace { 11241 11242 // Callback to only accept typo corrections that are namespaces. 11243 class NamespaceValidatorCCC final : public CorrectionCandidateCallback { 11244 public: 11245 bool ValidateCandidate(const TypoCorrection &candidate) override { 11246 if (NamedDecl *ND = candidate.getCorrectionDecl()) 11247 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 11248 return false; 11249 } 11250 11251 std::unique_ptr<CorrectionCandidateCallback> clone() override { 11252 return std::make_unique<NamespaceValidatorCCC>(*this); 11253 } 11254 }; 11255 11256 } 11257 11258 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 11259 CXXScopeSpec &SS, 11260 SourceLocation IdentLoc, 11261 IdentifierInfo *Ident) { 11262 R.clear(); 11263 NamespaceValidatorCCC CCC{}; 11264 if (TypoCorrection Corrected = 11265 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC, 11266 Sema::CTK_ErrorRecovery)) { 11267 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 11268 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 11269 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 11270 Ident->getName().equals(CorrectedStr); 11271 S.diagnoseTypo(Corrected, 11272 S.PDiag(diag::err_using_directive_member_suggest) 11273 << Ident << DC << DroppedSpecifier << SS.getRange(), 11274 S.PDiag(diag::note_namespace_defined_here)); 11275 } else { 11276 S.diagnoseTypo(Corrected, 11277 S.PDiag(diag::err_using_directive_suggest) << Ident, 11278 S.PDiag(diag::note_namespace_defined_here)); 11279 } 11280 R.addDecl(Corrected.getFoundDecl()); 11281 return true; 11282 } 11283 return false; 11284 } 11285 11286 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc, 11287 SourceLocation NamespcLoc, CXXScopeSpec &SS, 11288 SourceLocation IdentLoc, 11289 IdentifierInfo *NamespcName, 11290 const ParsedAttributesView &AttrList) { 11291 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 11292 assert(NamespcName && "Invalid NamespcName."); 11293 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 11294 11295 // This can only happen along a recovery path. 11296 while (S->isTemplateParamScope()) 11297 S = S->getParent(); 11298 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 11299 11300 UsingDirectiveDecl *UDir = nullptr; 11301 NestedNameSpecifier *Qualifier = nullptr; 11302 if (SS.isSet()) 11303 Qualifier = SS.getScopeRep(); 11304 11305 // Lookup namespace name. 11306 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 11307 LookupParsedName(R, S, &SS); 11308 if (R.isAmbiguous()) 11309 return nullptr; 11310 11311 if (R.empty()) { 11312 R.clear(); 11313 // Allow "using namespace std;" or "using namespace ::std;" even if 11314 // "std" hasn't been defined yet, for GCC compatibility. 11315 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 11316 NamespcName->isStr("std")) { 11317 Diag(IdentLoc, diag::ext_using_undefined_std); 11318 R.addDecl(getOrCreateStdNamespace()); 11319 R.resolveKind(); 11320 } 11321 // Otherwise, attempt typo correction. 11322 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 11323 } 11324 11325 if (!R.empty()) { 11326 NamedDecl *Named = R.getRepresentativeDecl(); 11327 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>(); 11328 assert(NS && "expected namespace decl"); 11329 11330 // The use of a nested name specifier may trigger deprecation warnings. 11331 DiagnoseUseOfDecl(Named, IdentLoc); 11332 11333 // C++ [namespace.udir]p1: 11334 // A using-directive specifies that the names in the nominated 11335 // namespace can be used in the scope in which the 11336 // using-directive appears after the using-directive. During 11337 // unqualified name lookup (3.4.1), the names appear as if they 11338 // were declared in the nearest enclosing namespace which 11339 // contains both the using-directive and the nominated 11340 // namespace. [Note: in this context, "contains" means "contains 11341 // directly or indirectly". ] 11342 11343 // Find enclosing context containing both using-directive and 11344 // nominated namespace. 11345 DeclContext *CommonAncestor = NS; 11346 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 11347 CommonAncestor = CommonAncestor->getParent(); 11348 11349 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 11350 SS.getWithLocInContext(Context), 11351 IdentLoc, Named, CommonAncestor); 11352 11353 if (IsUsingDirectiveInToplevelContext(CurContext) && 11354 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 11355 Diag(IdentLoc, diag::warn_using_directive_in_header); 11356 } 11357 11358 PushUsingDirective(S, UDir); 11359 } else { 11360 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 11361 } 11362 11363 if (UDir) 11364 ProcessDeclAttributeList(S, UDir, AttrList); 11365 11366 return UDir; 11367 } 11368 11369 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 11370 // If the scope has an associated entity and the using directive is at 11371 // namespace or translation unit scope, add the UsingDirectiveDecl into 11372 // its lookup structure so qualified name lookup can find it. 11373 DeclContext *Ctx = S->getEntity(); 11374 if (Ctx && !Ctx->isFunctionOrMethod()) 11375 Ctx->addDecl(UDir); 11376 else 11377 // Otherwise, it is at block scope. The using-directives will affect lookup 11378 // only to the end of the scope. 11379 S->PushUsingDirective(UDir); 11380 } 11381 11382 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS, 11383 SourceLocation UsingLoc, 11384 SourceLocation TypenameLoc, CXXScopeSpec &SS, 11385 UnqualifiedId &Name, 11386 SourceLocation EllipsisLoc, 11387 const ParsedAttributesView &AttrList) { 11388 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 11389 11390 if (SS.isEmpty()) { 11391 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname); 11392 return nullptr; 11393 } 11394 11395 switch (Name.getKind()) { 11396 case UnqualifiedIdKind::IK_ImplicitSelfParam: 11397 case UnqualifiedIdKind::IK_Identifier: 11398 case UnqualifiedIdKind::IK_OperatorFunctionId: 11399 case UnqualifiedIdKind::IK_LiteralOperatorId: 11400 case UnqualifiedIdKind::IK_ConversionFunctionId: 11401 break; 11402 11403 case UnqualifiedIdKind::IK_ConstructorName: 11404 case UnqualifiedIdKind::IK_ConstructorTemplateId: 11405 // C++11 inheriting constructors. 11406 Diag(Name.getBeginLoc(), 11407 getLangOpts().CPlusPlus11 11408 ? diag::warn_cxx98_compat_using_decl_constructor 11409 : diag::err_using_decl_constructor) 11410 << SS.getRange(); 11411 11412 if (getLangOpts().CPlusPlus11) break; 11413 11414 return nullptr; 11415 11416 case UnqualifiedIdKind::IK_DestructorName: 11417 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange(); 11418 return nullptr; 11419 11420 case UnqualifiedIdKind::IK_TemplateId: 11421 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id) 11422 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 11423 return nullptr; 11424 11425 case UnqualifiedIdKind::IK_DeductionGuideName: 11426 llvm_unreachable("cannot parse qualified deduction guide name"); 11427 } 11428 11429 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 11430 DeclarationName TargetName = TargetNameInfo.getName(); 11431 if (!TargetName) 11432 return nullptr; 11433 11434 // Warn about access declarations. 11435 if (UsingLoc.isInvalid()) { 11436 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11 11437 ? diag::err_access_decl 11438 : diag::warn_access_decl_deprecated) 11439 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 11440 } 11441 11442 if (EllipsisLoc.isInvalid()) { 11443 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 11444 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 11445 return nullptr; 11446 } else { 11447 if (!SS.getScopeRep()->containsUnexpandedParameterPack() && 11448 !TargetNameInfo.containsUnexpandedParameterPack()) { 11449 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 11450 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc()); 11451 EllipsisLoc = SourceLocation(); 11452 } 11453 } 11454 11455 NamedDecl *UD = 11456 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc, 11457 SS, TargetNameInfo, EllipsisLoc, AttrList, 11458 /*IsInstantiation*/false); 11459 if (UD) 11460 PushOnScopeChains(UD, S, /*AddToContext*/ false); 11461 11462 return UD; 11463 } 11464 11465 /// Determine whether a using declaration considers the given 11466 /// declarations as "equivalent", e.g., if they are redeclarations of 11467 /// the same entity or are both typedefs of the same type. 11468 static bool 11469 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 11470 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 11471 return true; 11472 11473 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 11474 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 11475 return Context.hasSameType(TD1->getUnderlyingType(), 11476 TD2->getUnderlyingType()); 11477 11478 return false; 11479 } 11480 11481 11482 /// Determines whether to create a using shadow decl for a particular 11483 /// decl, given the set of decls existing prior to this using lookup. 11484 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 11485 const LookupResult &Previous, 11486 UsingShadowDecl *&PrevShadow) { 11487 // Diagnose finding a decl which is not from a base class of the 11488 // current class. We do this now because there are cases where this 11489 // function will silently decide not to build a shadow decl, which 11490 // will pre-empt further diagnostics. 11491 // 11492 // We don't need to do this in C++11 because we do the check once on 11493 // the qualifier. 11494 // 11495 // FIXME: diagnose the following if we care enough: 11496 // struct A { int foo; }; 11497 // struct B : A { using A::foo; }; 11498 // template <class T> struct C : A {}; 11499 // template <class T> struct D : C<T> { using B::foo; } // <--- 11500 // This is invalid (during instantiation) in C++03 because B::foo 11501 // resolves to the using decl in B, which is not a base class of D<T>. 11502 // We can't diagnose it immediately because C<T> is an unknown 11503 // specialization. The UsingShadowDecl in D<T> then points directly 11504 // to A::foo, which will look well-formed when we instantiate. 11505 // The right solution is to not collapse the shadow-decl chain. 11506 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 11507 DeclContext *OrigDC = Orig->getDeclContext(); 11508 11509 // Handle enums and anonymous structs. 11510 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 11511 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 11512 while (OrigRec->isAnonymousStructOrUnion()) 11513 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 11514 11515 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 11516 if (OrigDC == CurContext) { 11517 Diag(Using->getLocation(), 11518 diag::err_using_decl_nested_name_specifier_is_current_class) 11519 << Using->getQualifierLoc().getSourceRange(); 11520 Diag(Orig->getLocation(), diag::note_using_decl_target); 11521 Using->setInvalidDecl(); 11522 return true; 11523 } 11524 11525 Diag(Using->getQualifierLoc().getBeginLoc(), 11526 diag::err_using_decl_nested_name_specifier_is_not_base_class) 11527 << Using->getQualifier() 11528 << cast<CXXRecordDecl>(CurContext) 11529 << Using->getQualifierLoc().getSourceRange(); 11530 Diag(Orig->getLocation(), diag::note_using_decl_target); 11531 Using->setInvalidDecl(); 11532 return true; 11533 } 11534 } 11535 11536 if (Previous.empty()) return false; 11537 11538 NamedDecl *Target = Orig; 11539 if (isa<UsingShadowDecl>(Target)) 11540 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 11541 11542 // If the target happens to be one of the previous declarations, we 11543 // don't have a conflict. 11544 // 11545 // FIXME: but we might be increasing its access, in which case we 11546 // should redeclare it. 11547 NamedDecl *NonTag = nullptr, *Tag = nullptr; 11548 bool FoundEquivalentDecl = false; 11549 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 11550 I != E; ++I) { 11551 NamedDecl *D = (*I)->getUnderlyingDecl(); 11552 // We can have UsingDecls in our Previous results because we use the same 11553 // LookupResult for checking whether the UsingDecl itself is a valid 11554 // redeclaration. 11555 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D)) 11556 continue; 11557 11558 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 11559 // C++ [class.mem]p19: 11560 // If T is the name of a class, then [every named member other than 11561 // a non-static data member] shall have a name different from T 11562 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) && 11563 !isa<IndirectFieldDecl>(Target) && 11564 !isa<UnresolvedUsingValueDecl>(Target) && 11565 DiagnoseClassNameShadow( 11566 CurContext, 11567 DeclarationNameInfo(Using->getDeclName(), Using->getLocation()))) 11568 return true; 11569 } 11570 11571 if (IsEquivalentForUsingDecl(Context, D, Target)) { 11572 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 11573 PrevShadow = Shadow; 11574 FoundEquivalentDecl = true; 11575 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) { 11576 // We don't conflict with an existing using shadow decl of an equivalent 11577 // declaration, but we're not a redeclaration of it. 11578 FoundEquivalentDecl = true; 11579 } 11580 11581 if (isVisible(D)) 11582 (isa<TagDecl>(D) ? Tag : NonTag) = D; 11583 } 11584 11585 if (FoundEquivalentDecl) 11586 return false; 11587 11588 if (FunctionDecl *FD = Target->getAsFunction()) { 11589 NamedDecl *OldDecl = nullptr; 11590 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 11591 /*IsForUsingDecl*/ true)) { 11592 case Ovl_Overload: 11593 return false; 11594 11595 case Ovl_NonFunction: 11596 Diag(Using->getLocation(), diag::err_using_decl_conflict); 11597 break; 11598 11599 // We found a decl with the exact signature. 11600 case Ovl_Match: 11601 // If we're in a record, we want to hide the target, so we 11602 // return true (without a diagnostic) to tell the caller not to 11603 // build a shadow decl. 11604 if (CurContext->isRecord()) 11605 return true; 11606 11607 // If we're not in a record, this is an error. 11608 Diag(Using->getLocation(), diag::err_using_decl_conflict); 11609 break; 11610 } 11611 11612 Diag(Target->getLocation(), diag::note_using_decl_target); 11613 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 11614 Using->setInvalidDecl(); 11615 return true; 11616 } 11617 11618 // Target is not a function. 11619 11620 if (isa<TagDecl>(Target)) { 11621 // No conflict between a tag and a non-tag. 11622 if (!Tag) return false; 11623 11624 Diag(Using->getLocation(), diag::err_using_decl_conflict); 11625 Diag(Target->getLocation(), diag::note_using_decl_target); 11626 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 11627 Using->setInvalidDecl(); 11628 return true; 11629 } 11630 11631 // No conflict between a tag and a non-tag. 11632 if (!NonTag) return false; 11633 11634 Diag(Using->getLocation(), diag::err_using_decl_conflict); 11635 Diag(Target->getLocation(), diag::note_using_decl_target); 11636 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 11637 Using->setInvalidDecl(); 11638 return true; 11639 } 11640 11641 /// Determine whether a direct base class is a virtual base class. 11642 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) { 11643 if (!Derived->getNumVBases()) 11644 return false; 11645 for (auto &B : Derived->bases()) 11646 if (B.getType()->getAsCXXRecordDecl() == Base) 11647 return B.isVirtual(); 11648 llvm_unreachable("not a direct base class"); 11649 } 11650 11651 /// Builds a shadow declaration corresponding to a 'using' declaration. 11652 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 11653 UsingDecl *UD, 11654 NamedDecl *Orig, 11655 UsingShadowDecl *PrevDecl) { 11656 // If we resolved to another shadow declaration, just coalesce them. 11657 NamedDecl *Target = Orig; 11658 if (isa<UsingShadowDecl>(Target)) { 11659 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 11660 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 11661 } 11662 11663 NamedDecl *NonTemplateTarget = Target; 11664 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target)) 11665 NonTemplateTarget = TargetTD->getTemplatedDecl(); 11666 11667 UsingShadowDecl *Shadow; 11668 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) { 11669 bool IsVirtualBase = 11670 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext), 11671 UD->getQualifier()->getAsRecordDecl()); 11672 Shadow = ConstructorUsingShadowDecl::Create( 11673 Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase); 11674 } else { 11675 Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD, 11676 Target); 11677 } 11678 UD->addShadowDecl(Shadow); 11679 11680 Shadow->setAccess(UD->getAccess()); 11681 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 11682 Shadow->setInvalidDecl(); 11683 11684 Shadow->setPreviousDecl(PrevDecl); 11685 11686 if (S) 11687 PushOnScopeChains(Shadow, S); 11688 else 11689 CurContext->addDecl(Shadow); 11690 11691 11692 return Shadow; 11693 } 11694 11695 /// Hides a using shadow declaration. This is required by the current 11696 /// using-decl implementation when a resolvable using declaration in a 11697 /// class is followed by a declaration which would hide or override 11698 /// one or more of the using decl's targets; for example: 11699 /// 11700 /// struct Base { void foo(int); }; 11701 /// struct Derived : Base { 11702 /// using Base::foo; 11703 /// void foo(int); 11704 /// }; 11705 /// 11706 /// The governing language is C++03 [namespace.udecl]p12: 11707 /// 11708 /// When a using-declaration brings names from a base class into a 11709 /// derived class scope, member functions in the derived class 11710 /// override and/or hide member functions with the same name and 11711 /// parameter types in a base class (rather than conflicting). 11712 /// 11713 /// There are two ways to implement this: 11714 /// (1) optimistically create shadow decls when they're not hidden 11715 /// by existing declarations, or 11716 /// (2) don't create any shadow decls (or at least don't make them 11717 /// visible) until we've fully parsed/instantiated the class. 11718 /// The problem with (1) is that we might have to retroactively remove 11719 /// a shadow decl, which requires several O(n) operations because the 11720 /// decl structures are (very reasonably) not designed for removal. 11721 /// (2) avoids this but is very fiddly and phase-dependent. 11722 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 11723 if (Shadow->getDeclName().getNameKind() == 11724 DeclarationName::CXXConversionFunctionName) 11725 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 11726 11727 // Remove it from the DeclContext... 11728 Shadow->getDeclContext()->removeDecl(Shadow); 11729 11730 // ...and the scope, if applicable... 11731 if (S) { 11732 S->RemoveDecl(Shadow); 11733 IdResolver.RemoveDecl(Shadow); 11734 } 11735 11736 // ...and the using decl. 11737 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 11738 11739 // TODO: complain somehow if Shadow was used. It shouldn't 11740 // be possible for this to happen, because...? 11741 } 11742 11743 /// Find the base specifier for a base class with the given type. 11744 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 11745 QualType DesiredBase, 11746 bool &AnyDependentBases) { 11747 // Check whether the named type is a direct base class. 11748 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified() 11749 .getUnqualifiedType(); 11750 for (auto &Base : Derived->bases()) { 11751 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 11752 if (CanonicalDesiredBase == BaseType) 11753 return &Base; 11754 if (BaseType->isDependentType()) 11755 AnyDependentBases = true; 11756 } 11757 return nullptr; 11758 } 11759 11760 namespace { 11761 class UsingValidatorCCC final : public CorrectionCandidateCallback { 11762 public: 11763 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 11764 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 11765 : HasTypenameKeyword(HasTypenameKeyword), 11766 IsInstantiation(IsInstantiation), OldNNS(NNS), 11767 RequireMemberOf(RequireMemberOf) {} 11768 11769 bool ValidateCandidate(const TypoCorrection &Candidate) override { 11770 NamedDecl *ND = Candidate.getCorrectionDecl(); 11771 11772 // Keywords are not valid here. 11773 if (!ND || isa<NamespaceDecl>(ND)) 11774 return false; 11775 11776 // Completely unqualified names are invalid for a 'using' declaration. 11777 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 11778 return false; 11779 11780 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would 11781 // reject. 11782 11783 if (RequireMemberOf) { 11784 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 11785 if (FoundRecord && FoundRecord->isInjectedClassName()) { 11786 // No-one ever wants a using-declaration to name an injected-class-name 11787 // of a base class, unless they're declaring an inheriting constructor. 11788 ASTContext &Ctx = ND->getASTContext(); 11789 if (!Ctx.getLangOpts().CPlusPlus11) 11790 return false; 11791 QualType FoundType = Ctx.getRecordType(FoundRecord); 11792 11793 // Check that the injected-class-name is named as a member of its own 11794 // type; we don't want to suggest 'using Derived::Base;', since that 11795 // means something else. 11796 NestedNameSpecifier *Specifier = 11797 Candidate.WillReplaceSpecifier() 11798 ? Candidate.getCorrectionSpecifier() 11799 : OldNNS; 11800 if (!Specifier->getAsType() || 11801 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 11802 return false; 11803 11804 // Check that this inheriting constructor declaration actually names a 11805 // direct base class of the current class. 11806 bool AnyDependentBases = false; 11807 if (!findDirectBaseWithType(RequireMemberOf, 11808 Ctx.getRecordType(FoundRecord), 11809 AnyDependentBases) && 11810 !AnyDependentBases) 11811 return false; 11812 } else { 11813 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 11814 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 11815 return false; 11816 11817 // FIXME: Check that the base class member is accessible? 11818 } 11819 } else { 11820 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 11821 if (FoundRecord && FoundRecord->isInjectedClassName()) 11822 return false; 11823 } 11824 11825 if (isa<TypeDecl>(ND)) 11826 return HasTypenameKeyword || !IsInstantiation; 11827 11828 return !HasTypenameKeyword; 11829 } 11830 11831 std::unique_ptr<CorrectionCandidateCallback> clone() override { 11832 return std::make_unique<UsingValidatorCCC>(*this); 11833 } 11834 11835 private: 11836 bool HasTypenameKeyword; 11837 bool IsInstantiation; 11838 NestedNameSpecifier *OldNNS; 11839 CXXRecordDecl *RequireMemberOf; 11840 }; 11841 } // end anonymous namespace 11842 11843 /// Builds a using declaration. 11844 /// 11845 /// \param IsInstantiation - Whether this call arises from an 11846 /// instantiation of an unresolved using declaration. We treat 11847 /// the lookup differently for these declarations. 11848 NamedDecl *Sema::BuildUsingDeclaration( 11849 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, 11850 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, 11851 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, 11852 const ParsedAttributesView &AttrList, bool IsInstantiation) { 11853 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 11854 SourceLocation IdentLoc = NameInfo.getLoc(); 11855 assert(IdentLoc.isValid() && "Invalid TargetName location."); 11856 11857 // FIXME: We ignore attributes for now. 11858 11859 // For an inheriting constructor declaration, the name of the using 11860 // declaration is the name of a constructor in this class, not in the 11861 // base class. 11862 DeclarationNameInfo UsingName = NameInfo; 11863 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName) 11864 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext)) 11865 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 11866 Context.getCanonicalType(Context.getRecordType(RD)))); 11867 11868 // Do the redeclaration lookup in the current scope. 11869 LookupResult Previous(*this, UsingName, LookupUsingDeclName, 11870 ForVisibleRedeclaration); 11871 Previous.setHideTags(false); 11872 if (S) { 11873 LookupName(Previous, S); 11874 11875 // It is really dumb that we have to do this. 11876 LookupResult::Filter F = Previous.makeFilter(); 11877 while (F.hasNext()) { 11878 NamedDecl *D = F.next(); 11879 if (!isDeclInScope(D, CurContext, S)) 11880 F.erase(); 11881 // If we found a local extern declaration that's not ordinarily visible, 11882 // and this declaration is being added to a non-block scope, ignore it. 11883 // We're only checking for scope conflicts here, not also for violations 11884 // of the linkage rules. 11885 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 11886 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 11887 F.erase(); 11888 } 11889 F.done(); 11890 } else { 11891 assert(IsInstantiation && "no scope in non-instantiation"); 11892 if (CurContext->isRecord()) 11893 LookupQualifiedName(Previous, CurContext); 11894 else { 11895 // No redeclaration check is needed here; in non-member contexts we 11896 // diagnosed all possible conflicts with other using-declarations when 11897 // building the template: 11898 // 11899 // For a dependent non-type using declaration, the only valid case is 11900 // if we instantiate to a single enumerator. We check for conflicts 11901 // between shadow declarations we introduce, and we check in the template 11902 // definition for conflicts between a non-type using declaration and any 11903 // other declaration, which together covers all cases. 11904 // 11905 // A dependent typename using declaration will never successfully 11906 // instantiate, since it will always name a class member, so we reject 11907 // that in the template definition. 11908 } 11909 } 11910 11911 // Check for invalid redeclarations. 11912 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 11913 SS, IdentLoc, Previous)) 11914 return nullptr; 11915 11916 // Check for bad qualifiers. 11917 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo, 11918 IdentLoc)) 11919 return nullptr; 11920 11921 DeclContext *LookupContext = computeDeclContext(SS); 11922 NamedDecl *D; 11923 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 11924 if (!LookupContext || EllipsisLoc.isValid()) { 11925 if (HasTypenameKeyword) { 11926 // FIXME: not all declaration name kinds are legal here 11927 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 11928 UsingLoc, TypenameLoc, 11929 QualifierLoc, 11930 IdentLoc, NameInfo.getName(), 11931 EllipsisLoc); 11932 } else { 11933 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 11934 QualifierLoc, NameInfo, EllipsisLoc); 11935 } 11936 D->setAccess(AS); 11937 CurContext->addDecl(D); 11938 return D; 11939 } 11940 11941 auto Build = [&](bool Invalid) { 11942 UsingDecl *UD = 11943 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 11944 UsingName, HasTypenameKeyword); 11945 UD->setAccess(AS); 11946 CurContext->addDecl(UD); 11947 UD->setInvalidDecl(Invalid); 11948 return UD; 11949 }; 11950 auto BuildInvalid = [&]{ return Build(true); }; 11951 auto BuildValid = [&]{ return Build(false); }; 11952 11953 if (RequireCompleteDeclContext(SS, LookupContext)) 11954 return BuildInvalid(); 11955 11956 // Look up the target name. 11957 LookupResult R(*this, NameInfo, LookupOrdinaryName); 11958 11959 // Unlike most lookups, we don't always want to hide tag 11960 // declarations: tag names are visible through the using declaration 11961 // even if hidden by ordinary names, *except* in a dependent context 11962 // where it's important for the sanity of two-phase lookup. 11963 if (!IsInstantiation) 11964 R.setHideTags(false); 11965 11966 // For the purposes of this lookup, we have a base object type 11967 // equal to that of the current context. 11968 if (CurContext->isRecord()) { 11969 R.setBaseObjectType( 11970 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 11971 } 11972 11973 LookupQualifiedName(R, LookupContext); 11974 11975 // Try to correct typos if possible. If constructor name lookup finds no 11976 // results, that means the named class has no explicit constructors, and we 11977 // suppressed declaring implicit ones (probably because it's dependent or 11978 // invalid). 11979 if (R.empty() && 11980 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { 11981 // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes 11982 // it will believe that glibc provides a ::gets in cases where it does not, 11983 // and will try to pull it into namespace std with a using-declaration. 11984 // Just ignore the using-declaration in that case. 11985 auto *II = NameInfo.getName().getAsIdentifierInfo(); 11986 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") && 11987 CurContext->isStdNamespace() && 11988 isa<TranslationUnitDecl>(LookupContext) && 11989 getSourceManager().isInSystemHeader(UsingLoc)) 11990 return nullptr; 11991 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 11992 dyn_cast<CXXRecordDecl>(CurContext)); 11993 if (TypoCorrection Corrected = 11994 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 11995 CTK_ErrorRecovery)) { 11996 // We reject candidates where DroppedSpecifier == true, hence the 11997 // literal '0' below. 11998 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 11999 << NameInfo.getName() << LookupContext << 0 12000 << SS.getRange()); 12001 12002 // If we picked a correction with no attached Decl we can't do anything 12003 // useful with it, bail out. 12004 NamedDecl *ND = Corrected.getCorrectionDecl(); 12005 if (!ND) 12006 return BuildInvalid(); 12007 12008 // If we corrected to an inheriting constructor, handle it as one. 12009 auto *RD = dyn_cast<CXXRecordDecl>(ND); 12010 if (RD && RD->isInjectedClassName()) { 12011 // The parent of the injected class name is the class itself. 12012 RD = cast<CXXRecordDecl>(RD->getParent()); 12013 12014 // Fix up the information we'll use to build the using declaration. 12015 if (Corrected.WillReplaceSpecifier()) { 12016 NestedNameSpecifierLocBuilder Builder; 12017 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 12018 QualifierLoc.getSourceRange()); 12019 QualifierLoc = Builder.getWithLocInContext(Context); 12020 } 12021 12022 // In this case, the name we introduce is the name of a derived class 12023 // constructor. 12024 auto *CurClass = cast<CXXRecordDecl>(CurContext); 12025 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 12026 Context.getCanonicalType(Context.getRecordType(CurClass)))); 12027 UsingName.setNamedTypeInfo(nullptr); 12028 for (auto *Ctor : LookupConstructors(RD)) 12029 R.addDecl(Ctor); 12030 R.resolveKind(); 12031 } else { 12032 // FIXME: Pick up all the declarations if we found an overloaded 12033 // function. 12034 UsingName.setName(ND->getDeclName()); 12035 R.addDecl(ND); 12036 } 12037 } else { 12038 Diag(IdentLoc, diag::err_no_member) 12039 << NameInfo.getName() << LookupContext << SS.getRange(); 12040 return BuildInvalid(); 12041 } 12042 } 12043 12044 if (R.isAmbiguous()) 12045 return BuildInvalid(); 12046 12047 if (HasTypenameKeyword) { 12048 // If we asked for a typename and got a non-type decl, error out. 12049 if (!R.getAsSingle<TypeDecl>()) { 12050 Diag(IdentLoc, diag::err_using_typename_non_type); 12051 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 12052 Diag((*I)->getUnderlyingDecl()->getLocation(), 12053 diag::note_using_decl_target); 12054 return BuildInvalid(); 12055 } 12056 } else { 12057 // If we asked for a non-typename and we got a type, error out, 12058 // but only if this is an instantiation of an unresolved using 12059 // decl. Otherwise just silently find the type name. 12060 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 12061 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 12062 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 12063 return BuildInvalid(); 12064 } 12065 } 12066 12067 // C++14 [namespace.udecl]p6: 12068 // A using-declaration shall not name a namespace. 12069 if (R.getAsSingle<NamespaceDecl>()) { 12070 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 12071 << SS.getRange(); 12072 return BuildInvalid(); 12073 } 12074 12075 // C++14 [namespace.udecl]p7: 12076 // A using-declaration shall not name a scoped enumerator. 12077 if (auto *ED = R.getAsSingle<EnumConstantDecl>()) { 12078 if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) { 12079 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum) 12080 << SS.getRange(); 12081 return BuildInvalid(); 12082 } 12083 } 12084 12085 UsingDecl *UD = BuildValid(); 12086 12087 // Some additional rules apply to inheriting constructors. 12088 if (UsingName.getName().getNameKind() == 12089 DeclarationName::CXXConstructorName) { 12090 // Suppress access diagnostics; the access check is instead performed at the 12091 // point of use for an inheriting constructor. 12092 R.suppressDiagnostics(); 12093 if (CheckInheritingConstructorUsingDecl(UD)) 12094 return UD; 12095 } 12096 12097 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 12098 UsingShadowDecl *PrevDecl = nullptr; 12099 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 12100 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 12101 } 12102 12103 return UD; 12104 } 12105 12106 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom, 12107 ArrayRef<NamedDecl *> Expansions) { 12108 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || 12109 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || 12110 isa<UsingPackDecl>(InstantiatedFrom)); 12111 12112 auto *UPD = 12113 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions); 12114 UPD->setAccess(InstantiatedFrom->getAccess()); 12115 CurContext->addDecl(UPD); 12116 return UPD; 12117 } 12118 12119 /// Additional checks for a using declaration referring to a constructor name. 12120 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 12121 assert(!UD->hasTypename() && "expecting a constructor name"); 12122 12123 const Type *SourceType = UD->getQualifier()->getAsType(); 12124 assert(SourceType && 12125 "Using decl naming constructor doesn't have type in scope spec."); 12126 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 12127 12128 // Check whether the named type is a direct base class. 12129 bool AnyDependentBases = false; 12130 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 12131 AnyDependentBases); 12132 if (!Base && !AnyDependentBases) { 12133 Diag(UD->getUsingLoc(), 12134 diag::err_using_decl_constructor_not_in_direct_base) 12135 << UD->getNameInfo().getSourceRange() 12136 << QualType(SourceType, 0) << TargetClass; 12137 UD->setInvalidDecl(); 12138 return true; 12139 } 12140 12141 if (Base) 12142 Base->setInheritConstructors(); 12143 12144 return false; 12145 } 12146 12147 /// Checks that the given using declaration is not an invalid 12148 /// redeclaration. Note that this is checking only for the using decl 12149 /// itself, not for any ill-formedness among the UsingShadowDecls. 12150 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 12151 bool HasTypenameKeyword, 12152 const CXXScopeSpec &SS, 12153 SourceLocation NameLoc, 12154 const LookupResult &Prev) { 12155 NestedNameSpecifier *Qual = SS.getScopeRep(); 12156 12157 // C++03 [namespace.udecl]p8: 12158 // C++0x [namespace.udecl]p10: 12159 // A using-declaration is a declaration and can therefore be used 12160 // repeatedly where (and only where) multiple declarations are 12161 // allowed. 12162 // 12163 // That's in non-member contexts. 12164 if (!CurContext->getRedeclContext()->isRecord()) { 12165 // A dependent qualifier outside a class can only ever resolve to an 12166 // enumeration type. Therefore it conflicts with any other non-type 12167 // declaration in the same scope. 12168 // FIXME: How should we check for dependent type-type conflicts at block 12169 // scope? 12170 if (Qual->isDependent() && !HasTypenameKeyword) { 12171 for (auto *D : Prev) { 12172 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) { 12173 bool OldCouldBeEnumerator = 12174 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D); 12175 Diag(NameLoc, 12176 OldCouldBeEnumerator ? diag::err_redefinition 12177 : diag::err_redefinition_different_kind) 12178 << Prev.getLookupName(); 12179 Diag(D->getLocation(), diag::note_previous_definition); 12180 return true; 12181 } 12182 } 12183 } 12184 return false; 12185 } 12186 12187 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 12188 NamedDecl *D = *I; 12189 12190 bool DTypename; 12191 NestedNameSpecifier *DQual; 12192 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 12193 DTypename = UD->hasTypename(); 12194 DQual = UD->getQualifier(); 12195 } else if (UnresolvedUsingValueDecl *UD 12196 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 12197 DTypename = false; 12198 DQual = UD->getQualifier(); 12199 } else if (UnresolvedUsingTypenameDecl *UD 12200 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 12201 DTypename = true; 12202 DQual = UD->getQualifier(); 12203 } else continue; 12204 12205 // using decls differ if one says 'typename' and the other doesn't. 12206 // FIXME: non-dependent using decls? 12207 if (HasTypenameKeyword != DTypename) continue; 12208 12209 // using decls differ if they name different scopes (but note that 12210 // template instantiation can cause this check to trigger when it 12211 // didn't before instantiation). 12212 if (Context.getCanonicalNestedNameSpecifier(Qual) != 12213 Context.getCanonicalNestedNameSpecifier(DQual)) 12214 continue; 12215 12216 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 12217 Diag(D->getLocation(), diag::note_using_decl) << 1; 12218 return true; 12219 } 12220 12221 return false; 12222 } 12223 12224 12225 /// Checks that the given nested-name qualifier used in a using decl 12226 /// in the current context is appropriately related to the current 12227 /// scope. If an error is found, diagnoses it and returns true. 12228 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 12229 bool HasTypename, 12230 const CXXScopeSpec &SS, 12231 const DeclarationNameInfo &NameInfo, 12232 SourceLocation NameLoc) { 12233 DeclContext *NamedContext = computeDeclContext(SS); 12234 12235 if (!CurContext->isRecord()) { 12236 // C++03 [namespace.udecl]p3: 12237 // C++0x [namespace.udecl]p8: 12238 // A using-declaration for a class member shall be a member-declaration. 12239 12240 // If we weren't able to compute a valid scope, it might validly be a 12241 // dependent class scope or a dependent enumeration unscoped scope. If 12242 // we have a 'typename' keyword, the scope must resolve to a class type. 12243 if ((HasTypename && !NamedContext) || 12244 (NamedContext && NamedContext->getRedeclContext()->isRecord())) { 12245 auto *RD = NamedContext 12246 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext()) 12247 : nullptr; 12248 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) 12249 RD = nullptr; 12250 12251 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 12252 << SS.getRange(); 12253 12254 // If we have a complete, non-dependent source type, try to suggest a 12255 // way to get the same effect. 12256 if (!RD) 12257 return true; 12258 12259 // Find what this using-declaration was referring to. 12260 LookupResult R(*this, NameInfo, LookupOrdinaryName); 12261 R.setHideTags(false); 12262 R.suppressDiagnostics(); 12263 LookupQualifiedName(R, RD); 12264 12265 if (R.getAsSingle<TypeDecl>()) { 12266 if (getLangOpts().CPlusPlus11) { 12267 // Convert 'using X::Y;' to 'using Y = X::Y;'. 12268 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 12269 << 0 // alias declaration 12270 << FixItHint::CreateInsertion(SS.getBeginLoc(), 12271 NameInfo.getName().getAsString() + 12272 " = "); 12273 } else { 12274 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 12275 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc()); 12276 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 12277 << 1 // typedef declaration 12278 << FixItHint::CreateReplacement(UsingLoc, "typedef") 12279 << FixItHint::CreateInsertion( 12280 InsertLoc, " " + NameInfo.getName().getAsString()); 12281 } 12282 } else if (R.getAsSingle<VarDecl>()) { 12283 // Don't provide a fixit outside C++11 mode; we don't want to suggest 12284 // repeating the type of the static data member here. 12285 FixItHint FixIt; 12286 if (getLangOpts().CPlusPlus11) { 12287 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 12288 FixIt = FixItHint::CreateReplacement( 12289 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 12290 } 12291 12292 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 12293 << 2 // reference declaration 12294 << FixIt; 12295 } else if (R.getAsSingle<EnumConstantDecl>()) { 12296 // Don't provide a fixit outside C++11 mode; we don't want to suggest 12297 // repeating the type of the enumeration here, and we can't do so if 12298 // the type is anonymous. 12299 FixItHint FixIt; 12300 if (getLangOpts().CPlusPlus11) { 12301 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 12302 FixIt = FixItHint::CreateReplacement( 12303 UsingLoc, 12304 "constexpr auto " + NameInfo.getName().getAsString() + " = "); 12305 } 12306 12307 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 12308 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable 12309 << FixIt; 12310 } 12311 return true; 12312 } 12313 12314 // Otherwise, this might be valid. 12315 return false; 12316 } 12317 12318 // The current scope is a record. 12319 12320 // If the named context is dependent, we can't decide much. 12321 if (!NamedContext) { 12322 // FIXME: in C++0x, we can diagnose if we can prove that the 12323 // nested-name-specifier does not refer to a base class, which is 12324 // still possible in some cases. 12325 12326 // Otherwise we have to conservatively report that things might be 12327 // okay. 12328 return false; 12329 } 12330 12331 if (!NamedContext->isRecord()) { 12332 // Ideally this would point at the last name in the specifier, 12333 // but we don't have that level of source info. 12334 Diag(SS.getRange().getBegin(), 12335 diag::err_using_decl_nested_name_specifier_is_not_class) 12336 << SS.getScopeRep() << SS.getRange(); 12337 return true; 12338 } 12339 12340 if (!NamedContext->isDependentContext() && 12341 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 12342 return true; 12343 12344 if (getLangOpts().CPlusPlus11) { 12345 // C++11 [namespace.udecl]p3: 12346 // In a using-declaration used as a member-declaration, the 12347 // nested-name-specifier shall name a base class of the class 12348 // being defined. 12349 12350 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 12351 cast<CXXRecordDecl>(NamedContext))) { 12352 if (CurContext == NamedContext) { 12353 Diag(NameLoc, 12354 diag::err_using_decl_nested_name_specifier_is_current_class) 12355 << SS.getRange(); 12356 return true; 12357 } 12358 12359 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) { 12360 Diag(SS.getRange().getBegin(), 12361 diag::err_using_decl_nested_name_specifier_is_not_base_class) 12362 << SS.getScopeRep() 12363 << cast<CXXRecordDecl>(CurContext) 12364 << SS.getRange(); 12365 } 12366 return true; 12367 } 12368 12369 return false; 12370 } 12371 12372 // C++03 [namespace.udecl]p4: 12373 // A using-declaration used as a member-declaration shall refer 12374 // to a member of a base class of the class being defined [etc.]. 12375 12376 // Salient point: SS doesn't have to name a base class as long as 12377 // lookup only finds members from base classes. Therefore we can 12378 // diagnose here only if we can prove that that can't happen, 12379 // i.e. if the class hierarchies provably don't intersect. 12380 12381 // TODO: it would be nice if "definitely valid" results were cached 12382 // in the UsingDecl and UsingShadowDecl so that these checks didn't 12383 // need to be repeated. 12384 12385 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases; 12386 auto Collect = [&Bases](const CXXRecordDecl *Base) { 12387 Bases.insert(Base); 12388 return true; 12389 }; 12390 12391 // Collect all bases. Return false if we find a dependent base. 12392 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect)) 12393 return false; 12394 12395 // Returns true if the base is dependent or is one of the accumulated base 12396 // classes. 12397 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) { 12398 return !Bases.count(Base); 12399 }; 12400 12401 // Return false if the class has a dependent base or if it or one 12402 // of its bases is present in the base set of the current context. 12403 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) || 12404 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase)) 12405 return false; 12406 12407 Diag(SS.getRange().getBegin(), 12408 diag::err_using_decl_nested_name_specifier_is_not_base_class) 12409 << SS.getScopeRep() 12410 << cast<CXXRecordDecl>(CurContext) 12411 << SS.getRange(); 12412 12413 return true; 12414 } 12415 12416 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS, 12417 MultiTemplateParamsArg TemplateParamLists, 12418 SourceLocation UsingLoc, UnqualifiedId &Name, 12419 const ParsedAttributesView &AttrList, 12420 TypeResult Type, Decl *DeclFromDeclSpec) { 12421 // Skip up to the relevant declaration scope. 12422 while (S->isTemplateParamScope()) 12423 S = S->getParent(); 12424 assert((S->getFlags() & Scope::DeclScope) && 12425 "got alias-declaration outside of declaration scope"); 12426 12427 if (Type.isInvalid()) 12428 return nullptr; 12429 12430 bool Invalid = false; 12431 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 12432 TypeSourceInfo *TInfo = nullptr; 12433 GetTypeFromParser(Type.get(), &TInfo); 12434 12435 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 12436 return nullptr; 12437 12438 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 12439 UPPC_DeclarationType)) { 12440 Invalid = true; 12441 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 12442 TInfo->getTypeLoc().getBeginLoc()); 12443 } 12444 12445 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 12446 TemplateParamLists.size() 12447 ? forRedeclarationInCurContext() 12448 : ForVisibleRedeclaration); 12449 LookupName(Previous, S); 12450 12451 // Warn about shadowing the name of a template parameter. 12452 if (Previous.isSingleResult() && 12453 Previous.getFoundDecl()->isTemplateParameter()) { 12454 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 12455 Previous.clear(); 12456 } 12457 12458 assert(Name.Kind == UnqualifiedIdKind::IK_Identifier && 12459 "name in alias declaration must be an identifier"); 12460 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 12461 Name.StartLocation, 12462 Name.Identifier, TInfo); 12463 12464 NewTD->setAccess(AS); 12465 12466 if (Invalid) 12467 NewTD->setInvalidDecl(); 12468 12469 ProcessDeclAttributeList(S, NewTD, AttrList); 12470 AddPragmaAttributes(S, NewTD); 12471 12472 CheckTypedefForVariablyModifiedType(S, NewTD); 12473 Invalid |= NewTD->isInvalidDecl(); 12474 12475 bool Redeclaration = false; 12476 12477 NamedDecl *NewND; 12478 if (TemplateParamLists.size()) { 12479 TypeAliasTemplateDecl *OldDecl = nullptr; 12480 TemplateParameterList *OldTemplateParams = nullptr; 12481 12482 if (TemplateParamLists.size() != 1) { 12483 Diag(UsingLoc, diag::err_alias_template_extra_headers) 12484 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 12485 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 12486 } 12487 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 12488 12489 // Check that we can declare a template here. 12490 if (CheckTemplateDeclScope(S, TemplateParams)) 12491 return nullptr; 12492 12493 // Only consider previous declarations in the same scope. 12494 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 12495 /*ExplicitInstantiationOrSpecialization*/false); 12496 if (!Previous.empty()) { 12497 Redeclaration = true; 12498 12499 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 12500 if (!OldDecl && !Invalid) { 12501 Diag(UsingLoc, diag::err_redefinition_different_kind) 12502 << Name.Identifier; 12503 12504 NamedDecl *OldD = Previous.getRepresentativeDecl(); 12505 if (OldD->getLocation().isValid()) 12506 Diag(OldD->getLocation(), diag::note_previous_definition); 12507 12508 Invalid = true; 12509 } 12510 12511 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 12512 if (TemplateParameterListsAreEqual(TemplateParams, 12513 OldDecl->getTemplateParameters(), 12514 /*Complain=*/true, 12515 TPL_TemplateMatch)) 12516 OldTemplateParams = 12517 OldDecl->getMostRecentDecl()->getTemplateParameters(); 12518 else 12519 Invalid = true; 12520 12521 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 12522 if (!Invalid && 12523 !Context.hasSameType(OldTD->getUnderlyingType(), 12524 NewTD->getUnderlyingType())) { 12525 // FIXME: The C++0x standard does not clearly say this is ill-formed, 12526 // but we can't reasonably accept it. 12527 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 12528 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 12529 if (OldTD->getLocation().isValid()) 12530 Diag(OldTD->getLocation(), diag::note_previous_definition); 12531 Invalid = true; 12532 } 12533 } 12534 } 12535 12536 // Merge any previous default template arguments into our parameters, 12537 // and check the parameter list. 12538 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 12539 TPC_TypeAliasTemplate)) 12540 return nullptr; 12541 12542 TypeAliasTemplateDecl *NewDecl = 12543 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 12544 Name.Identifier, TemplateParams, 12545 NewTD); 12546 NewTD->setDescribedAliasTemplate(NewDecl); 12547 12548 NewDecl->setAccess(AS); 12549 12550 if (Invalid) 12551 NewDecl->setInvalidDecl(); 12552 else if (OldDecl) { 12553 NewDecl->setPreviousDecl(OldDecl); 12554 CheckRedeclarationModuleOwnership(NewDecl, OldDecl); 12555 } 12556 12557 NewND = NewDecl; 12558 } else { 12559 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { 12560 setTagNameForLinkagePurposes(TD, NewTD); 12561 handleTagNumbering(TD, S); 12562 } 12563 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 12564 NewND = NewTD; 12565 } 12566 12567 PushOnScopeChains(NewND, S); 12568 ActOnDocumentableDecl(NewND); 12569 return NewND; 12570 } 12571 12572 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 12573 SourceLocation AliasLoc, 12574 IdentifierInfo *Alias, CXXScopeSpec &SS, 12575 SourceLocation IdentLoc, 12576 IdentifierInfo *Ident) { 12577 12578 // Lookup the namespace name. 12579 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 12580 LookupParsedName(R, S, &SS); 12581 12582 if (R.isAmbiguous()) 12583 return nullptr; 12584 12585 if (R.empty()) { 12586 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 12587 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 12588 return nullptr; 12589 } 12590 } 12591 assert(!R.isAmbiguous() && !R.empty()); 12592 NamedDecl *ND = R.getRepresentativeDecl(); 12593 12594 // Check if we have a previous declaration with the same name. 12595 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName, 12596 ForVisibleRedeclaration); 12597 LookupName(PrevR, S); 12598 12599 // Check we're not shadowing a template parameter. 12600 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) { 12601 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl()); 12602 PrevR.clear(); 12603 } 12604 12605 // Filter out any other lookup result from an enclosing scope. 12606 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false, 12607 /*AllowInlineNamespace*/false); 12608 12609 // Find the previous declaration and check that we can redeclare it. 12610 NamespaceAliasDecl *Prev = nullptr; 12611 if (PrevR.isSingleResult()) { 12612 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl(); 12613 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 12614 // We already have an alias with the same name that points to the same 12615 // namespace; check that it matches. 12616 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) { 12617 Prev = AD; 12618 } else if (isVisible(PrevDecl)) { 12619 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 12620 << Alias; 12621 Diag(AD->getLocation(), diag::note_previous_namespace_alias) 12622 << AD->getNamespace(); 12623 return nullptr; 12624 } 12625 } else if (isVisible(PrevDecl)) { 12626 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl()) 12627 ? diag::err_redefinition 12628 : diag::err_redefinition_different_kind; 12629 Diag(AliasLoc, DiagID) << Alias; 12630 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 12631 return nullptr; 12632 } 12633 } 12634 12635 // The use of a nested name specifier may trigger deprecation warnings. 12636 DiagnoseUseOfDecl(ND, IdentLoc); 12637 12638 NamespaceAliasDecl *AliasDecl = 12639 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 12640 Alias, SS.getWithLocInContext(Context), 12641 IdentLoc, ND); 12642 if (Prev) 12643 AliasDecl->setPreviousDecl(Prev); 12644 12645 PushOnScopeChains(AliasDecl, S); 12646 return AliasDecl; 12647 } 12648 12649 namespace { 12650 struct SpecialMemberExceptionSpecInfo 12651 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> { 12652 SourceLocation Loc; 12653 Sema::ImplicitExceptionSpecification ExceptSpec; 12654 12655 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD, 12656 Sema::CXXSpecialMember CSM, 12657 Sema::InheritedConstructorInfo *ICI, 12658 SourceLocation Loc) 12659 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {} 12660 12661 bool visitBase(CXXBaseSpecifier *Base); 12662 bool visitField(FieldDecl *FD); 12663 12664 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 12665 unsigned Quals); 12666 12667 void visitSubobjectCall(Subobject Subobj, 12668 Sema::SpecialMemberOverloadResult SMOR); 12669 }; 12670 } 12671 12672 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) { 12673 auto *RT = Base->getType()->getAs<RecordType>(); 12674 if (!RT) 12675 return false; 12676 12677 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl()); 12678 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 12679 if (auto *BaseCtor = SMOR.getMethod()) { 12680 visitSubobjectCall(Base, BaseCtor); 12681 return false; 12682 } 12683 12684 visitClassSubobject(BaseClass, Base, 0); 12685 return false; 12686 } 12687 12688 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) { 12689 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) { 12690 Expr *E = FD->getInClassInitializer(); 12691 if (!E) 12692 // FIXME: It's a little wasteful to build and throw away a 12693 // CXXDefaultInitExpr here. 12694 // FIXME: We should have a single context note pointing at Loc, and 12695 // this location should be MD->getLocation() instead, since that's 12696 // the location where we actually use the default init expression. 12697 E = S.BuildCXXDefaultInitExpr(Loc, FD).get(); 12698 if (E) 12699 ExceptSpec.CalledExpr(E); 12700 } else if (auto *RT = S.Context.getBaseElementType(FD->getType()) 12701 ->getAs<RecordType>()) { 12702 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD, 12703 FD->getType().getCVRQualifiers()); 12704 } 12705 return false; 12706 } 12707 12708 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class, 12709 Subobject Subobj, 12710 unsigned Quals) { 12711 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 12712 bool IsMutable = Field && Field->isMutable(); 12713 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable)); 12714 } 12715 12716 void SpecialMemberExceptionSpecInfo::visitSubobjectCall( 12717 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) { 12718 // Note, if lookup fails, it doesn't matter what exception specification we 12719 // choose because the special member will be deleted. 12720 if (CXXMethodDecl *MD = SMOR.getMethod()) 12721 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD); 12722 } 12723 12724 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) { 12725 llvm::APSInt Result; 12726 ExprResult Converted = CheckConvertedConstantExpression( 12727 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool); 12728 ExplicitSpec.setExpr(Converted.get()); 12729 if (Converted.isUsable() && !Converted.get()->isValueDependent()) { 12730 ExplicitSpec.setKind(Result.getBoolValue() 12731 ? ExplicitSpecKind::ResolvedTrue 12732 : ExplicitSpecKind::ResolvedFalse); 12733 return true; 12734 } 12735 ExplicitSpec.setKind(ExplicitSpecKind::Unresolved); 12736 return false; 12737 } 12738 12739 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) { 12740 ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved); 12741 if (!ExplicitExpr->isTypeDependent()) 12742 tryResolveExplicitSpecifier(ES); 12743 return ES; 12744 } 12745 12746 static Sema::ImplicitExceptionSpecification 12747 ComputeDefaultedSpecialMemberExceptionSpec( 12748 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 12749 Sema::InheritedConstructorInfo *ICI) { 12750 ComputingExceptionSpec CES(S, MD, Loc); 12751 12752 CXXRecordDecl *ClassDecl = MD->getParent(); 12753 12754 // C++ [except.spec]p14: 12755 // An implicitly declared special member function (Clause 12) shall have an 12756 // exception-specification. [...] 12757 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation()); 12758 if (ClassDecl->isInvalidDecl()) 12759 return Info.ExceptSpec; 12760 12761 // FIXME: If this diagnostic fires, we're probably missing a check for 12762 // attempting to resolve an exception specification before it's known 12763 // at a higher level. 12764 if (S.RequireCompleteType(MD->getLocation(), 12765 S.Context.getRecordType(ClassDecl), 12766 diag::err_exception_spec_incomplete_type)) 12767 return Info.ExceptSpec; 12768 12769 // C++1z [except.spec]p7: 12770 // [Look for exceptions thrown by] a constructor selected [...] to 12771 // initialize a potentially constructed subobject, 12772 // C++1z [except.spec]p8: 12773 // The exception specification for an implicitly-declared destructor, or a 12774 // destructor without a noexcept-specifier, is potentially-throwing if and 12775 // only if any of the destructors for any of its potentially constructed 12776 // subojects is potentially throwing. 12777 // FIXME: We respect the first rule but ignore the "potentially constructed" 12778 // in the second rule to resolve a core issue (no number yet) that would have 12779 // us reject: 12780 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; }; 12781 // struct B : A {}; 12782 // struct C : B { void f(); }; 12783 // ... due to giving B::~B() a non-throwing exception specification. 12784 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases 12785 : Info.VisitAllBases); 12786 12787 return Info.ExceptSpec; 12788 } 12789 12790 namespace { 12791 /// RAII object to register a special member as being currently declared. 12792 struct DeclaringSpecialMember { 12793 Sema &S; 12794 Sema::SpecialMemberDecl D; 12795 Sema::ContextRAII SavedContext; 12796 bool WasAlreadyBeingDeclared; 12797 12798 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 12799 : S(S), D(RD, CSM), SavedContext(S, RD) { 12800 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 12801 if (WasAlreadyBeingDeclared) 12802 // This almost never happens, but if it does, ensure that our cache 12803 // doesn't contain a stale result. 12804 S.SpecialMemberCache.clear(); 12805 else { 12806 // Register a note to be produced if we encounter an error while 12807 // declaring the special member. 12808 Sema::CodeSynthesisContext Ctx; 12809 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember; 12810 // FIXME: We don't have a location to use here. Using the class's 12811 // location maintains the fiction that we declare all special members 12812 // with the class, but (1) it's not clear that lying about that helps our 12813 // users understand what's going on, and (2) there may be outer contexts 12814 // on the stack (some of which are relevant) and printing them exposes 12815 // our lies. 12816 Ctx.PointOfInstantiation = RD->getLocation(); 12817 Ctx.Entity = RD; 12818 Ctx.SpecialMember = CSM; 12819 S.pushCodeSynthesisContext(Ctx); 12820 } 12821 } 12822 ~DeclaringSpecialMember() { 12823 if (!WasAlreadyBeingDeclared) { 12824 S.SpecialMembersBeingDeclared.erase(D); 12825 S.popCodeSynthesisContext(); 12826 } 12827 } 12828 12829 /// Are we already trying to declare this special member? 12830 bool isAlreadyBeingDeclared() const { 12831 return WasAlreadyBeingDeclared; 12832 } 12833 }; 12834 } 12835 12836 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) { 12837 // Look up any existing declarations, but don't trigger declaration of all 12838 // implicit special members with this name. 12839 DeclarationName Name = FD->getDeclName(); 12840 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName, 12841 ForExternalRedeclaration); 12842 for (auto *D : FD->getParent()->lookup(Name)) 12843 if (auto *Acceptable = R.getAcceptableDecl(D)) 12844 R.addDecl(Acceptable); 12845 R.resolveKind(); 12846 R.suppressDiagnostics(); 12847 12848 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false); 12849 } 12850 12851 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem, 12852 QualType ResultTy, 12853 ArrayRef<QualType> Args) { 12854 // Build an exception specification pointing back at this constructor. 12855 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem); 12856 12857 LangAS AS = getDefaultCXXMethodAddrSpace(); 12858 if (AS != LangAS::Default) { 12859 EPI.TypeQuals.addAddressSpace(AS); 12860 } 12861 12862 auto QT = Context.getFunctionType(ResultTy, Args, EPI); 12863 SpecialMem->setType(QT); 12864 } 12865 12866 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 12867 CXXRecordDecl *ClassDecl) { 12868 // C++ [class.ctor]p5: 12869 // A default constructor for a class X is a constructor of class X 12870 // that can be called without an argument. If there is no 12871 // user-declared constructor for class X, a default constructor is 12872 // implicitly declared. An implicitly-declared default constructor 12873 // is an inline public member of its class. 12874 assert(ClassDecl->needsImplicitDefaultConstructor() && 12875 "Should not build implicit default constructor!"); 12876 12877 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 12878 if (DSM.isAlreadyBeingDeclared()) 12879 return nullptr; 12880 12881 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12882 CXXDefaultConstructor, 12883 false); 12884 12885 // Create the actual constructor declaration. 12886 CanQualType ClassType 12887 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 12888 SourceLocation ClassLoc = ClassDecl->getLocation(); 12889 DeclarationName Name 12890 = Context.DeclarationNames.getCXXConstructorName(ClassType); 12891 DeclarationNameInfo NameInfo(Name, ClassLoc); 12892 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 12893 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(), 12894 /*TInfo=*/nullptr, ExplicitSpecifier(), 12895 /*isInline=*/true, /*isImplicitlyDeclared=*/true, 12896 Constexpr ? CSK_constexpr : CSK_unspecified); 12897 DefaultCon->setAccess(AS_public); 12898 DefaultCon->setDefaulted(); 12899 12900 if (getLangOpts().CUDA) { 12901 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 12902 DefaultCon, 12903 /* ConstRHS */ false, 12904 /* Diagnose */ false); 12905 } 12906 12907 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None); 12908 12909 // We don't need to use SpecialMemberIsTrivial here; triviality for default 12910 // constructors is easy to compute. 12911 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 12912 12913 // Note that we have declared this constructor. 12914 ++getASTContext().NumImplicitDefaultConstructorsDeclared; 12915 12916 Scope *S = getScopeForContext(ClassDecl); 12917 CheckImplicitSpecialMemberDeclaration(S, DefaultCon); 12918 12919 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 12920 SetDeclDeleted(DefaultCon, ClassLoc); 12921 12922 if (S) 12923 PushOnScopeChains(DefaultCon, S, false); 12924 ClassDecl->addDecl(DefaultCon); 12925 12926 return DefaultCon; 12927 } 12928 12929 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 12930 CXXConstructorDecl *Constructor) { 12931 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 12932 !Constructor->doesThisDeclarationHaveABody() && 12933 !Constructor->isDeleted()) && 12934 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 12935 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 12936 return; 12937 12938 CXXRecordDecl *ClassDecl = Constructor->getParent(); 12939 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 12940 12941 SynthesizedFunctionScope Scope(*this, Constructor); 12942 12943 // The exception specification is needed because we are defining the 12944 // function. 12945 ResolveExceptionSpec(CurrentLocation, 12946 Constructor->getType()->castAs<FunctionProtoType>()); 12947 MarkVTableUsed(CurrentLocation, ClassDecl); 12948 12949 // Add a context note for diagnostics produced after this point. 12950 Scope.addContextNote(CurrentLocation); 12951 12952 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) { 12953 Constructor->setInvalidDecl(); 12954 return; 12955 } 12956 12957 SourceLocation Loc = Constructor->getEndLoc().isValid() 12958 ? Constructor->getEndLoc() 12959 : Constructor->getLocation(); 12960 Constructor->setBody(new (Context) CompoundStmt(Loc)); 12961 Constructor->markUsed(Context); 12962 12963 if (ASTMutationListener *L = getASTMutationListener()) { 12964 L->CompletedImplicitDefinition(Constructor); 12965 } 12966 12967 DiagnoseUninitializedFields(*this, Constructor); 12968 } 12969 12970 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 12971 // Perform any delayed checks on exception specifications. 12972 CheckDelayedMemberExceptionSpecs(); 12973 } 12974 12975 /// Find or create the fake constructor we synthesize to model constructing an 12976 /// object of a derived class via a constructor of a base class. 12977 CXXConstructorDecl * 12978 Sema::findInheritingConstructor(SourceLocation Loc, 12979 CXXConstructorDecl *BaseCtor, 12980 ConstructorUsingShadowDecl *Shadow) { 12981 CXXRecordDecl *Derived = Shadow->getParent(); 12982 SourceLocation UsingLoc = Shadow->getLocation(); 12983 12984 // FIXME: Add a new kind of DeclarationName for an inherited constructor. 12985 // For now we use the name of the base class constructor as a member of the 12986 // derived class to indicate a (fake) inherited constructor name. 12987 DeclarationName Name = BaseCtor->getDeclName(); 12988 12989 // Check to see if we already have a fake constructor for this inherited 12990 // constructor call. 12991 for (NamedDecl *Ctor : Derived->lookup(Name)) 12992 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor) 12993 ->getInheritedConstructor() 12994 .getConstructor(), 12995 BaseCtor)) 12996 return cast<CXXConstructorDecl>(Ctor); 12997 12998 DeclarationNameInfo NameInfo(Name, UsingLoc); 12999 TypeSourceInfo *TInfo = 13000 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc); 13001 FunctionProtoTypeLoc ProtoLoc = 13002 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 13003 13004 // Check the inherited constructor is valid and find the list of base classes 13005 // from which it was inherited. 13006 InheritedConstructorInfo ICI(*this, Loc, Shadow); 13007 13008 bool Constexpr = 13009 BaseCtor->isConstexpr() && 13010 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor, 13011 false, BaseCtor, &ICI); 13012 13013 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 13014 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo, 13015 BaseCtor->getExplicitSpecifier(), /*isInline=*/true, 13016 /*isImplicitlyDeclared=*/true, 13017 Constexpr ? BaseCtor->getConstexprKind() : CSK_unspecified, 13018 InheritedConstructor(Shadow, BaseCtor), 13019 BaseCtor->getTrailingRequiresClause()); 13020 if (Shadow->isInvalidDecl()) 13021 DerivedCtor->setInvalidDecl(); 13022 13023 // Build an unevaluated exception specification for this fake constructor. 13024 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>(); 13025 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 13026 EPI.ExceptionSpec.Type = EST_Unevaluated; 13027 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 13028 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 13029 FPT->getParamTypes(), EPI)); 13030 13031 // Build the parameter declarations. 13032 SmallVector<ParmVarDecl *, 16> ParamDecls; 13033 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 13034 TypeSourceInfo *TInfo = 13035 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 13036 ParmVarDecl *PD = ParmVarDecl::Create( 13037 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 13038 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr); 13039 PD->setScopeInfo(0, I); 13040 PD->setImplicit(); 13041 // Ensure attributes are propagated onto parameters (this matters for 13042 // format, pass_object_size, ...). 13043 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I)); 13044 ParamDecls.push_back(PD); 13045 ProtoLoc.setParam(I, PD); 13046 } 13047 13048 // Set up the new constructor. 13049 assert(!BaseCtor->isDeleted() && "should not use deleted constructor"); 13050 DerivedCtor->setAccess(BaseCtor->getAccess()); 13051 DerivedCtor->setParams(ParamDecls); 13052 Derived->addDecl(DerivedCtor); 13053 13054 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI)) 13055 SetDeclDeleted(DerivedCtor, UsingLoc); 13056 13057 return DerivedCtor; 13058 } 13059 13060 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) { 13061 InheritedConstructorInfo ICI(*this, Ctor->getLocation(), 13062 Ctor->getInheritedConstructor().getShadowDecl()); 13063 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI, 13064 /*Diagnose*/true); 13065 } 13066 13067 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 13068 CXXConstructorDecl *Constructor) { 13069 CXXRecordDecl *ClassDecl = Constructor->getParent(); 13070 assert(Constructor->getInheritedConstructor() && 13071 !Constructor->doesThisDeclarationHaveABody() && 13072 !Constructor->isDeleted()); 13073 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 13074 return; 13075 13076 // Initializations are performed "as if by a defaulted default constructor", 13077 // so enter the appropriate scope. 13078 SynthesizedFunctionScope Scope(*this, Constructor); 13079 13080 // The exception specification is needed because we are defining the 13081 // function. 13082 ResolveExceptionSpec(CurrentLocation, 13083 Constructor->getType()->castAs<FunctionProtoType>()); 13084 MarkVTableUsed(CurrentLocation, ClassDecl); 13085 13086 // Add a context note for diagnostics produced after this point. 13087 Scope.addContextNote(CurrentLocation); 13088 13089 ConstructorUsingShadowDecl *Shadow = 13090 Constructor->getInheritedConstructor().getShadowDecl(); 13091 CXXConstructorDecl *InheritedCtor = 13092 Constructor->getInheritedConstructor().getConstructor(); 13093 13094 // [class.inhctor.init]p1: 13095 // initialization proceeds as if a defaulted default constructor is used to 13096 // initialize the D object and each base class subobject from which the 13097 // constructor was inherited 13098 13099 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow); 13100 CXXRecordDecl *RD = Shadow->getParent(); 13101 SourceLocation InitLoc = Shadow->getLocation(); 13102 13103 // Build explicit initializers for all base classes from which the 13104 // constructor was inherited. 13105 SmallVector<CXXCtorInitializer*, 8> Inits; 13106 for (bool VBase : {false, true}) { 13107 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) { 13108 if (B.isVirtual() != VBase) 13109 continue; 13110 13111 auto *BaseRD = B.getType()->getAsCXXRecordDecl(); 13112 if (!BaseRD) 13113 continue; 13114 13115 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor); 13116 if (!BaseCtor.first) 13117 continue; 13118 13119 MarkFunctionReferenced(CurrentLocation, BaseCtor.first); 13120 ExprResult Init = new (Context) CXXInheritedCtorInitExpr( 13121 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second); 13122 13123 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc); 13124 Inits.push_back(new (Context) CXXCtorInitializer( 13125 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc, 13126 SourceLocation())); 13127 } 13128 } 13129 13130 // We now proceed as if for a defaulted default constructor, with the relevant 13131 // initializers replaced. 13132 13133 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) { 13134 Constructor->setInvalidDecl(); 13135 return; 13136 } 13137 13138 Constructor->setBody(new (Context) CompoundStmt(InitLoc)); 13139 Constructor->markUsed(Context); 13140 13141 if (ASTMutationListener *L = getASTMutationListener()) { 13142 L->CompletedImplicitDefinition(Constructor); 13143 } 13144 13145 DiagnoseUninitializedFields(*this, Constructor); 13146 } 13147 13148 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 13149 // C++ [class.dtor]p2: 13150 // If a class has no user-declared destructor, a destructor is 13151 // declared implicitly. An implicitly-declared destructor is an 13152 // inline public member of its class. 13153 assert(ClassDecl->needsImplicitDestructor()); 13154 13155 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 13156 if (DSM.isAlreadyBeingDeclared()) 13157 return nullptr; 13158 13159 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 13160 CXXDestructor, 13161 false); 13162 13163 // Create the actual destructor declaration. 13164 CanQualType ClassType 13165 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 13166 SourceLocation ClassLoc = ClassDecl->getLocation(); 13167 DeclarationName Name 13168 = Context.DeclarationNames.getCXXDestructorName(ClassType); 13169 DeclarationNameInfo NameInfo(Name, ClassLoc); 13170 CXXDestructorDecl *Destructor = 13171 CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 13172 QualType(), nullptr, /*isInline=*/true, 13173 /*isImplicitlyDeclared=*/true, 13174 Constexpr ? CSK_constexpr : CSK_unspecified); 13175 Destructor->setAccess(AS_public); 13176 Destructor->setDefaulted(); 13177 13178 if (getLangOpts().CUDA) { 13179 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 13180 Destructor, 13181 /* ConstRHS */ false, 13182 /* Diagnose */ false); 13183 } 13184 13185 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None); 13186 13187 // We don't need to use SpecialMemberIsTrivial here; triviality for 13188 // destructors is easy to compute. 13189 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 13190 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() || 13191 ClassDecl->hasTrivialDestructorForCall()); 13192 13193 // Note that we have declared this destructor. 13194 ++getASTContext().NumImplicitDestructorsDeclared; 13195 13196 Scope *S = getScopeForContext(ClassDecl); 13197 CheckImplicitSpecialMemberDeclaration(S, Destructor); 13198 13199 // We can't check whether an implicit destructor is deleted before we complete 13200 // the definition of the class, because its validity depends on the alignment 13201 // of the class. We'll check this from ActOnFields once the class is complete. 13202 if (ClassDecl->isCompleteDefinition() && 13203 ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 13204 SetDeclDeleted(Destructor, ClassLoc); 13205 13206 // Introduce this destructor into its scope. 13207 if (S) 13208 PushOnScopeChains(Destructor, S, false); 13209 ClassDecl->addDecl(Destructor); 13210 13211 return Destructor; 13212 } 13213 13214 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 13215 CXXDestructorDecl *Destructor) { 13216 assert((Destructor->isDefaulted() && 13217 !Destructor->doesThisDeclarationHaveABody() && 13218 !Destructor->isDeleted()) && 13219 "DefineImplicitDestructor - call it for implicit default dtor"); 13220 if (Destructor->willHaveBody() || Destructor->isInvalidDecl()) 13221 return; 13222 13223 CXXRecordDecl *ClassDecl = Destructor->getParent(); 13224 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 13225 13226 SynthesizedFunctionScope Scope(*this, Destructor); 13227 13228 // The exception specification is needed because we are defining the 13229 // function. 13230 ResolveExceptionSpec(CurrentLocation, 13231 Destructor->getType()->castAs<FunctionProtoType>()); 13232 MarkVTableUsed(CurrentLocation, ClassDecl); 13233 13234 // Add a context note for diagnostics produced after this point. 13235 Scope.addContextNote(CurrentLocation); 13236 13237 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 13238 Destructor->getParent()); 13239 13240 if (CheckDestructor(Destructor)) { 13241 Destructor->setInvalidDecl(); 13242 return; 13243 } 13244 13245 SourceLocation Loc = Destructor->getEndLoc().isValid() 13246 ? Destructor->getEndLoc() 13247 : Destructor->getLocation(); 13248 Destructor->setBody(new (Context) CompoundStmt(Loc)); 13249 Destructor->markUsed(Context); 13250 13251 if (ASTMutationListener *L = getASTMutationListener()) { 13252 L->CompletedImplicitDefinition(Destructor); 13253 } 13254 } 13255 13256 void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation, 13257 CXXDestructorDecl *Destructor) { 13258 if (Destructor->isInvalidDecl()) 13259 return; 13260 13261 CXXRecordDecl *ClassDecl = Destructor->getParent(); 13262 assert(Context.getTargetInfo().getCXXABI().isMicrosoft() && 13263 "implicit complete dtors unneeded outside MS ABI"); 13264 assert(ClassDecl->getNumVBases() > 0 && 13265 "complete dtor only exists for classes with vbases"); 13266 13267 SynthesizedFunctionScope Scope(*this, Destructor); 13268 13269 // Add a context note for diagnostics produced after this point. 13270 Scope.addContextNote(CurrentLocation); 13271 13272 MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl); 13273 } 13274 13275 /// Perform any semantic analysis which needs to be delayed until all 13276 /// pending class member declarations have been parsed. 13277 void Sema::ActOnFinishCXXMemberDecls() { 13278 // If the context is an invalid C++ class, just suppress these checks. 13279 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 13280 if (Record->isInvalidDecl()) { 13281 DelayedOverridingExceptionSpecChecks.clear(); 13282 DelayedEquivalentExceptionSpecChecks.clear(); 13283 return; 13284 } 13285 checkForMultipleExportedDefaultConstructors(*this, Record); 13286 } 13287 } 13288 13289 void Sema::ActOnFinishCXXNonNestedClass() { 13290 referenceDLLExportedClassMethods(); 13291 13292 if (!DelayedDllExportMemberFunctions.empty()) { 13293 SmallVector<CXXMethodDecl*, 4> WorkList; 13294 std::swap(DelayedDllExportMemberFunctions, WorkList); 13295 for (CXXMethodDecl *M : WorkList) { 13296 DefineDefaultedFunction(*this, M, M->getLocation()); 13297 13298 // Pass the method to the consumer to get emitted. This is not necessary 13299 // for explicit instantiation definitions, as they will get emitted 13300 // anyway. 13301 if (M->getParent()->getTemplateSpecializationKind() != 13302 TSK_ExplicitInstantiationDefinition) 13303 ActOnFinishInlineFunctionDef(M); 13304 } 13305 } 13306 } 13307 13308 void Sema::referenceDLLExportedClassMethods() { 13309 if (!DelayedDllExportClasses.empty()) { 13310 // Calling ReferenceDllExportedMembers might cause the current function to 13311 // be called again, so use a local copy of DelayedDllExportClasses. 13312 SmallVector<CXXRecordDecl *, 4> WorkList; 13313 std::swap(DelayedDllExportClasses, WorkList); 13314 for (CXXRecordDecl *Class : WorkList) 13315 ReferenceDllExportedMembers(*this, Class); 13316 } 13317 } 13318 13319 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) { 13320 assert(getLangOpts().CPlusPlus11 && 13321 "adjusting dtor exception specs was introduced in c++11"); 13322 13323 if (Destructor->isDependentContext()) 13324 return; 13325 13326 // C++11 [class.dtor]p3: 13327 // A declaration of a destructor that does not have an exception- 13328 // specification is implicitly considered to have the same exception- 13329 // specification as an implicit declaration. 13330 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>(); 13331 if (DtorType->hasExceptionSpec()) 13332 return; 13333 13334 // Replace the destructor's type, building off the existing one. Fortunately, 13335 // the only thing of interest in the destructor type is its extended info. 13336 // The return and arguments are fixed. 13337 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 13338 EPI.ExceptionSpec.Type = EST_Unevaluated; 13339 EPI.ExceptionSpec.SourceDecl = Destructor; 13340 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 13341 13342 // FIXME: If the destructor has a body that could throw, and the newly created 13343 // spec doesn't allow exceptions, we should emit a warning, because this 13344 // change in behavior can break conforming C++03 programs at runtime. 13345 // However, we don't have a body or an exception specification yet, so it 13346 // needs to be done somewhere else. 13347 } 13348 13349 namespace { 13350 /// An abstract base class for all helper classes used in building the 13351 // copy/move operators. These classes serve as factory functions and help us 13352 // avoid using the same Expr* in the AST twice. 13353 class ExprBuilder { 13354 ExprBuilder(const ExprBuilder&) = delete; 13355 ExprBuilder &operator=(const ExprBuilder&) = delete; 13356 13357 protected: 13358 static Expr *assertNotNull(Expr *E) { 13359 assert(E && "Expression construction must not fail."); 13360 return E; 13361 } 13362 13363 public: 13364 ExprBuilder() {} 13365 virtual ~ExprBuilder() {} 13366 13367 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 13368 }; 13369 13370 class RefBuilder: public ExprBuilder { 13371 VarDecl *Var; 13372 QualType VarType; 13373 13374 public: 13375 Expr *build(Sema &S, SourceLocation Loc) const override { 13376 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc)); 13377 } 13378 13379 RefBuilder(VarDecl *Var, QualType VarType) 13380 : Var(Var), VarType(VarType) {} 13381 }; 13382 13383 class ThisBuilder: public ExprBuilder { 13384 public: 13385 Expr *build(Sema &S, SourceLocation Loc) const override { 13386 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 13387 } 13388 }; 13389 13390 class CastBuilder: public ExprBuilder { 13391 const ExprBuilder &Builder; 13392 QualType Type; 13393 ExprValueKind Kind; 13394 const CXXCastPath &Path; 13395 13396 public: 13397 Expr *build(Sema &S, SourceLocation Loc) const override { 13398 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 13399 CK_UncheckedDerivedToBase, Kind, 13400 &Path).get()); 13401 } 13402 13403 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 13404 const CXXCastPath &Path) 13405 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 13406 }; 13407 13408 class DerefBuilder: public ExprBuilder { 13409 const ExprBuilder &Builder; 13410 13411 public: 13412 Expr *build(Sema &S, SourceLocation Loc) const override { 13413 return assertNotNull( 13414 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 13415 } 13416 13417 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13418 }; 13419 13420 class MemberBuilder: public ExprBuilder { 13421 const ExprBuilder &Builder; 13422 QualType Type; 13423 CXXScopeSpec SS; 13424 bool IsArrow; 13425 LookupResult &MemberLookup; 13426 13427 public: 13428 Expr *build(Sema &S, SourceLocation Loc) const override { 13429 return assertNotNull(S.BuildMemberReferenceExpr( 13430 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 13431 nullptr, MemberLookup, nullptr, nullptr).get()); 13432 } 13433 13434 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 13435 LookupResult &MemberLookup) 13436 : Builder(Builder), Type(Type), IsArrow(IsArrow), 13437 MemberLookup(MemberLookup) {} 13438 }; 13439 13440 class MoveCastBuilder: public ExprBuilder { 13441 const ExprBuilder &Builder; 13442 13443 public: 13444 Expr *build(Sema &S, SourceLocation Loc) const override { 13445 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 13446 } 13447 13448 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13449 }; 13450 13451 class LvalueConvBuilder: public ExprBuilder { 13452 const ExprBuilder &Builder; 13453 13454 public: 13455 Expr *build(Sema &S, SourceLocation Loc) const override { 13456 return assertNotNull( 13457 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 13458 } 13459 13460 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 13461 }; 13462 13463 class SubscriptBuilder: public ExprBuilder { 13464 const ExprBuilder &Base; 13465 const ExprBuilder &Index; 13466 13467 public: 13468 Expr *build(Sema &S, SourceLocation Loc) const override { 13469 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 13470 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 13471 } 13472 13473 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 13474 : Base(Base), Index(Index) {} 13475 }; 13476 13477 } // end anonymous namespace 13478 13479 /// When generating a defaulted copy or move assignment operator, if a field 13480 /// should be copied with __builtin_memcpy rather than via explicit assignments, 13481 /// do so. This optimization only applies for arrays of scalars, and for arrays 13482 /// of class type where the selected copy/move-assignment operator is trivial. 13483 static StmtResult 13484 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 13485 const ExprBuilder &ToB, const ExprBuilder &FromB) { 13486 // Compute the size of the memory buffer to be copied. 13487 QualType SizeType = S.Context.getSizeType(); 13488 llvm::APInt Size(S.Context.getTypeSize(SizeType), 13489 S.Context.getTypeSizeInChars(T).getQuantity()); 13490 13491 // Take the address of the field references for "from" and "to". We 13492 // directly construct UnaryOperators here because semantic analysis 13493 // does not permit us to take the address of an xvalue. 13494 Expr *From = FromB.build(S, Loc); 13495 From = UnaryOperator::Create( 13496 S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()), 13497 VK_RValue, OK_Ordinary, Loc, false, S.CurFPFeatures); 13498 Expr *To = ToB.build(S, Loc); 13499 To = UnaryOperator::Create(S.Context, To, UO_AddrOf, 13500 S.Context.getPointerType(To->getType()), VK_RValue, 13501 OK_Ordinary, Loc, false, S.CurFPFeatures); 13502 13503 const Type *E = T->getBaseElementTypeUnsafe(); 13504 bool NeedsCollectableMemCpy = 13505 E->isRecordType() && 13506 E->castAs<RecordType>()->getDecl()->hasObjectMember(); 13507 13508 // Create a reference to the __builtin_objc_memmove_collectable function 13509 StringRef MemCpyName = NeedsCollectableMemCpy ? 13510 "__builtin_objc_memmove_collectable" : 13511 "__builtin_memcpy"; 13512 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 13513 Sema::LookupOrdinaryName); 13514 S.LookupName(R, S.TUScope, true); 13515 13516 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 13517 if (!MemCpy) 13518 // Something went horribly wrong earlier, and we will have complained 13519 // about it. 13520 return StmtError(); 13521 13522 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 13523 VK_RValue, Loc, nullptr); 13524 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 13525 13526 Expr *CallArgs[] = { 13527 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 13528 }; 13529 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 13530 Loc, CallArgs, Loc); 13531 13532 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 13533 return Call.getAs<Stmt>(); 13534 } 13535 13536 /// Builds a statement that copies/moves the given entity from \p From to 13537 /// \c To. 13538 /// 13539 /// This routine is used to copy/move the members of a class with an 13540 /// implicitly-declared copy/move assignment operator. When the entities being 13541 /// copied are arrays, this routine builds for loops to copy them. 13542 /// 13543 /// \param S The Sema object used for type-checking. 13544 /// 13545 /// \param Loc The location where the implicit copy/move is being generated. 13546 /// 13547 /// \param T The type of the expressions being copied/moved. Both expressions 13548 /// must have this type. 13549 /// 13550 /// \param To The expression we are copying/moving to. 13551 /// 13552 /// \param From The expression we are copying/moving from. 13553 /// 13554 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 13555 /// Otherwise, it's a non-static member subobject. 13556 /// 13557 /// \param Copying Whether we're copying or moving. 13558 /// 13559 /// \param Depth Internal parameter recording the depth of the recursion. 13560 /// 13561 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 13562 /// if a memcpy should be used instead. 13563 static StmtResult 13564 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 13565 const ExprBuilder &To, const ExprBuilder &From, 13566 bool CopyingBaseSubobject, bool Copying, 13567 unsigned Depth = 0) { 13568 // C++11 [class.copy]p28: 13569 // Each subobject is assigned in the manner appropriate to its type: 13570 // 13571 // - if the subobject is of class type, as if by a call to operator= with 13572 // the subobject as the object expression and the corresponding 13573 // subobject of x as a single function argument (as if by explicit 13574 // qualification; that is, ignoring any possible virtual overriding 13575 // functions in more derived classes); 13576 // 13577 // C++03 [class.copy]p13: 13578 // - if the subobject is of class type, the copy assignment operator for 13579 // the class is used (as if by explicit qualification; that is, 13580 // ignoring any possible virtual overriding functions in more derived 13581 // classes); 13582 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 13583 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 13584 13585 // Look for operator=. 13586 DeclarationName Name 13587 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 13588 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 13589 S.LookupQualifiedName(OpLookup, ClassDecl, false); 13590 13591 // Prior to C++11, filter out any result that isn't a copy/move-assignment 13592 // operator. 13593 if (!S.getLangOpts().CPlusPlus11) { 13594 LookupResult::Filter F = OpLookup.makeFilter(); 13595 while (F.hasNext()) { 13596 NamedDecl *D = F.next(); 13597 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 13598 if (Method->isCopyAssignmentOperator() || 13599 (!Copying && Method->isMoveAssignmentOperator())) 13600 continue; 13601 13602 F.erase(); 13603 } 13604 F.done(); 13605 } 13606 13607 // Suppress the protected check (C++ [class.protected]) for each of the 13608 // assignment operators we found. This strange dance is required when 13609 // we're assigning via a base classes's copy-assignment operator. To 13610 // ensure that we're getting the right base class subobject (without 13611 // ambiguities), we need to cast "this" to that subobject type; to 13612 // ensure that we don't go through the virtual call mechanism, we need 13613 // to qualify the operator= name with the base class (see below). However, 13614 // this means that if the base class has a protected copy assignment 13615 // operator, the protected member access check will fail. So, we 13616 // rewrite "protected" access to "public" access in this case, since we 13617 // know by construction that we're calling from a derived class. 13618 if (CopyingBaseSubobject) { 13619 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 13620 L != LEnd; ++L) { 13621 if (L.getAccess() == AS_protected) 13622 L.setAccess(AS_public); 13623 } 13624 } 13625 13626 // Create the nested-name-specifier that will be used to qualify the 13627 // reference to operator=; this is required to suppress the virtual 13628 // call mechanism. 13629 CXXScopeSpec SS; 13630 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 13631 SS.MakeTrivial(S.Context, 13632 NestedNameSpecifier::Create(S.Context, nullptr, false, 13633 CanonicalT), 13634 Loc); 13635 13636 // Create the reference to operator=. 13637 ExprResult OpEqualRef 13638 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false, 13639 SS, /*TemplateKWLoc=*/SourceLocation(), 13640 /*FirstQualifierInScope=*/nullptr, 13641 OpLookup, 13642 /*TemplateArgs=*/nullptr, /*S*/nullptr, 13643 /*SuppressQualifierCheck=*/true); 13644 if (OpEqualRef.isInvalid()) 13645 return StmtError(); 13646 13647 // Build the call to the assignment operator. 13648 13649 Expr *FromInst = From.build(S, Loc); 13650 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 13651 OpEqualRef.getAs<Expr>(), 13652 Loc, FromInst, Loc); 13653 if (Call.isInvalid()) 13654 return StmtError(); 13655 13656 // If we built a call to a trivial 'operator=' while copying an array, 13657 // bail out. We'll replace the whole shebang with a memcpy. 13658 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 13659 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 13660 return StmtResult((Stmt*)nullptr); 13661 13662 // Convert to an expression-statement, and clean up any produced 13663 // temporaries. 13664 return S.ActOnExprStmt(Call); 13665 } 13666 13667 // - if the subobject is of scalar type, the built-in assignment 13668 // operator is used. 13669 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 13670 if (!ArrayTy) { 13671 ExprResult Assignment = S.CreateBuiltinBinOp( 13672 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 13673 if (Assignment.isInvalid()) 13674 return StmtError(); 13675 return S.ActOnExprStmt(Assignment); 13676 } 13677 13678 // - if the subobject is an array, each element is assigned, in the 13679 // manner appropriate to the element type; 13680 13681 // Construct a loop over the array bounds, e.g., 13682 // 13683 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 13684 // 13685 // that will copy each of the array elements. 13686 QualType SizeType = S.Context.getSizeType(); 13687 13688 // Create the iteration variable. 13689 IdentifierInfo *IterationVarName = nullptr; 13690 { 13691 SmallString<8> Str; 13692 llvm::raw_svector_ostream OS(Str); 13693 OS << "__i" << Depth; 13694 IterationVarName = &S.Context.Idents.get(OS.str()); 13695 } 13696 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 13697 IterationVarName, SizeType, 13698 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 13699 SC_None); 13700 13701 // Initialize the iteration variable to zero. 13702 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 13703 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 13704 13705 // Creates a reference to the iteration variable. 13706 RefBuilder IterationVarRef(IterationVar, SizeType); 13707 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 13708 13709 // Create the DeclStmt that holds the iteration variable. 13710 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 13711 13712 // Subscript the "from" and "to" expressions with the iteration variable. 13713 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 13714 MoveCastBuilder FromIndexMove(FromIndexCopy); 13715 const ExprBuilder *FromIndex; 13716 if (Copying) 13717 FromIndex = &FromIndexCopy; 13718 else 13719 FromIndex = &FromIndexMove; 13720 13721 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 13722 13723 // Build the copy/move for an individual element of the array. 13724 StmtResult Copy = 13725 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 13726 ToIndex, *FromIndex, CopyingBaseSubobject, 13727 Copying, Depth + 1); 13728 // Bail out if copying fails or if we determined that we should use memcpy. 13729 if (Copy.isInvalid() || !Copy.get()) 13730 return Copy; 13731 13732 // Create the comparison against the array bound. 13733 llvm::APInt Upper 13734 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 13735 Expr *Comparison = BinaryOperator::Create( 13736 S.Context, IterationVarRefRVal.build(S, Loc), 13737 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE, 13738 S.Context.BoolTy, VK_RValue, OK_Ordinary, Loc, S.CurFPFeatures); 13739 13740 // Create the pre-increment of the iteration variable. We can determine 13741 // whether the increment will overflow based on the value of the array 13742 // bound. 13743 Expr *Increment = UnaryOperator::Create( 13744 S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue, 13745 OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatures); 13746 13747 // Construct the loop that copies all elements of this array. 13748 return S.ActOnForStmt( 13749 Loc, Loc, InitStmt, 13750 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean), 13751 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get()); 13752 } 13753 13754 static StmtResult 13755 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 13756 const ExprBuilder &To, const ExprBuilder &From, 13757 bool CopyingBaseSubobject, bool Copying) { 13758 // Maybe we should use a memcpy? 13759 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 13760 T.isTriviallyCopyableType(S.Context)) 13761 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 13762 13763 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 13764 CopyingBaseSubobject, 13765 Copying, 0)); 13766 13767 // If we ended up picking a trivial assignment operator for an array of a 13768 // non-trivially-copyable class type, just emit a memcpy. 13769 if (!Result.isInvalid() && !Result.get()) 13770 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 13771 13772 return Result; 13773 } 13774 13775 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 13776 // Note: The following rules are largely analoguous to the copy 13777 // constructor rules. Note that virtual bases are not taken into account 13778 // for determining the argument type of the operator. Note also that 13779 // operators taking an object instead of a reference are allowed. 13780 assert(ClassDecl->needsImplicitCopyAssignment()); 13781 13782 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 13783 if (DSM.isAlreadyBeingDeclared()) 13784 return nullptr; 13785 13786 QualType ArgType = Context.getTypeDeclType(ClassDecl); 13787 LangAS AS = getDefaultCXXMethodAddrSpace(); 13788 if (AS != LangAS::Default) 13789 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 13790 QualType RetType = Context.getLValueReferenceType(ArgType); 13791 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 13792 if (Const) 13793 ArgType = ArgType.withConst(); 13794 13795 ArgType = Context.getLValueReferenceType(ArgType); 13796 13797 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 13798 CXXCopyAssignment, 13799 Const); 13800 13801 // An implicitly-declared copy assignment operator is an inline public 13802 // member of its class. 13803 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 13804 SourceLocation ClassLoc = ClassDecl->getLocation(); 13805 DeclarationNameInfo NameInfo(Name, ClassLoc); 13806 CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create( 13807 Context, ClassDecl, ClassLoc, NameInfo, QualType(), 13808 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 13809 /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified, 13810 SourceLocation()); 13811 CopyAssignment->setAccess(AS_public); 13812 CopyAssignment->setDefaulted(); 13813 CopyAssignment->setImplicit(); 13814 13815 if (getLangOpts().CUDA) { 13816 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 13817 CopyAssignment, 13818 /* ConstRHS */ Const, 13819 /* Diagnose */ false); 13820 } 13821 13822 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType); 13823 13824 // Add the parameter to the operator. 13825 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 13826 ClassLoc, ClassLoc, 13827 /*Id=*/nullptr, ArgType, 13828 /*TInfo=*/nullptr, SC_None, 13829 nullptr); 13830 CopyAssignment->setParams(FromParam); 13831 13832 CopyAssignment->setTrivial( 13833 ClassDecl->needsOverloadResolutionForCopyAssignment() 13834 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 13835 : ClassDecl->hasTrivialCopyAssignment()); 13836 13837 // Note that we have added this copy-assignment operator. 13838 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared; 13839 13840 Scope *S = getScopeForContext(ClassDecl); 13841 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment); 13842 13843 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) { 13844 ClassDecl->setImplicitCopyAssignmentIsDeleted(); 13845 SetDeclDeleted(CopyAssignment, ClassLoc); 13846 } 13847 13848 if (S) 13849 PushOnScopeChains(CopyAssignment, S, false); 13850 ClassDecl->addDecl(CopyAssignment); 13851 13852 return CopyAssignment; 13853 } 13854 13855 /// Diagnose an implicit copy operation for a class which is odr-used, but 13856 /// which is deprecated because the class has a user-declared copy constructor, 13857 /// copy assignment operator, or destructor. 13858 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) { 13859 assert(CopyOp->isImplicit()); 13860 13861 CXXRecordDecl *RD = CopyOp->getParent(); 13862 CXXMethodDecl *UserDeclaredOperation = nullptr; 13863 13864 // In Microsoft mode, assignment operations don't affect constructors and 13865 // vice versa. 13866 if (RD->hasUserDeclaredDestructor()) { 13867 UserDeclaredOperation = RD->getDestructor(); 13868 } else if (!isa<CXXConstructorDecl>(CopyOp) && 13869 RD->hasUserDeclaredCopyConstructor() && 13870 !S.getLangOpts().MSVCCompat) { 13871 // Find any user-declared copy constructor. 13872 for (auto *I : RD->ctors()) { 13873 if (I->isCopyConstructor()) { 13874 UserDeclaredOperation = I; 13875 break; 13876 } 13877 } 13878 assert(UserDeclaredOperation); 13879 } else if (isa<CXXConstructorDecl>(CopyOp) && 13880 RD->hasUserDeclaredCopyAssignment() && 13881 !S.getLangOpts().MSVCCompat) { 13882 // Find any user-declared move assignment operator. 13883 for (auto *I : RD->methods()) { 13884 if (I->isCopyAssignmentOperator()) { 13885 UserDeclaredOperation = I; 13886 break; 13887 } 13888 } 13889 assert(UserDeclaredOperation); 13890 } 13891 13892 if (UserDeclaredOperation && UserDeclaredOperation->isUserProvided()) { 13893 S.Diag(UserDeclaredOperation->getLocation(), 13894 isa<CXXDestructorDecl>(UserDeclaredOperation) 13895 ? diag::warn_deprecated_copy_dtor_operation 13896 : diag::warn_deprecated_copy_operation) 13897 << RD << /*copy assignment*/ !isa<CXXConstructorDecl>(CopyOp); 13898 } 13899 } 13900 13901 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 13902 CXXMethodDecl *CopyAssignOperator) { 13903 assert((CopyAssignOperator->isDefaulted() && 13904 CopyAssignOperator->isOverloadedOperator() && 13905 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 13906 !CopyAssignOperator->doesThisDeclarationHaveABody() && 13907 !CopyAssignOperator->isDeleted()) && 13908 "DefineImplicitCopyAssignment called for wrong function"); 13909 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl()) 13910 return; 13911 13912 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 13913 if (ClassDecl->isInvalidDecl()) { 13914 CopyAssignOperator->setInvalidDecl(); 13915 return; 13916 } 13917 13918 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 13919 13920 // The exception specification is needed because we are defining the 13921 // function. 13922 ResolveExceptionSpec(CurrentLocation, 13923 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 13924 13925 // Add a context note for diagnostics produced after this point. 13926 Scope.addContextNote(CurrentLocation); 13927 13928 // C++11 [class.copy]p18: 13929 // The [definition of an implicitly declared copy assignment operator] is 13930 // deprecated if the class has a user-declared copy constructor or a 13931 // user-declared destructor. 13932 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 13933 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator); 13934 13935 // C++0x [class.copy]p30: 13936 // The implicitly-defined or explicitly-defaulted copy assignment operator 13937 // for a non-union class X performs memberwise copy assignment of its 13938 // subobjects. The direct base classes of X are assigned first, in the 13939 // order of their declaration in the base-specifier-list, and then the 13940 // immediate non-static data members of X are assigned, in the order in 13941 // which they were declared in the class definition. 13942 13943 // The statements that form the synthesized function body. 13944 SmallVector<Stmt*, 8> Statements; 13945 13946 // The parameter for the "other" object, which we are copying from. 13947 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 13948 Qualifiers OtherQuals = Other->getType().getQualifiers(); 13949 QualType OtherRefType = Other->getType(); 13950 if (const LValueReferenceType *OtherRef 13951 = OtherRefType->getAs<LValueReferenceType>()) { 13952 OtherRefType = OtherRef->getPointeeType(); 13953 OtherQuals = OtherRefType.getQualifiers(); 13954 } 13955 13956 // Our location for everything implicitly-generated. 13957 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid() 13958 ? CopyAssignOperator->getEndLoc() 13959 : CopyAssignOperator->getLocation(); 13960 13961 // Builds a DeclRefExpr for the "other" object. 13962 RefBuilder OtherRef(Other, OtherRefType); 13963 13964 // Builds the "this" pointer. 13965 ThisBuilder This; 13966 13967 // Assign base classes. 13968 bool Invalid = false; 13969 for (auto &Base : ClassDecl->bases()) { 13970 // Form the assignment: 13971 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 13972 QualType BaseType = Base.getType().getUnqualifiedType(); 13973 if (!BaseType->isRecordType()) { 13974 Invalid = true; 13975 continue; 13976 } 13977 13978 CXXCastPath BasePath; 13979 BasePath.push_back(&Base); 13980 13981 // Construct the "from" expression, which is an implicit cast to the 13982 // appropriately-qualified base type. 13983 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 13984 VK_LValue, BasePath); 13985 13986 // Dereference "this". 13987 DerefBuilder DerefThis(This); 13988 CastBuilder To(DerefThis, 13989 Context.getQualifiedType( 13990 BaseType, CopyAssignOperator->getMethodQualifiers()), 13991 VK_LValue, BasePath); 13992 13993 // Build the copy. 13994 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 13995 To, From, 13996 /*CopyingBaseSubobject=*/true, 13997 /*Copying=*/true); 13998 if (Copy.isInvalid()) { 13999 CopyAssignOperator->setInvalidDecl(); 14000 return; 14001 } 14002 14003 // Success! Record the copy. 14004 Statements.push_back(Copy.getAs<Expr>()); 14005 } 14006 14007 // Assign non-static members. 14008 for (auto *Field : ClassDecl->fields()) { 14009 // FIXME: We should form some kind of AST representation for the implied 14010 // memcpy in a union copy operation. 14011 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 14012 continue; 14013 14014 if (Field->isInvalidDecl()) { 14015 Invalid = true; 14016 continue; 14017 } 14018 14019 // Check for members of reference type; we can't copy those. 14020 if (Field->getType()->isReferenceType()) { 14021 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14022 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 14023 Diag(Field->getLocation(), diag::note_declared_at); 14024 Invalid = true; 14025 continue; 14026 } 14027 14028 // Check for members of const-qualified, non-class type. 14029 QualType BaseType = Context.getBaseElementType(Field->getType()); 14030 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 14031 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14032 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 14033 Diag(Field->getLocation(), diag::note_declared_at); 14034 Invalid = true; 14035 continue; 14036 } 14037 14038 // Suppress assigning zero-width bitfields. 14039 if (Field->isZeroLengthBitField(Context)) 14040 continue; 14041 14042 QualType FieldType = Field->getType().getNonReferenceType(); 14043 if (FieldType->isIncompleteArrayType()) { 14044 assert(ClassDecl->hasFlexibleArrayMember() && 14045 "Incomplete array type is not valid"); 14046 continue; 14047 } 14048 14049 // Build references to the field in the object we're copying from and to. 14050 CXXScopeSpec SS; // Intentionally empty 14051 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 14052 LookupMemberName); 14053 MemberLookup.addDecl(Field); 14054 MemberLookup.resolveKind(); 14055 14056 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 14057 14058 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 14059 14060 // Build the copy of this field. 14061 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 14062 To, From, 14063 /*CopyingBaseSubobject=*/false, 14064 /*Copying=*/true); 14065 if (Copy.isInvalid()) { 14066 CopyAssignOperator->setInvalidDecl(); 14067 return; 14068 } 14069 14070 // Success! Record the copy. 14071 Statements.push_back(Copy.getAs<Stmt>()); 14072 } 14073 14074 if (!Invalid) { 14075 // Add a "return *this;" 14076 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 14077 14078 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 14079 if (Return.isInvalid()) 14080 Invalid = true; 14081 else 14082 Statements.push_back(Return.getAs<Stmt>()); 14083 } 14084 14085 if (Invalid) { 14086 CopyAssignOperator->setInvalidDecl(); 14087 return; 14088 } 14089 14090 StmtResult Body; 14091 { 14092 CompoundScopeRAII CompoundScope(*this); 14093 Body = ActOnCompoundStmt(Loc, Loc, Statements, 14094 /*isStmtExpr=*/false); 14095 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 14096 } 14097 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 14098 CopyAssignOperator->markUsed(Context); 14099 14100 if (ASTMutationListener *L = getASTMutationListener()) { 14101 L->CompletedImplicitDefinition(CopyAssignOperator); 14102 } 14103 } 14104 14105 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 14106 assert(ClassDecl->needsImplicitMoveAssignment()); 14107 14108 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 14109 if (DSM.isAlreadyBeingDeclared()) 14110 return nullptr; 14111 14112 // Note: The following rules are largely analoguous to the move 14113 // constructor rules. 14114 14115 QualType ArgType = Context.getTypeDeclType(ClassDecl); 14116 LangAS AS = getDefaultCXXMethodAddrSpace(); 14117 if (AS != LangAS::Default) 14118 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 14119 QualType RetType = Context.getLValueReferenceType(ArgType); 14120 ArgType = Context.getRValueReferenceType(ArgType); 14121 14122 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14123 CXXMoveAssignment, 14124 false); 14125 14126 // An implicitly-declared move assignment operator is an inline public 14127 // member of its class. 14128 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 14129 SourceLocation ClassLoc = ClassDecl->getLocation(); 14130 DeclarationNameInfo NameInfo(Name, ClassLoc); 14131 CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create( 14132 Context, ClassDecl, ClassLoc, NameInfo, QualType(), 14133 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 14134 /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified, 14135 SourceLocation()); 14136 MoveAssignment->setAccess(AS_public); 14137 MoveAssignment->setDefaulted(); 14138 MoveAssignment->setImplicit(); 14139 14140 if (getLangOpts().CUDA) { 14141 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 14142 MoveAssignment, 14143 /* ConstRHS */ false, 14144 /* Diagnose */ false); 14145 } 14146 14147 // Build an exception specification pointing back at this member. 14148 FunctionProtoType::ExtProtoInfo EPI = 14149 getImplicitMethodEPI(*this, MoveAssignment); 14150 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 14151 14152 // Add the parameter to the operator. 14153 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 14154 ClassLoc, ClassLoc, 14155 /*Id=*/nullptr, ArgType, 14156 /*TInfo=*/nullptr, SC_None, 14157 nullptr); 14158 MoveAssignment->setParams(FromParam); 14159 14160 MoveAssignment->setTrivial( 14161 ClassDecl->needsOverloadResolutionForMoveAssignment() 14162 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 14163 : ClassDecl->hasTrivialMoveAssignment()); 14164 14165 // Note that we have added this copy-assignment operator. 14166 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared; 14167 14168 Scope *S = getScopeForContext(ClassDecl); 14169 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment); 14170 14171 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 14172 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 14173 SetDeclDeleted(MoveAssignment, ClassLoc); 14174 } 14175 14176 if (S) 14177 PushOnScopeChains(MoveAssignment, S, false); 14178 ClassDecl->addDecl(MoveAssignment); 14179 14180 return MoveAssignment; 14181 } 14182 14183 /// Check if we're implicitly defining a move assignment operator for a class 14184 /// with virtual bases. Such a move assignment might move-assign the virtual 14185 /// base multiple times. 14186 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 14187 SourceLocation CurrentLocation) { 14188 assert(!Class->isDependentContext() && "should not define dependent move"); 14189 14190 // Only a virtual base could get implicitly move-assigned multiple times. 14191 // Only a non-trivial move assignment can observe this. We only want to 14192 // diagnose if we implicitly define an assignment operator that assigns 14193 // two base classes, both of which move-assign the same virtual base. 14194 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 14195 Class->getNumBases() < 2) 14196 return; 14197 14198 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 14199 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 14200 VBaseMap VBases; 14201 14202 for (auto &BI : Class->bases()) { 14203 Worklist.push_back(&BI); 14204 while (!Worklist.empty()) { 14205 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 14206 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 14207 14208 // If the base has no non-trivial move assignment operators, 14209 // we don't care about moves from it. 14210 if (!Base->hasNonTrivialMoveAssignment()) 14211 continue; 14212 14213 // If there's nothing virtual here, skip it. 14214 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 14215 continue; 14216 14217 // If we're not actually going to call a move assignment for this base, 14218 // or the selected move assignment is trivial, skip it. 14219 Sema::SpecialMemberOverloadResult SMOR = 14220 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 14221 /*ConstArg*/false, /*VolatileArg*/false, 14222 /*RValueThis*/true, /*ConstThis*/false, 14223 /*VolatileThis*/false); 14224 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() || 14225 !SMOR.getMethod()->isMoveAssignmentOperator()) 14226 continue; 14227 14228 if (BaseSpec->isVirtual()) { 14229 // We're going to move-assign this virtual base, and its move 14230 // assignment operator is not trivial. If this can happen for 14231 // multiple distinct direct bases of Class, diagnose it. (If it 14232 // only happens in one base, we'll diagnose it when synthesizing 14233 // that base class's move assignment operator.) 14234 CXXBaseSpecifier *&Existing = 14235 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 14236 .first->second; 14237 if (Existing && Existing != &BI) { 14238 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 14239 << Class << Base; 14240 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here) 14241 << (Base->getCanonicalDecl() == 14242 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 14243 << Base << Existing->getType() << Existing->getSourceRange(); 14244 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here) 14245 << (Base->getCanonicalDecl() == 14246 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 14247 << Base << BI.getType() << BaseSpec->getSourceRange(); 14248 14249 // Only diagnose each vbase once. 14250 Existing = nullptr; 14251 } 14252 } else { 14253 // Only walk over bases that have defaulted move assignment operators. 14254 // We assume that any user-provided move assignment operator handles 14255 // the multiple-moves-of-vbase case itself somehow. 14256 if (!SMOR.getMethod()->isDefaulted()) 14257 continue; 14258 14259 // We're going to move the base classes of Base. Add them to the list. 14260 for (auto &BI : Base->bases()) 14261 Worklist.push_back(&BI); 14262 } 14263 } 14264 } 14265 } 14266 14267 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 14268 CXXMethodDecl *MoveAssignOperator) { 14269 assert((MoveAssignOperator->isDefaulted() && 14270 MoveAssignOperator->isOverloadedOperator() && 14271 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 14272 !MoveAssignOperator->doesThisDeclarationHaveABody() && 14273 !MoveAssignOperator->isDeleted()) && 14274 "DefineImplicitMoveAssignment called for wrong function"); 14275 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl()) 14276 return; 14277 14278 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 14279 if (ClassDecl->isInvalidDecl()) { 14280 MoveAssignOperator->setInvalidDecl(); 14281 return; 14282 } 14283 14284 // C++0x [class.copy]p28: 14285 // The implicitly-defined or move assignment operator for a non-union class 14286 // X performs memberwise move assignment of its subobjects. The direct base 14287 // classes of X are assigned first, in the order of their declaration in the 14288 // base-specifier-list, and then the immediate non-static data members of X 14289 // are assigned, in the order in which they were declared in the class 14290 // definition. 14291 14292 // Issue a warning if our implicit move assignment operator will move 14293 // from a virtual base more than once. 14294 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 14295 14296 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 14297 14298 // The exception specification is needed because we are defining the 14299 // function. 14300 ResolveExceptionSpec(CurrentLocation, 14301 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 14302 14303 // Add a context note for diagnostics produced after this point. 14304 Scope.addContextNote(CurrentLocation); 14305 14306 // The statements that form the synthesized function body. 14307 SmallVector<Stmt*, 8> Statements; 14308 14309 // The parameter for the "other" object, which we are move from. 14310 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 14311 QualType OtherRefType = 14312 Other->getType()->castAs<RValueReferenceType>()->getPointeeType(); 14313 14314 // Our location for everything implicitly-generated. 14315 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid() 14316 ? MoveAssignOperator->getEndLoc() 14317 : MoveAssignOperator->getLocation(); 14318 14319 // Builds a reference to the "other" object. 14320 RefBuilder OtherRef(Other, OtherRefType); 14321 // Cast to rvalue. 14322 MoveCastBuilder MoveOther(OtherRef); 14323 14324 // Builds the "this" pointer. 14325 ThisBuilder This; 14326 14327 // Assign base classes. 14328 bool Invalid = false; 14329 for (auto &Base : ClassDecl->bases()) { 14330 // C++11 [class.copy]p28: 14331 // It is unspecified whether subobjects representing virtual base classes 14332 // are assigned more than once by the implicitly-defined copy assignment 14333 // operator. 14334 // FIXME: Do not assign to a vbase that will be assigned by some other base 14335 // class. For a move-assignment, this can result in the vbase being moved 14336 // multiple times. 14337 14338 // Form the assignment: 14339 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 14340 QualType BaseType = Base.getType().getUnqualifiedType(); 14341 if (!BaseType->isRecordType()) { 14342 Invalid = true; 14343 continue; 14344 } 14345 14346 CXXCastPath BasePath; 14347 BasePath.push_back(&Base); 14348 14349 // Construct the "from" expression, which is an implicit cast to the 14350 // appropriately-qualified base type. 14351 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 14352 14353 // Dereference "this". 14354 DerefBuilder DerefThis(This); 14355 14356 // Implicitly cast "this" to the appropriately-qualified base type. 14357 CastBuilder To(DerefThis, 14358 Context.getQualifiedType( 14359 BaseType, MoveAssignOperator->getMethodQualifiers()), 14360 VK_LValue, BasePath); 14361 14362 // Build the move. 14363 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 14364 To, From, 14365 /*CopyingBaseSubobject=*/true, 14366 /*Copying=*/false); 14367 if (Move.isInvalid()) { 14368 MoveAssignOperator->setInvalidDecl(); 14369 return; 14370 } 14371 14372 // Success! Record the move. 14373 Statements.push_back(Move.getAs<Expr>()); 14374 } 14375 14376 // Assign non-static members. 14377 for (auto *Field : ClassDecl->fields()) { 14378 // FIXME: We should form some kind of AST representation for the implied 14379 // memcpy in a union copy operation. 14380 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 14381 continue; 14382 14383 if (Field->isInvalidDecl()) { 14384 Invalid = true; 14385 continue; 14386 } 14387 14388 // Check for members of reference type; we can't move those. 14389 if (Field->getType()->isReferenceType()) { 14390 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14391 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 14392 Diag(Field->getLocation(), diag::note_declared_at); 14393 Invalid = true; 14394 continue; 14395 } 14396 14397 // Check for members of const-qualified, non-class type. 14398 QualType BaseType = Context.getBaseElementType(Field->getType()); 14399 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 14400 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 14401 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 14402 Diag(Field->getLocation(), diag::note_declared_at); 14403 Invalid = true; 14404 continue; 14405 } 14406 14407 // Suppress assigning zero-width bitfields. 14408 if (Field->isZeroLengthBitField(Context)) 14409 continue; 14410 14411 QualType FieldType = Field->getType().getNonReferenceType(); 14412 if (FieldType->isIncompleteArrayType()) { 14413 assert(ClassDecl->hasFlexibleArrayMember() && 14414 "Incomplete array type is not valid"); 14415 continue; 14416 } 14417 14418 // Build references to the field in the object we're copying from and to. 14419 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 14420 LookupMemberName); 14421 MemberLookup.addDecl(Field); 14422 MemberLookup.resolveKind(); 14423 MemberBuilder From(MoveOther, OtherRefType, 14424 /*IsArrow=*/false, MemberLookup); 14425 MemberBuilder To(This, getCurrentThisType(), 14426 /*IsArrow=*/true, MemberLookup); 14427 14428 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 14429 "Member reference with rvalue base must be rvalue except for reference " 14430 "members, which aren't allowed for move assignment."); 14431 14432 // Build the move of this field. 14433 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 14434 To, From, 14435 /*CopyingBaseSubobject=*/false, 14436 /*Copying=*/false); 14437 if (Move.isInvalid()) { 14438 MoveAssignOperator->setInvalidDecl(); 14439 return; 14440 } 14441 14442 // Success! Record the copy. 14443 Statements.push_back(Move.getAs<Stmt>()); 14444 } 14445 14446 if (!Invalid) { 14447 // Add a "return *this;" 14448 ExprResult ThisObj = 14449 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 14450 14451 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 14452 if (Return.isInvalid()) 14453 Invalid = true; 14454 else 14455 Statements.push_back(Return.getAs<Stmt>()); 14456 } 14457 14458 if (Invalid) { 14459 MoveAssignOperator->setInvalidDecl(); 14460 return; 14461 } 14462 14463 StmtResult Body; 14464 { 14465 CompoundScopeRAII CompoundScope(*this); 14466 Body = ActOnCompoundStmt(Loc, Loc, Statements, 14467 /*isStmtExpr=*/false); 14468 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 14469 } 14470 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 14471 MoveAssignOperator->markUsed(Context); 14472 14473 if (ASTMutationListener *L = getASTMutationListener()) { 14474 L->CompletedImplicitDefinition(MoveAssignOperator); 14475 } 14476 } 14477 14478 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 14479 CXXRecordDecl *ClassDecl) { 14480 // C++ [class.copy]p4: 14481 // If the class definition does not explicitly declare a copy 14482 // constructor, one is declared implicitly. 14483 assert(ClassDecl->needsImplicitCopyConstructor()); 14484 14485 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 14486 if (DSM.isAlreadyBeingDeclared()) 14487 return nullptr; 14488 14489 QualType ClassType = Context.getTypeDeclType(ClassDecl); 14490 QualType ArgType = ClassType; 14491 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 14492 if (Const) 14493 ArgType = ArgType.withConst(); 14494 14495 LangAS AS = getDefaultCXXMethodAddrSpace(); 14496 if (AS != LangAS::Default) 14497 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 14498 14499 ArgType = Context.getLValueReferenceType(ArgType); 14500 14501 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14502 CXXCopyConstructor, 14503 Const); 14504 14505 DeclarationName Name 14506 = Context.DeclarationNames.getCXXConstructorName( 14507 Context.getCanonicalType(ClassType)); 14508 SourceLocation ClassLoc = ClassDecl->getLocation(); 14509 DeclarationNameInfo NameInfo(Name, ClassLoc); 14510 14511 // An implicitly-declared copy constructor is an inline public 14512 // member of its class. 14513 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 14514 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 14515 ExplicitSpecifier(), 14516 /*isInline=*/true, 14517 /*isImplicitlyDeclared=*/true, 14518 Constexpr ? CSK_constexpr : CSK_unspecified); 14519 CopyConstructor->setAccess(AS_public); 14520 CopyConstructor->setDefaulted(); 14521 14522 if (getLangOpts().CUDA) { 14523 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 14524 CopyConstructor, 14525 /* ConstRHS */ Const, 14526 /* Diagnose */ false); 14527 } 14528 14529 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType); 14530 14531 // Add the parameter to the constructor. 14532 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 14533 ClassLoc, ClassLoc, 14534 /*IdentifierInfo=*/nullptr, 14535 ArgType, /*TInfo=*/nullptr, 14536 SC_None, nullptr); 14537 CopyConstructor->setParams(FromParam); 14538 14539 CopyConstructor->setTrivial( 14540 ClassDecl->needsOverloadResolutionForCopyConstructor() 14541 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 14542 : ClassDecl->hasTrivialCopyConstructor()); 14543 14544 CopyConstructor->setTrivialForCall( 14545 ClassDecl->hasAttr<TrivialABIAttr>() || 14546 (ClassDecl->needsOverloadResolutionForCopyConstructor() 14547 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor, 14548 TAH_ConsiderTrivialABI) 14549 : ClassDecl->hasTrivialCopyConstructorForCall())); 14550 14551 // Note that we have declared this constructor. 14552 ++getASTContext().NumImplicitCopyConstructorsDeclared; 14553 14554 Scope *S = getScopeForContext(ClassDecl); 14555 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor); 14556 14557 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) { 14558 ClassDecl->setImplicitCopyConstructorIsDeleted(); 14559 SetDeclDeleted(CopyConstructor, ClassLoc); 14560 } 14561 14562 if (S) 14563 PushOnScopeChains(CopyConstructor, S, false); 14564 ClassDecl->addDecl(CopyConstructor); 14565 14566 return CopyConstructor; 14567 } 14568 14569 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 14570 CXXConstructorDecl *CopyConstructor) { 14571 assert((CopyConstructor->isDefaulted() && 14572 CopyConstructor->isCopyConstructor() && 14573 !CopyConstructor->doesThisDeclarationHaveABody() && 14574 !CopyConstructor->isDeleted()) && 14575 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 14576 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl()) 14577 return; 14578 14579 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 14580 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 14581 14582 SynthesizedFunctionScope Scope(*this, CopyConstructor); 14583 14584 // The exception specification is needed because we are defining the 14585 // function. 14586 ResolveExceptionSpec(CurrentLocation, 14587 CopyConstructor->getType()->castAs<FunctionProtoType>()); 14588 MarkVTableUsed(CurrentLocation, ClassDecl); 14589 14590 // Add a context note for diagnostics produced after this point. 14591 Scope.addContextNote(CurrentLocation); 14592 14593 // C++11 [class.copy]p7: 14594 // The [definition of an implicitly declared copy constructor] is 14595 // deprecated if the class has a user-declared copy assignment operator 14596 // or a user-declared destructor. 14597 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 14598 diagnoseDeprecatedCopyOperation(*this, CopyConstructor); 14599 14600 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) { 14601 CopyConstructor->setInvalidDecl(); 14602 } else { 14603 SourceLocation Loc = CopyConstructor->getEndLoc().isValid() 14604 ? CopyConstructor->getEndLoc() 14605 : CopyConstructor->getLocation(); 14606 Sema::CompoundScopeRAII CompoundScope(*this); 14607 CopyConstructor->setBody( 14608 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 14609 CopyConstructor->markUsed(Context); 14610 } 14611 14612 if (ASTMutationListener *L = getASTMutationListener()) { 14613 L->CompletedImplicitDefinition(CopyConstructor); 14614 } 14615 } 14616 14617 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 14618 CXXRecordDecl *ClassDecl) { 14619 assert(ClassDecl->needsImplicitMoveConstructor()); 14620 14621 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 14622 if (DSM.isAlreadyBeingDeclared()) 14623 return nullptr; 14624 14625 QualType ClassType = Context.getTypeDeclType(ClassDecl); 14626 14627 QualType ArgType = ClassType; 14628 LangAS AS = getDefaultCXXMethodAddrSpace(); 14629 if (AS != LangAS::Default) 14630 ArgType = Context.getAddrSpaceQualType(ClassType, AS); 14631 ArgType = Context.getRValueReferenceType(ArgType); 14632 14633 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14634 CXXMoveConstructor, 14635 false); 14636 14637 DeclarationName Name 14638 = Context.DeclarationNames.getCXXConstructorName( 14639 Context.getCanonicalType(ClassType)); 14640 SourceLocation ClassLoc = ClassDecl->getLocation(); 14641 DeclarationNameInfo NameInfo(Name, ClassLoc); 14642 14643 // C++11 [class.copy]p11: 14644 // An implicitly-declared copy/move constructor is an inline public 14645 // member of its class. 14646 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 14647 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 14648 ExplicitSpecifier(), 14649 /*isInline=*/true, 14650 /*isImplicitlyDeclared=*/true, 14651 Constexpr ? CSK_constexpr : CSK_unspecified); 14652 MoveConstructor->setAccess(AS_public); 14653 MoveConstructor->setDefaulted(); 14654 14655 if (getLangOpts().CUDA) { 14656 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 14657 MoveConstructor, 14658 /* ConstRHS */ false, 14659 /* Diagnose */ false); 14660 } 14661 14662 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType); 14663 14664 // Add the parameter to the constructor. 14665 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 14666 ClassLoc, ClassLoc, 14667 /*IdentifierInfo=*/nullptr, 14668 ArgType, /*TInfo=*/nullptr, 14669 SC_None, nullptr); 14670 MoveConstructor->setParams(FromParam); 14671 14672 MoveConstructor->setTrivial( 14673 ClassDecl->needsOverloadResolutionForMoveConstructor() 14674 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 14675 : ClassDecl->hasTrivialMoveConstructor()); 14676 14677 MoveConstructor->setTrivialForCall( 14678 ClassDecl->hasAttr<TrivialABIAttr>() || 14679 (ClassDecl->needsOverloadResolutionForMoveConstructor() 14680 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor, 14681 TAH_ConsiderTrivialABI) 14682 : ClassDecl->hasTrivialMoveConstructorForCall())); 14683 14684 // Note that we have declared this constructor. 14685 ++getASTContext().NumImplicitMoveConstructorsDeclared; 14686 14687 Scope *S = getScopeForContext(ClassDecl); 14688 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor); 14689 14690 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 14691 ClassDecl->setImplicitMoveConstructorIsDeleted(); 14692 SetDeclDeleted(MoveConstructor, ClassLoc); 14693 } 14694 14695 if (S) 14696 PushOnScopeChains(MoveConstructor, S, false); 14697 ClassDecl->addDecl(MoveConstructor); 14698 14699 return MoveConstructor; 14700 } 14701 14702 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 14703 CXXConstructorDecl *MoveConstructor) { 14704 assert((MoveConstructor->isDefaulted() && 14705 MoveConstructor->isMoveConstructor() && 14706 !MoveConstructor->doesThisDeclarationHaveABody() && 14707 !MoveConstructor->isDeleted()) && 14708 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 14709 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl()) 14710 return; 14711 14712 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 14713 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 14714 14715 SynthesizedFunctionScope Scope(*this, MoveConstructor); 14716 14717 // The exception specification is needed because we are defining the 14718 // function. 14719 ResolveExceptionSpec(CurrentLocation, 14720 MoveConstructor->getType()->castAs<FunctionProtoType>()); 14721 MarkVTableUsed(CurrentLocation, ClassDecl); 14722 14723 // Add a context note for diagnostics produced after this point. 14724 Scope.addContextNote(CurrentLocation); 14725 14726 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) { 14727 MoveConstructor->setInvalidDecl(); 14728 } else { 14729 SourceLocation Loc = MoveConstructor->getEndLoc().isValid() 14730 ? MoveConstructor->getEndLoc() 14731 : MoveConstructor->getLocation(); 14732 Sema::CompoundScopeRAII CompoundScope(*this); 14733 MoveConstructor->setBody(ActOnCompoundStmt( 14734 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 14735 MoveConstructor->markUsed(Context); 14736 } 14737 14738 if (ASTMutationListener *L = getASTMutationListener()) { 14739 L->CompletedImplicitDefinition(MoveConstructor); 14740 } 14741 } 14742 14743 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 14744 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 14745 } 14746 14747 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 14748 SourceLocation CurrentLocation, 14749 CXXConversionDecl *Conv) { 14750 SynthesizedFunctionScope Scope(*this, Conv); 14751 assert(!Conv->getReturnType()->isUndeducedType()); 14752 14753 CXXRecordDecl *Lambda = Conv->getParent(); 14754 FunctionDecl *CallOp = Lambda->getLambdaCallOperator(); 14755 FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(); 14756 14757 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) { 14758 CallOp = InstantiateFunctionDeclaration( 14759 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 14760 if (!CallOp) 14761 return; 14762 14763 Invoker = InstantiateFunctionDeclaration( 14764 Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 14765 if (!Invoker) 14766 return; 14767 } 14768 14769 if (CallOp->isInvalidDecl()) 14770 return; 14771 14772 // Mark the call operator referenced (and add to pending instantiations 14773 // if necessary). 14774 // For both the conversion and static-invoker template specializations 14775 // we construct their body's in this function, so no need to add them 14776 // to the PendingInstantiations. 14777 MarkFunctionReferenced(CurrentLocation, CallOp); 14778 14779 // Fill in the __invoke function with a dummy implementation. IR generation 14780 // will fill in the actual details. Update its type in case it contained 14781 // an 'auto'. 14782 Invoker->markUsed(Context); 14783 Invoker->setReferenced(); 14784 Invoker->setType(Conv->getReturnType()->getPointeeType()); 14785 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 14786 14787 // Construct the body of the conversion function { return __invoke; }. 14788 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 14789 VK_LValue, Conv->getLocation()); 14790 assert(FunctionRef && "Can't refer to __invoke function?"); 14791 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 14792 Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(), 14793 Conv->getLocation())); 14794 Conv->markUsed(Context); 14795 Conv->setReferenced(); 14796 14797 if (ASTMutationListener *L = getASTMutationListener()) { 14798 L->CompletedImplicitDefinition(Conv); 14799 L->CompletedImplicitDefinition(Invoker); 14800 } 14801 } 14802 14803 14804 14805 void Sema::DefineImplicitLambdaToBlockPointerConversion( 14806 SourceLocation CurrentLocation, 14807 CXXConversionDecl *Conv) 14808 { 14809 assert(!Conv->getParent()->isGenericLambda()); 14810 14811 SynthesizedFunctionScope Scope(*this, Conv); 14812 14813 // Copy-initialize the lambda object as needed to capture it. 14814 Expr *This = ActOnCXXThis(CurrentLocation).get(); 14815 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 14816 14817 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 14818 Conv->getLocation(), 14819 Conv, DerefThis); 14820 14821 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 14822 // behavior. Note that only the general conversion function does this 14823 // (since it's unusable otherwise); in the case where we inline the 14824 // block literal, it has block literal lifetime semantics. 14825 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 14826 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 14827 CK_CopyAndAutoreleaseBlockObject, 14828 BuildBlock.get(), nullptr, VK_RValue); 14829 14830 if (BuildBlock.isInvalid()) { 14831 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 14832 Conv->setInvalidDecl(); 14833 return; 14834 } 14835 14836 // Create the return statement that returns the block from the conversion 14837 // function. 14838 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 14839 if (Return.isInvalid()) { 14840 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 14841 Conv->setInvalidDecl(); 14842 return; 14843 } 14844 14845 // Set the body of the conversion function. 14846 Stmt *ReturnS = Return.get(); 14847 Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(), 14848 Conv->getLocation())); 14849 Conv->markUsed(Context); 14850 14851 // We're done; notify the mutation listener, if any. 14852 if (ASTMutationListener *L = getASTMutationListener()) { 14853 L->CompletedImplicitDefinition(Conv); 14854 } 14855 } 14856 14857 /// Determine whether the given list arguments contains exactly one 14858 /// "real" (non-default) argument. 14859 static bool hasOneRealArgument(MultiExprArg Args) { 14860 switch (Args.size()) { 14861 case 0: 14862 return false; 14863 14864 default: 14865 if (!Args[1]->isDefaultArgument()) 14866 return false; 14867 14868 LLVM_FALLTHROUGH; 14869 case 1: 14870 return !Args[0]->isDefaultArgument(); 14871 } 14872 14873 return false; 14874 } 14875 14876 ExprResult 14877 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 14878 NamedDecl *FoundDecl, 14879 CXXConstructorDecl *Constructor, 14880 MultiExprArg ExprArgs, 14881 bool HadMultipleCandidates, 14882 bool IsListInitialization, 14883 bool IsStdInitListInitialization, 14884 bool RequiresZeroInit, 14885 unsigned ConstructKind, 14886 SourceRange ParenRange) { 14887 bool Elidable = false; 14888 14889 // C++0x [class.copy]p34: 14890 // When certain criteria are met, an implementation is allowed to 14891 // omit the copy/move construction of a class object, even if the 14892 // copy/move constructor and/or destructor for the object have 14893 // side effects. [...] 14894 // - when a temporary class object that has not been bound to a 14895 // reference (12.2) would be copied/moved to a class object 14896 // with the same cv-unqualified type, the copy/move operation 14897 // can be omitted by constructing the temporary object 14898 // directly into the target of the omitted copy/move 14899 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor && 14900 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 14901 Expr *SubExpr = ExprArgs[0]; 14902 Elidable = SubExpr->isTemporaryObject( 14903 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 14904 } 14905 14906 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, 14907 FoundDecl, Constructor, 14908 Elidable, ExprArgs, HadMultipleCandidates, 14909 IsListInitialization, 14910 IsStdInitListInitialization, RequiresZeroInit, 14911 ConstructKind, ParenRange); 14912 } 14913 14914 ExprResult 14915 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 14916 NamedDecl *FoundDecl, 14917 CXXConstructorDecl *Constructor, 14918 bool Elidable, 14919 MultiExprArg ExprArgs, 14920 bool HadMultipleCandidates, 14921 bool IsListInitialization, 14922 bool IsStdInitListInitialization, 14923 bool RequiresZeroInit, 14924 unsigned ConstructKind, 14925 SourceRange ParenRange) { 14926 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) { 14927 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow); 14928 if (DiagnoseUseOfDecl(Constructor, ConstructLoc)) 14929 return ExprError(); 14930 } 14931 14932 return BuildCXXConstructExpr( 14933 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs, 14934 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 14935 RequiresZeroInit, ConstructKind, ParenRange); 14936 } 14937 14938 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 14939 /// including handling of its default argument expressions. 14940 ExprResult 14941 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 14942 CXXConstructorDecl *Constructor, 14943 bool Elidable, 14944 MultiExprArg ExprArgs, 14945 bool HadMultipleCandidates, 14946 bool IsListInitialization, 14947 bool IsStdInitListInitialization, 14948 bool RequiresZeroInit, 14949 unsigned ConstructKind, 14950 SourceRange ParenRange) { 14951 assert(declaresSameEntity( 14952 Constructor->getParent(), 14953 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && 14954 "given constructor for wrong type"); 14955 MarkFunctionReferenced(ConstructLoc, Constructor); 14956 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor)) 14957 return ExprError(); 14958 if (getLangOpts().SYCLIsDevice && 14959 !checkSYCLDeviceFunction(ConstructLoc, Constructor)) 14960 return ExprError(); 14961 14962 return CheckForImmediateInvocation( 14963 CXXConstructExpr::Create( 14964 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs, 14965 HadMultipleCandidates, IsListInitialization, 14966 IsStdInitListInitialization, RequiresZeroInit, 14967 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 14968 ParenRange), 14969 Constructor); 14970 } 14971 14972 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 14973 assert(Field->hasInClassInitializer()); 14974 14975 // If we already have the in-class initializer nothing needs to be done. 14976 if (Field->getInClassInitializer()) 14977 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext); 14978 14979 // If we might have already tried and failed to instantiate, don't try again. 14980 if (Field->isInvalidDecl()) 14981 return ExprError(); 14982 14983 // Maybe we haven't instantiated the in-class initializer. Go check the 14984 // pattern FieldDecl to see if it has one. 14985 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 14986 14987 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 14988 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 14989 DeclContext::lookup_result Lookup = 14990 ClassPattern->lookup(Field->getDeclName()); 14991 14992 // Lookup can return at most two results: the pattern for the field, or the 14993 // injected class name of the parent record. No other member can have the 14994 // same name as the field. 14995 // In modules mode, lookup can return multiple results (coming from 14996 // different modules). 14997 assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) && 14998 "more than two lookup results for field name"); 14999 FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]); 15000 if (!Pattern) { 15001 assert(isa<CXXRecordDecl>(Lookup[0]) && 15002 "cannot have other non-field member with same name"); 15003 for (auto L : Lookup) 15004 if (isa<FieldDecl>(L)) { 15005 Pattern = cast<FieldDecl>(L); 15006 break; 15007 } 15008 assert(Pattern && "We must have set the Pattern!"); 15009 } 15010 15011 if (!Pattern->hasInClassInitializer() || 15012 InstantiateInClassInitializer(Loc, Field, Pattern, 15013 getTemplateInstantiationArgs(Field))) { 15014 // Don't diagnose this again. 15015 Field->setInvalidDecl(); 15016 return ExprError(); 15017 } 15018 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext); 15019 } 15020 15021 // DR1351: 15022 // If the brace-or-equal-initializer of a non-static data member 15023 // invokes a defaulted default constructor of its class or of an 15024 // enclosing class in a potentially evaluated subexpression, the 15025 // program is ill-formed. 15026 // 15027 // This resolution is unworkable: the exception specification of the 15028 // default constructor can be needed in an unevaluated context, in 15029 // particular, in the operand of a noexcept-expression, and we can be 15030 // unable to compute an exception specification for an enclosed class. 15031 // 15032 // Any attempt to resolve the exception specification of a defaulted default 15033 // constructor before the initializer is lexically complete will ultimately 15034 // come here at which point we can diagnose it. 15035 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 15036 Diag(Loc, diag::err_in_class_initializer_not_yet_parsed) 15037 << OutermostClass << Field; 15038 Diag(Field->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed); 15039 // Recover by marking the field invalid, unless we're in a SFINAE context. 15040 if (!isSFINAEContext()) 15041 Field->setInvalidDecl(); 15042 return ExprError(); 15043 } 15044 15045 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 15046 if (VD->isInvalidDecl()) return; 15047 // If initializing the variable failed, don't also diagnose problems with 15048 // the desctructor, they're likely related. 15049 if (VD->getInit() && VD->getInit()->containsErrors()) 15050 return; 15051 15052 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 15053 if (ClassDecl->isInvalidDecl()) return; 15054 if (ClassDecl->hasIrrelevantDestructor()) return; 15055 if (ClassDecl->isDependentContext()) return; 15056 15057 if (VD->isNoDestroy(getASTContext())) 15058 return; 15059 15060 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 15061 15062 // If this is an array, we'll require the destructor during initialization, so 15063 // we can skip over this. We still want to emit exit-time destructor warnings 15064 // though. 15065 if (!VD->getType()->isArrayType()) { 15066 MarkFunctionReferenced(VD->getLocation(), Destructor); 15067 CheckDestructorAccess(VD->getLocation(), Destructor, 15068 PDiag(diag::err_access_dtor_var) 15069 << VD->getDeclName() << VD->getType()); 15070 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 15071 } 15072 15073 if (Destructor->isTrivial()) return; 15074 15075 // If the destructor is constexpr, check whether the variable has constant 15076 // destruction now. 15077 if (Destructor->isConstexpr()) { 15078 bool HasConstantInit = false; 15079 if (VD->getInit() && !VD->getInit()->isValueDependent()) 15080 HasConstantInit = VD->evaluateValue(); 15081 SmallVector<PartialDiagnosticAt, 8> Notes; 15082 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() && 15083 HasConstantInit) { 15084 Diag(VD->getLocation(), 15085 diag::err_constexpr_var_requires_const_destruction) << VD; 15086 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 15087 Diag(Notes[I].first, Notes[I].second); 15088 } 15089 } 15090 15091 if (!VD->hasGlobalStorage()) return; 15092 15093 // Emit warning for non-trivial dtor in global scope (a real global, 15094 // class-static, function-static). 15095 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 15096 15097 // TODO: this should be re-enabled for static locals by !CXAAtExit 15098 if (!VD->isStaticLocal()) 15099 Diag(VD->getLocation(), diag::warn_global_destructor); 15100 } 15101 15102 /// Given a constructor and the set of arguments provided for the 15103 /// constructor, convert the arguments and add any required default arguments 15104 /// to form a proper call to this constructor. 15105 /// 15106 /// \returns true if an error occurred, false otherwise. 15107 bool 15108 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 15109 MultiExprArg ArgsPtr, 15110 SourceLocation Loc, 15111 SmallVectorImpl<Expr*> &ConvertedArgs, 15112 bool AllowExplicit, 15113 bool IsListInitialization) { 15114 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 15115 unsigned NumArgs = ArgsPtr.size(); 15116 Expr **Args = ArgsPtr.data(); 15117 15118 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>(); 15119 unsigned NumParams = Proto->getNumParams(); 15120 15121 // If too few arguments are available, we'll fill in the rest with defaults. 15122 if (NumArgs < NumParams) 15123 ConvertedArgs.reserve(NumParams); 15124 else 15125 ConvertedArgs.reserve(NumArgs); 15126 15127 VariadicCallType CallType = 15128 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 15129 SmallVector<Expr *, 8> AllArgs; 15130 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 15131 Proto, 0, 15132 llvm::makeArrayRef(Args, NumArgs), 15133 AllArgs, 15134 CallType, AllowExplicit, 15135 IsListInitialization); 15136 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 15137 15138 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 15139 15140 CheckConstructorCall(Constructor, 15141 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 15142 Proto, Loc); 15143 15144 return Invalid; 15145 } 15146 15147 static inline bool 15148 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 15149 const FunctionDecl *FnDecl) { 15150 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 15151 if (isa<NamespaceDecl>(DC)) { 15152 return SemaRef.Diag(FnDecl->getLocation(), 15153 diag::err_operator_new_delete_declared_in_namespace) 15154 << FnDecl->getDeclName(); 15155 } 15156 15157 if (isa<TranslationUnitDecl>(DC) && 15158 FnDecl->getStorageClass() == SC_Static) { 15159 return SemaRef.Diag(FnDecl->getLocation(), 15160 diag::err_operator_new_delete_declared_static) 15161 << FnDecl->getDeclName(); 15162 } 15163 15164 return false; 15165 } 15166 15167 static QualType 15168 RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) { 15169 QualType QTy = PtrTy->getPointeeType(); 15170 QTy = SemaRef.Context.removeAddrSpaceQualType(QTy); 15171 return SemaRef.Context.getPointerType(QTy); 15172 } 15173 15174 static inline bool 15175 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 15176 CanQualType ExpectedResultType, 15177 CanQualType ExpectedFirstParamType, 15178 unsigned DependentParamTypeDiag, 15179 unsigned InvalidParamTypeDiag) { 15180 QualType ResultType = 15181 FnDecl->getType()->castAs<FunctionType>()->getReturnType(); 15182 15183 // Check that the result type is not dependent. 15184 if (ResultType->isDependentType()) 15185 return SemaRef.Diag(FnDecl->getLocation(), 15186 diag::err_operator_new_delete_dependent_result_type) 15187 << FnDecl->getDeclName() << ExpectedResultType; 15188 15189 // The operator is valid on any address space for OpenCL. 15190 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 15191 if (auto *PtrTy = ResultType->getAs<PointerType>()) { 15192 ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 15193 } 15194 } 15195 15196 // Check that the result type is what we expect. 15197 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 15198 return SemaRef.Diag(FnDecl->getLocation(), 15199 diag::err_operator_new_delete_invalid_result_type) 15200 << FnDecl->getDeclName() << ExpectedResultType; 15201 15202 // A function template must have at least 2 parameters. 15203 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 15204 return SemaRef.Diag(FnDecl->getLocation(), 15205 diag::err_operator_new_delete_template_too_few_parameters) 15206 << FnDecl->getDeclName(); 15207 15208 // The function decl must have at least 1 parameter. 15209 if (FnDecl->getNumParams() == 0) 15210 return SemaRef.Diag(FnDecl->getLocation(), 15211 diag::err_operator_new_delete_too_few_parameters) 15212 << FnDecl->getDeclName(); 15213 15214 // Check the first parameter type is not dependent. 15215 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 15216 if (FirstParamType->isDependentType()) 15217 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 15218 << FnDecl->getDeclName() << ExpectedFirstParamType; 15219 15220 // Check that the first parameter type is what we expect. 15221 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 15222 // The operator is valid on any address space for OpenCL. 15223 if (auto *PtrTy = 15224 FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) { 15225 FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 15226 } 15227 } 15228 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 15229 ExpectedFirstParamType) 15230 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 15231 << FnDecl->getDeclName() << ExpectedFirstParamType; 15232 15233 return false; 15234 } 15235 15236 static bool 15237 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 15238 // C++ [basic.stc.dynamic.allocation]p1: 15239 // A program is ill-formed if an allocation function is declared in a 15240 // namespace scope other than global scope or declared static in global 15241 // scope. 15242 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 15243 return true; 15244 15245 CanQualType SizeTy = 15246 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 15247 15248 // C++ [basic.stc.dynamic.allocation]p1: 15249 // The return type shall be void*. The first parameter shall have type 15250 // std::size_t. 15251 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 15252 SizeTy, 15253 diag::err_operator_new_dependent_param_type, 15254 diag::err_operator_new_param_type)) 15255 return true; 15256 15257 // C++ [basic.stc.dynamic.allocation]p1: 15258 // The first parameter shall not have an associated default argument. 15259 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 15260 return SemaRef.Diag(FnDecl->getLocation(), 15261 diag::err_operator_new_default_arg) 15262 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 15263 15264 return false; 15265 } 15266 15267 static bool 15268 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 15269 // C++ [basic.stc.dynamic.deallocation]p1: 15270 // A program is ill-formed if deallocation functions are declared in a 15271 // namespace scope other than global scope or declared static in global 15272 // scope. 15273 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 15274 return true; 15275 15276 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl); 15277 15278 // C++ P0722: 15279 // Within a class C, the first parameter of a destroying operator delete 15280 // shall be of type C *. The first parameter of any other deallocation 15281 // function shall be of type void *. 15282 CanQualType ExpectedFirstParamType = 15283 MD && MD->isDestroyingOperatorDelete() 15284 ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType( 15285 SemaRef.Context.getRecordType(MD->getParent()))) 15286 : SemaRef.Context.VoidPtrTy; 15287 15288 // C++ [basic.stc.dynamic.deallocation]p2: 15289 // Each deallocation function shall return void 15290 if (CheckOperatorNewDeleteTypes( 15291 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType, 15292 diag::err_operator_delete_dependent_param_type, 15293 diag::err_operator_delete_param_type)) 15294 return true; 15295 15296 // C++ P0722: 15297 // A destroying operator delete shall be a usual deallocation function. 15298 if (MD && !MD->getParent()->isDependentContext() && 15299 MD->isDestroyingOperatorDelete() && 15300 !SemaRef.isUsualDeallocationFunction(MD)) { 15301 SemaRef.Diag(MD->getLocation(), 15302 diag::err_destroying_operator_delete_not_usual); 15303 return true; 15304 } 15305 15306 return false; 15307 } 15308 15309 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 15310 /// of this overloaded operator is well-formed. If so, returns false; 15311 /// otherwise, emits appropriate diagnostics and returns true. 15312 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 15313 assert(FnDecl && FnDecl->isOverloadedOperator() && 15314 "Expected an overloaded operator declaration"); 15315 15316 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 15317 15318 // C++ [over.oper]p5: 15319 // The allocation and deallocation functions, operator new, 15320 // operator new[], operator delete and operator delete[], are 15321 // described completely in 3.7.3. The attributes and restrictions 15322 // found in the rest of this subclause do not apply to them unless 15323 // explicitly stated in 3.7.3. 15324 if (Op == OO_Delete || Op == OO_Array_Delete) 15325 return CheckOperatorDeleteDeclaration(*this, FnDecl); 15326 15327 if (Op == OO_New || Op == OO_Array_New) 15328 return CheckOperatorNewDeclaration(*this, FnDecl); 15329 15330 // C++ [over.oper]p6: 15331 // An operator function shall either be a non-static member 15332 // function or be a non-member function and have at least one 15333 // parameter whose type is a class, a reference to a class, an 15334 // enumeration, or a reference to an enumeration. 15335 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 15336 if (MethodDecl->isStatic()) 15337 return Diag(FnDecl->getLocation(), 15338 diag::err_operator_overload_static) << FnDecl->getDeclName(); 15339 } else { 15340 bool ClassOrEnumParam = false; 15341 for (auto Param : FnDecl->parameters()) { 15342 QualType ParamType = Param->getType().getNonReferenceType(); 15343 if (ParamType->isDependentType() || ParamType->isRecordType() || 15344 ParamType->isEnumeralType()) { 15345 ClassOrEnumParam = true; 15346 break; 15347 } 15348 } 15349 15350 if (!ClassOrEnumParam) 15351 return Diag(FnDecl->getLocation(), 15352 diag::err_operator_overload_needs_class_or_enum) 15353 << FnDecl->getDeclName(); 15354 } 15355 15356 // C++ [over.oper]p8: 15357 // An operator function cannot have default arguments (8.3.6), 15358 // except where explicitly stated below. 15359 // 15360 // Only the function-call operator allows default arguments 15361 // (C++ [over.call]p1). 15362 if (Op != OO_Call) { 15363 for (auto Param : FnDecl->parameters()) { 15364 if (Param->hasDefaultArg()) 15365 return Diag(Param->getLocation(), 15366 diag::err_operator_overload_default_arg) 15367 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 15368 } 15369 } 15370 15371 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 15372 { false, false, false } 15373 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 15374 , { Unary, Binary, MemberOnly } 15375 #include "clang/Basic/OperatorKinds.def" 15376 }; 15377 15378 bool CanBeUnaryOperator = OperatorUses[Op][0]; 15379 bool CanBeBinaryOperator = OperatorUses[Op][1]; 15380 bool MustBeMemberOperator = OperatorUses[Op][2]; 15381 15382 // C++ [over.oper]p8: 15383 // [...] Operator functions cannot have more or fewer parameters 15384 // than the number required for the corresponding operator, as 15385 // described in the rest of this subclause. 15386 unsigned NumParams = FnDecl->getNumParams() 15387 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 15388 if (Op != OO_Call && 15389 ((NumParams == 1 && !CanBeUnaryOperator) || 15390 (NumParams == 2 && !CanBeBinaryOperator) || 15391 (NumParams < 1) || (NumParams > 2))) { 15392 // We have the wrong number of parameters. 15393 unsigned ErrorKind; 15394 if (CanBeUnaryOperator && CanBeBinaryOperator) { 15395 ErrorKind = 2; // 2 -> unary or binary. 15396 } else if (CanBeUnaryOperator) { 15397 ErrorKind = 0; // 0 -> unary 15398 } else { 15399 assert(CanBeBinaryOperator && 15400 "All non-call overloaded operators are unary or binary!"); 15401 ErrorKind = 1; // 1 -> binary 15402 } 15403 15404 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 15405 << FnDecl->getDeclName() << NumParams << ErrorKind; 15406 } 15407 15408 // Overloaded operators other than operator() cannot be variadic. 15409 if (Op != OO_Call && 15410 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) { 15411 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 15412 << FnDecl->getDeclName(); 15413 } 15414 15415 // Some operators must be non-static member functions. 15416 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 15417 return Diag(FnDecl->getLocation(), 15418 diag::err_operator_overload_must_be_member) 15419 << FnDecl->getDeclName(); 15420 } 15421 15422 // C++ [over.inc]p1: 15423 // The user-defined function called operator++ implements the 15424 // prefix and postfix ++ operator. If this function is a member 15425 // function with no parameters, or a non-member function with one 15426 // parameter of class or enumeration type, it defines the prefix 15427 // increment operator ++ for objects of that type. If the function 15428 // is a member function with one parameter (which shall be of type 15429 // int) or a non-member function with two parameters (the second 15430 // of which shall be of type int), it defines the postfix 15431 // increment operator ++ for objects of that type. 15432 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 15433 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 15434 QualType ParamType = LastParam->getType(); 15435 15436 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 15437 !ParamType->isDependentType()) 15438 return Diag(LastParam->getLocation(), 15439 diag::err_operator_overload_post_incdec_must_be_int) 15440 << LastParam->getType() << (Op == OO_MinusMinus); 15441 } 15442 15443 return false; 15444 } 15445 15446 static bool 15447 checkLiteralOperatorTemplateParameterList(Sema &SemaRef, 15448 FunctionTemplateDecl *TpDecl) { 15449 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters(); 15450 15451 // Must have one or two template parameters. 15452 if (TemplateParams->size() == 1) { 15453 NonTypeTemplateParmDecl *PmDecl = 15454 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0)); 15455 15456 // The template parameter must be a char parameter pack. 15457 if (PmDecl && PmDecl->isTemplateParameterPack() && 15458 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy)) 15459 return false; 15460 15461 } else if (TemplateParams->size() == 2) { 15462 TemplateTypeParmDecl *PmType = 15463 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0)); 15464 NonTypeTemplateParmDecl *PmArgs = 15465 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1)); 15466 15467 // The second template parameter must be a parameter pack with the 15468 // first template parameter as its type. 15469 if (PmType && PmArgs && !PmType->isTemplateParameterPack() && 15470 PmArgs->isTemplateParameterPack()) { 15471 const TemplateTypeParmType *TArgs = 15472 PmArgs->getType()->getAs<TemplateTypeParmType>(); 15473 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 15474 TArgs->getIndex() == PmType->getIndex()) { 15475 if (!SemaRef.inTemplateInstantiation()) 15476 SemaRef.Diag(TpDecl->getLocation(), 15477 diag::ext_string_literal_operator_template); 15478 return false; 15479 } 15480 } 15481 } 15482 15483 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(), 15484 diag::err_literal_operator_template) 15485 << TpDecl->getTemplateParameters()->getSourceRange(); 15486 return true; 15487 } 15488 15489 /// CheckLiteralOperatorDeclaration - Check whether the declaration 15490 /// of this literal operator function is well-formed. If so, returns 15491 /// false; otherwise, emits appropriate diagnostics and returns true. 15492 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 15493 if (isa<CXXMethodDecl>(FnDecl)) { 15494 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 15495 << FnDecl->getDeclName(); 15496 return true; 15497 } 15498 15499 if (FnDecl->isExternC()) { 15500 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 15501 if (const LinkageSpecDecl *LSD = 15502 FnDecl->getDeclContext()->getExternCContext()) 15503 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here); 15504 return true; 15505 } 15506 15507 // This might be the definition of a literal operator template. 15508 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 15509 15510 // This might be a specialization of a literal operator template. 15511 if (!TpDecl) 15512 TpDecl = FnDecl->getPrimaryTemplate(); 15513 15514 // template <char...> type operator "" name() and 15515 // template <class T, T...> type operator "" name() are the only valid 15516 // template signatures, and the only valid signatures with no parameters. 15517 if (TpDecl) { 15518 if (FnDecl->param_size() != 0) { 15519 Diag(FnDecl->getLocation(), 15520 diag::err_literal_operator_template_with_params); 15521 return true; 15522 } 15523 15524 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl)) 15525 return true; 15526 15527 } else if (FnDecl->param_size() == 1) { 15528 const ParmVarDecl *Param = FnDecl->getParamDecl(0); 15529 15530 QualType ParamType = Param->getType().getUnqualifiedType(); 15531 15532 // Only unsigned long long int, long double, any character type, and const 15533 // char * are allowed as the only parameters. 15534 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) || 15535 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) || 15536 Context.hasSameType(ParamType, Context.CharTy) || 15537 Context.hasSameType(ParamType, Context.WideCharTy) || 15538 Context.hasSameType(ParamType, Context.Char8Ty) || 15539 Context.hasSameType(ParamType, Context.Char16Ty) || 15540 Context.hasSameType(ParamType, Context.Char32Ty)) { 15541 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) { 15542 QualType InnerType = Ptr->getPointeeType(); 15543 15544 // Pointer parameter must be a const char *. 15545 if (!(Context.hasSameType(InnerType.getUnqualifiedType(), 15546 Context.CharTy) && 15547 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) { 15548 Diag(Param->getSourceRange().getBegin(), 15549 diag::err_literal_operator_param) 15550 << ParamType << "'const char *'" << Param->getSourceRange(); 15551 return true; 15552 } 15553 15554 } else if (ParamType->isRealFloatingType()) { 15555 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 15556 << ParamType << Context.LongDoubleTy << Param->getSourceRange(); 15557 return true; 15558 15559 } else if (ParamType->isIntegerType()) { 15560 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 15561 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange(); 15562 return true; 15563 15564 } else { 15565 Diag(Param->getSourceRange().getBegin(), 15566 diag::err_literal_operator_invalid_param) 15567 << ParamType << Param->getSourceRange(); 15568 return true; 15569 } 15570 15571 } else if (FnDecl->param_size() == 2) { 15572 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 15573 15574 // First, verify that the first parameter is correct. 15575 15576 QualType FirstParamType = (*Param)->getType().getUnqualifiedType(); 15577 15578 // Two parameter function must have a pointer to const as a 15579 // first parameter; let's strip those qualifiers. 15580 const PointerType *PT = FirstParamType->getAs<PointerType>(); 15581 15582 if (!PT) { 15583 Diag((*Param)->getSourceRange().getBegin(), 15584 diag::err_literal_operator_param) 15585 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 15586 return true; 15587 } 15588 15589 QualType PointeeType = PT->getPointeeType(); 15590 // First parameter must be const 15591 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) { 15592 Diag((*Param)->getSourceRange().getBegin(), 15593 diag::err_literal_operator_param) 15594 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 15595 return true; 15596 } 15597 15598 QualType InnerType = PointeeType.getUnqualifiedType(); 15599 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and 15600 // const char32_t* are allowed as the first parameter to a two-parameter 15601 // function 15602 if (!(Context.hasSameType(InnerType, Context.CharTy) || 15603 Context.hasSameType(InnerType, Context.WideCharTy) || 15604 Context.hasSameType(InnerType, Context.Char8Ty) || 15605 Context.hasSameType(InnerType, Context.Char16Ty) || 15606 Context.hasSameType(InnerType, Context.Char32Ty))) { 15607 Diag((*Param)->getSourceRange().getBegin(), 15608 diag::err_literal_operator_param) 15609 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 15610 return true; 15611 } 15612 15613 // Move on to the second and final parameter. 15614 ++Param; 15615 15616 // The second parameter must be a std::size_t. 15617 QualType SecondParamType = (*Param)->getType().getUnqualifiedType(); 15618 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) { 15619 Diag((*Param)->getSourceRange().getBegin(), 15620 diag::err_literal_operator_param) 15621 << SecondParamType << Context.getSizeType() 15622 << (*Param)->getSourceRange(); 15623 return true; 15624 } 15625 } else { 15626 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count); 15627 return true; 15628 } 15629 15630 // Parameters are good. 15631 15632 // A parameter-declaration-clause containing a default argument is not 15633 // equivalent to any of the permitted forms. 15634 for (auto Param : FnDecl->parameters()) { 15635 if (Param->hasDefaultArg()) { 15636 Diag(Param->getDefaultArgRange().getBegin(), 15637 diag::err_literal_operator_default_argument) 15638 << Param->getDefaultArgRange(); 15639 break; 15640 } 15641 } 15642 15643 StringRef LiteralName 15644 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 15645 if (LiteralName[0] != '_' && 15646 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) { 15647 // C++11 [usrlit.suffix]p1: 15648 // Literal suffix identifiers that do not start with an underscore 15649 // are reserved for future standardization. 15650 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 15651 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 15652 } 15653 15654 return false; 15655 } 15656 15657 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 15658 /// linkage specification, including the language and (if present) 15659 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 15660 /// language string literal. LBraceLoc, if valid, provides the location of 15661 /// the '{' brace. Otherwise, this linkage specification does not 15662 /// have any braces. 15663 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 15664 Expr *LangStr, 15665 SourceLocation LBraceLoc) { 15666 StringLiteral *Lit = cast<StringLiteral>(LangStr); 15667 if (!Lit->isAscii()) { 15668 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 15669 << LangStr->getSourceRange(); 15670 return nullptr; 15671 } 15672 15673 StringRef Lang = Lit->getString(); 15674 LinkageSpecDecl::LanguageIDs Language; 15675 if (Lang == "C") 15676 Language = LinkageSpecDecl::lang_c; 15677 else if (Lang == "C++") 15678 Language = LinkageSpecDecl::lang_cxx; 15679 else { 15680 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 15681 << LangStr->getSourceRange(); 15682 return nullptr; 15683 } 15684 15685 // FIXME: Add all the various semantics of linkage specifications 15686 15687 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 15688 LangStr->getExprLoc(), Language, 15689 LBraceLoc.isValid()); 15690 CurContext->addDecl(D); 15691 PushDeclContext(S, D); 15692 return D; 15693 } 15694 15695 /// ActOnFinishLinkageSpecification - Complete the definition of 15696 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 15697 /// valid, it's the position of the closing '}' brace in a linkage 15698 /// specification that uses braces. 15699 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 15700 Decl *LinkageSpec, 15701 SourceLocation RBraceLoc) { 15702 if (RBraceLoc.isValid()) { 15703 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 15704 LSDecl->setRBraceLoc(RBraceLoc); 15705 } 15706 PopDeclContext(); 15707 return LinkageSpec; 15708 } 15709 15710 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 15711 const ParsedAttributesView &AttrList, 15712 SourceLocation SemiLoc) { 15713 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 15714 // Attribute declarations appertain to empty declaration so we handle 15715 // them here. 15716 ProcessDeclAttributeList(S, ED, AttrList); 15717 15718 CurContext->addDecl(ED); 15719 return ED; 15720 } 15721 15722 /// Perform semantic analysis for the variable declaration that 15723 /// occurs within a C++ catch clause, returning the newly-created 15724 /// variable. 15725 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 15726 TypeSourceInfo *TInfo, 15727 SourceLocation StartLoc, 15728 SourceLocation Loc, 15729 IdentifierInfo *Name) { 15730 bool Invalid = false; 15731 QualType ExDeclType = TInfo->getType(); 15732 15733 // Arrays and functions decay. 15734 if (ExDeclType->isArrayType()) 15735 ExDeclType = Context.getArrayDecayedType(ExDeclType); 15736 else if (ExDeclType->isFunctionType()) 15737 ExDeclType = Context.getPointerType(ExDeclType); 15738 15739 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 15740 // The exception-declaration shall not denote a pointer or reference to an 15741 // incomplete type, other than [cv] void*. 15742 // N2844 forbids rvalue references. 15743 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 15744 Diag(Loc, diag::err_catch_rvalue_ref); 15745 Invalid = true; 15746 } 15747 15748 if (ExDeclType->isVariablyModifiedType()) { 15749 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType; 15750 Invalid = true; 15751 } 15752 15753 QualType BaseType = ExDeclType; 15754 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 15755 unsigned DK = diag::err_catch_incomplete; 15756 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 15757 BaseType = Ptr->getPointeeType(); 15758 Mode = 1; 15759 DK = diag::err_catch_incomplete_ptr; 15760 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 15761 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 15762 BaseType = Ref->getPointeeType(); 15763 Mode = 2; 15764 DK = diag::err_catch_incomplete_ref; 15765 } 15766 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 15767 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 15768 Invalid = true; 15769 15770 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) { 15771 Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType; 15772 Invalid = true; 15773 } 15774 15775 if (!Invalid && !ExDeclType->isDependentType() && 15776 RequireNonAbstractType(Loc, ExDeclType, 15777 diag::err_abstract_type_in_decl, 15778 AbstractVariableType)) 15779 Invalid = true; 15780 15781 // Only the non-fragile NeXT runtime currently supports C++ catches 15782 // of ObjC types, and no runtime supports catching ObjC types by value. 15783 if (!Invalid && getLangOpts().ObjC) { 15784 QualType T = ExDeclType; 15785 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 15786 T = RT->getPointeeType(); 15787 15788 if (T->isObjCObjectType()) { 15789 Diag(Loc, diag::err_objc_object_catch); 15790 Invalid = true; 15791 } else if (T->isObjCObjectPointerType()) { 15792 // FIXME: should this be a test for macosx-fragile specifically? 15793 if (getLangOpts().ObjCRuntime.isFragile()) 15794 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 15795 } 15796 } 15797 15798 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 15799 ExDeclType, TInfo, SC_None); 15800 ExDecl->setExceptionVariable(true); 15801 15802 // In ARC, infer 'retaining' for variables of retainable type. 15803 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 15804 Invalid = true; 15805 15806 if (!Invalid && !ExDeclType->isDependentType()) { 15807 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 15808 // Insulate this from anything else we might currently be parsing. 15809 EnterExpressionEvaluationContext scope( 15810 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 15811 15812 // C++ [except.handle]p16: 15813 // The object declared in an exception-declaration or, if the 15814 // exception-declaration does not specify a name, a temporary (12.2) is 15815 // copy-initialized (8.5) from the exception object. [...] 15816 // The object is destroyed when the handler exits, after the destruction 15817 // of any automatic objects initialized within the handler. 15818 // 15819 // We just pretend to initialize the object with itself, then make sure 15820 // it can be destroyed later. 15821 QualType initType = Context.getExceptionObjectType(ExDeclType); 15822 15823 InitializedEntity entity = 15824 InitializedEntity::InitializeVariable(ExDecl); 15825 InitializationKind initKind = 15826 InitializationKind::CreateCopy(Loc, SourceLocation()); 15827 15828 Expr *opaqueValue = 15829 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 15830 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 15831 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 15832 if (result.isInvalid()) 15833 Invalid = true; 15834 else { 15835 // If the constructor used was non-trivial, set this as the 15836 // "initializer". 15837 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 15838 if (!construct->getConstructor()->isTrivial()) { 15839 Expr *init = MaybeCreateExprWithCleanups(construct); 15840 ExDecl->setInit(init); 15841 } 15842 15843 // And make sure it's destructable. 15844 FinalizeVarWithDestructor(ExDecl, recordType); 15845 } 15846 } 15847 } 15848 15849 if (Invalid) 15850 ExDecl->setInvalidDecl(); 15851 15852 return ExDecl; 15853 } 15854 15855 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 15856 /// handler. 15857 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 15858 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 15859 bool Invalid = D.isInvalidType(); 15860 15861 // Check for unexpanded parameter packs. 15862 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 15863 UPPC_ExceptionType)) { 15864 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 15865 D.getIdentifierLoc()); 15866 Invalid = true; 15867 } 15868 15869 IdentifierInfo *II = D.getIdentifier(); 15870 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 15871 LookupOrdinaryName, 15872 ForVisibleRedeclaration)) { 15873 // The scope should be freshly made just for us. There is just no way 15874 // it contains any previous declaration, except for function parameters in 15875 // a function-try-block's catch statement. 15876 assert(!S->isDeclScope(PrevDecl)); 15877 if (isDeclInScope(PrevDecl, CurContext, S)) { 15878 Diag(D.getIdentifierLoc(), diag::err_redefinition) 15879 << D.getIdentifier(); 15880 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 15881 Invalid = true; 15882 } else if (PrevDecl->isTemplateParameter()) 15883 // Maybe we will complain about the shadowed template parameter. 15884 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 15885 } 15886 15887 if (D.getCXXScopeSpec().isSet() && !Invalid) { 15888 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 15889 << D.getCXXScopeSpec().getRange(); 15890 Invalid = true; 15891 } 15892 15893 VarDecl *ExDecl = BuildExceptionDeclaration( 15894 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier()); 15895 if (Invalid) 15896 ExDecl->setInvalidDecl(); 15897 15898 // Add the exception declaration into this scope. 15899 if (II) 15900 PushOnScopeChains(ExDecl, S); 15901 else 15902 CurContext->addDecl(ExDecl); 15903 15904 ProcessDeclAttributes(S, ExDecl, D); 15905 return ExDecl; 15906 } 15907 15908 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 15909 Expr *AssertExpr, 15910 Expr *AssertMessageExpr, 15911 SourceLocation RParenLoc) { 15912 StringLiteral *AssertMessage = 15913 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 15914 15915 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 15916 return nullptr; 15917 15918 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 15919 AssertMessage, RParenLoc, false); 15920 } 15921 15922 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 15923 Expr *AssertExpr, 15924 StringLiteral *AssertMessage, 15925 SourceLocation RParenLoc, 15926 bool Failed) { 15927 assert(AssertExpr != nullptr && "Expected non-null condition"); 15928 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 15929 !Failed) { 15930 // In a static_assert-declaration, the constant-expression shall be a 15931 // constant expression that can be contextually converted to bool. 15932 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 15933 if (Converted.isInvalid()) 15934 Failed = true; 15935 15936 ExprResult FullAssertExpr = 15937 ActOnFinishFullExpr(Converted.get(), StaticAssertLoc, 15938 /*DiscardedValue*/ false, 15939 /*IsConstexpr*/ true); 15940 if (FullAssertExpr.isInvalid()) 15941 Failed = true; 15942 else 15943 AssertExpr = FullAssertExpr.get(); 15944 15945 llvm::APSInt Cond; 15946 if (!Failed && VerifyIntegerConstantExpression(AssertExpr, &Cond, 15947 diag::err_static_assert_expression_is_not_constant, 15948 /*AllowFold=*/false).isInvalid()) 15949 Failed = true; 15950 15951 if (!Failed && !Cond) { 15952 SmallString<256> MsgBuffer; 15953 llvm::raw_svector_ostream Msg(MsgBuffer); 15954 if (AssertMessage) 15955 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 15956 15957 Expr *InnerCond = nullptr; 15958 std::string InnerCondDescription; 15959 std::tie(InnerCond, InnerCondDescription) = 15960 findFailedBooleanCondition(Converted.get()); 15961 if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) { 15962 // Drill down into concept specialization expressions to see why they 15963 // weren't satisfied. 15964 Diag(StaticAssertLoc, diag::err_static_assert_failed) 15965 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 15966 ConstraintSatisfaction Satisfaction; 15967 if (!CheckConstraintSatisfaction(InnerCond, Satisfaction)) 15968 DiagnoseUnsatisfiedConstraint(Satisfaction); 15969 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond) 15970 && !isa<IntegerLiteral>(InnerCond)) { 15971 Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed) 15972 << InnerCondDescription << !AssertMessage 15973 << Msg.str() << InnerCond->getSourceRange(); 15974 } else { 15975 Diag(StaticAssertLoc, diag::err_static_assert_failed) 15976 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 15977 } 15978 Failed = true; 15979 } 15980 } else { 15981 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc, 15982 /*DiscardedValue*/false, 15983 /*IsConstexpr*/true); 15984 if (FullAssertExpr.isInvalid()) 15985 Failed = true; 15986 else 15987 AssertExpr = FullAssertExpr.get(); 15988 } 15989 15990 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 15991 AssertExpr, AssertMessage, RParenLoc, 15992 Failed); 15993 15994 CurContext->addDecl(Decl); 15995 return Decl; 15996 } 15997 15998 /// Perform semantic analysis of the given friend type declaration. 15999 /// 16000 /// \returns A friend declaration that. 16001 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 16002 SourceLocation FriendLoc, 16003 TypeSourceInfo *TSInfo) { 16004 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 16005 16006 QualType T = TSInfo->getType(); 16007 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 16008 16009 // C++03 [class.friend]p2: 16010 // An elaborated-type-specifier shall be used in a friend declaration 16011 // for a class.* 16012 // 16013 // * The class-key of the elaborated-type-specifier is required. 16014 if (!CodeSynthesisContexts.empty()) { 16015 // Do not complain about the form of friend template types during any kind 16016 // of code synthesis. For template instantiation, we will have complained 16017 // when the template was defined. 16018 } else { 16019 if (!T->isElaboratedTypeSpecifier()) { 16020 // If we evaluated the type to a record type, suggest putting 16021 // a tag in front. 16022 if (const RecordType *RT = T->getAs<RecordType>()) { 16023 RecordDecl *RD = RT->getDecl(); 16024 16025 SmallString<16> InsertionText(" "); 16026 InsertionText += RD->getKindName(); 16027 16028 Diag(TypeRange.getBegin(), 16029 getLangOpts().CPlusPlus11 ? 16030 diag::warn_cxx98_compat_unelaborated_friend_type : 16031 diag::ext_unelaborated_friend_type) 16032 << (unsigned) RD->getTagKind() 16033 << T 16034 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc), 16035 InsertionText); 16036 } else { 16037 Diag(FriendLoc, 16038 getLangOpts().CPlusPlus11 ? 16039 diag::warn_cxx98_compat_nonclass_type_friend : 16040 diag::ext_nonclass_type_friend) 16041 << T 16042 << TypeRange; 16043 } 16044 } else if (T->getAs<EnumType>()) { 16045 Diag(FriendLoc, 16046 getLangOpts().CPlusPlus11 ? 16047 diag::warn_cxx98_compat_enum_friend : 16048 diag::ext_enum_friend) 16049 << T 16050 << TypeRange; 16051 } 16052 16053 // C++11 [class.friend]p3: 16054 // A friend declaration that does not declare a function shall have one 16055 // of the following forms: 16056 // friend elaborated-type-specifier ; 16057 // friend simple-type-specifier ; 16058 // friend typename-specifier ; 16059 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 16060 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 16061 } 16062 16063 // If the type specifier in a friend declaration designates a (possibly 16064 // cv-qualified) class type, that class is declared as a friend; otherwise, 16065 // the friend declaration is ignored. 16066 return FriendDecl::Create(Context, CurContext, 16067 TSInfo->getTypeLoc().getBeginLoc(), TSInfo, 16068 FriendLoc); 16069 } 16070 16071 /// Handle a friend tag declaration where the scope specifier was 16072 /// templated. 16073 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 16074 unsigned TagSpec, SourceLocation TagLoc, 16075 CXXScopeSpec &SS, IdentifierInfo *Name, 16076 SourceLocation NameLoc, 16077 const ParsedAttributesView &Attr, 16078 MultiTemplateParamsArg TempParamLists) { 16079 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 16080 16081 bool IsMemberSpecialization = false; 16082 bool Invalid = false; 16083 16084 if (TemplateParameterList *TemplateParams = 16085 MatchTemplateParametersToScopeSpecifier( 16086 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 16087 IsMemberSpecialization, Invalid)) { 16088 if (TemplateParams->size() > 0) { 16089 // This is a declaration of a class template. 16090 if (Invalid) 16091 return nullptr; 16092 16093 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 16094 NameLoc, Attr, TemplateParams, AS_public, 16095 /*ModulePrivateLoc=*/SourceLocation(), 16096 FriendLoc, TempParamLists.size() - 1, 16097 TempParamLists.data()).get(); 16098 } else { 16099 // The "template<>" header is extraneous. 16100 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 16101 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 16102 IsMemberSpecialization = true; 16103 } 16104 } 16105 16106 if (Invalid) return nullptr; 16107 16108 bool isAllExplicitSpecializations = true; 16109 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 16110 if (TempParamLists[I]->size()) { 16111 isAllExplicitSpecializations = false; 16112 break; 16113 } 16114 } 16115 16116 // FIXME: don't ignore attributes. 16117 16118 // If it's explicit specializations all the way down, just forget 16119 // about the template header and build an appropriate non-templated 16120 // friend. TODO: for source fidelity, remember the headers. 16121 if (isAllExplicitSpecializations) { 16122 if (SS.isEmpty()) { 16123 bool Owned = false; 16124 bool IsDependent = false; 16125 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 16126 Attr, AS_public, 16127 /*ModulePrivateLoc=*/SourceLocation(), 16128 MultiTemplateParamsArg(), Owned, IsDependent, 16129 /*ScopedEnumKWLoc=*/SourceLocation(), 16130 /*ScopedEnumUsesClassTag=*/false, 16131 /*UnderlyingType=*/TypeResult(), 16132 /*IsTypeSpecifier=*/false, 16133 /*IsTemplateParamOrArg=*/false); 16134 } 16135 16136 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 16137 ElaboratedTypeKeyword Keyword 16138 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 16139 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 16140 *Name, NameLoc); 16141 if (T.isNull()) 16142 return nullptr; 16143 16144 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 16145 if (isa<DependentNameType>(T)) { 16146 DependentNameTypeLoc TL = 16147 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 16148 TL.setElaboratedKeywordLoc(TagLoc); 16149 TL.setQualifierLoc(QualifierLoc); 16150 TL.setNameLoc(NameLoc); 16151 } else { 16152 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 16153 TL.setElaboratedKeywordLoc(TagLoc); 16154 TL.setQualifierLoc(QualifierLoc); 16155 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 16156 } 16157 16158 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 16159 TSI, FriendLoc, TempParamLists); 16160 Friend->setAccess(AS_public); 16161 CurContext->addDecl(Friend); 16162 return Friend; 16163 } 16164 16165 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 16166 16167 16168 16169 // Handle the case of a templated-scope friend class. e.g. 16170 // template <class T> class A<T>::B; 16171 // FIXME: we don't support these right now. 16172 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 16173 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 16174 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 16175 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 16176 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 16177 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 16178 TL.setElaboratedKeywordLoc(TagLoc); 16179 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 16180 TL.setNameLoc(NameLoc); 16181 16182 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 16183 TSI, FriendLoc, TempParamLists); 16184 Friend->setAccess(AS_public); 16185 Friend->setUnsupportedFriend(true); 16186 CurContext->addDecl(Friend); 16187 return Friend; 16188 } 16189 16190 /// Handle a friend type declaration. This works in tandem with 16191 /// ActOnTag. 16192 /// 16193 /// Notes on friend class templates: 16194 /// 16195 /// We generally treat friend class declarations as if they were 16196 /// declaring a class. So, for example, the elaborated type specifier 16197 /// in a friend declaration is required to obey the restrictions of a 16198 /// class-head (i.e. no typedefs in the scope chain), template 16199 /// parameters are required to match up with simple template-ids, &c. 16200 /// However, unlike when declaring a template specialization, it's 16201 /// okay to refer to a template specialization without an empty 16202 /// template parameter declaration, e.g. 16203 /// friend class A<T>::B<unsigned>; 16204 /// We permit this as a special case; if there are any template 16205 /// parameters present at all, require proper matching, i.e. 16206 /// template <> template \<class T> friend class A<int>::B; 16207 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 16208 MultiTemplateParamsArg TempParams) { 16209 SourceLocation Loc = DS.getBeginLoc(); 16210 16211 assert(DS.isFriendSpecified()); 16212 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 16213 16214 // C++ [class.friend]p3: 16215 // A friend declaration that does not declare a function shall have one of 16216 // the following forms: 16217 // friend elaborated-type-specifier ; 16218 // friend simple-type-specifier ; 16219 // friend typename-specifier ; 16220 // 16221 // Any declaration with a type qualifier does not have that form. (It's 16222 // legal to specify a qualified type as a friend, you just can't write the 16223 // keywords.) 16224 if (DS.getTypeQualifiers()) { 16225 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 16226 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const"; 16227 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 16228 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile"; 16229 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 16230 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict"; 16231 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 16232 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic"; 16233 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 16234 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned"; 16235 } 16236 16237 // Try to convert the decl specifier to a type. This works for 16238 // friend templates because ActOnTag never produces a ClassTemplateDecl 16239 // for a TUK_Friend. 16240 Declarator TheDeclarator(DS, DeclaratorContext::MemberContext); 16241 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 16242 QualType T = TSI->getType(); 16243 if (TheDeclarator.isInvalidType()) 16244 return nullptr; 16245 16246 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 16247 return nullptr; 16248 16249 // This is definitely an error in C++98. It's probably meant to 16250 // be forbidden in C++0x, too, but the specification is just 16251 // poorly written. 16252 // 16253 // The problem is with declarations like the following: 16254 // template <T> friend A<T>::foo; 16255 // where deciding whether a class C is a friend or not now hinges 16256 // on whether there exists an instantiation of A that causes 16257 // 'foo' to equal C. There are restrictions on class-heads 16258 // (which we declare (by fiat) elaborated friend declarations to 16259 // be) that makes this tractable. 16260 // 16261 // FIXME: handle "template <> friend class A<T>;", which 16262 // is possibly well-formed? Who even knows? 16263 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 16264 Diag(Loc, diag::err_tagless_friend_type_template) 16265 << DS.getSourceRange(); 16266 return nullptr; 16267 } 16268 16269 // C++98 [class.friend]p1: A friend of a class is a function 16270 // or class that is not a member of the class . . . 16271 // This is fixed in DR77, which just barely didn't make the C++03 16272 // deadline. It's also a very silly restriction that seriously 16273 // affects inner classes and which nobody else seems to implement; 16274 // thus we never diagnose it, not even in -pedantic. 16275 // 16276 // But note that we could warn about it: it's always useless to 16277 // friend one of your own members (it's not, however, worthless to 16278 // friend a member of an arbitrary specialization of your template). 16279 16280 Decl *D; 16281 if (!TempParams.empty()) 16282 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 16283 TempParams, 16284 TSI, 16285 DS.getFriendSpecLoc()); 16286 else 16287 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 16288 16289 if (!D) 16290 return nullptr; 16291 16292 D->setAccess(AS_public); 16293 CurContext->addDecl(D); 16294 16295 return D; 16296 } 16297 16298 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 16299 MultiTemplateParamsArg TemplateParams) { 16300 const DeclSpec &DS = D.getDeclSpec(); 16301 16302 assert(DS.isFriendSpecified()); 16303 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 16304 16305 SourceLocation Loc = D.getIdentifierLoc(); 16306 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16307 16308 // C++ [class.friend]p1 16309 // A friend of a class is a function or class.... 16310 // Note that this sees through typedefs, which is intended. 16311 // It *doesn't* see through dependent types, which is correct 16312 // according to [temp.arg.type]p3: 16313 // If a declaration acquires a function type through a 16314 // type dependent on a template-parameter and this causes 16315 // a declaration that does not use the syntactic form of a 16316 // function declarator to have a function type, the program 16317 // is ill-formed. 16318 if (!TInfo->getType()->isFunctionType()) { 16319 Diag(Loc, diag::err_unexpected_friend); 16320 16321 // It might be worthwhile to try to recover by creating an 16322 // appropriate declaration. 16323 return nullptr; 16324 } 16325 16326 // C++ [namespace.memdef]p3 16327 // - If a friend declaration in a non-local class first declares a 16328 // class or function, the friend class or function is a member 16329 // of the innermost enclosing namespace. 16330 // - The name of the friend is not found by simple name lookup 16331 // until a matching declaration is provided in that namespace 16332 // scope (either before or after the class declaration granting 16333 // friendship). 16334 // - If a friend function is called, its name may be found by the 16335 // name lookup that considers functions from namespaces and 16336 // classes associated with the types of the function arguments. 16337 // - When looking for a prior declaration of a class or a function 16338 // declared as a friend, scopes outside the innermost enclosing 16339 // namespace scope are not considered. 16340 16341 CXXScopeSpec &SS = D.getCXXScopeSpec(); 16342 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 16343 assert(NameInfo.getName()); 16344 16345 // Check for unexpanded parameter packs. 16346 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 16347 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 16348 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 16349 return nullptr; 16350 16351 // The context we found the declaration in, or in which we should 16352 // create the declaration. 16353 DeclContext *DC; 16354 Scope *DCScope = S; 16355 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 16356 ForExternalRedeclaration); 16357 16358 // There are five cases here. 16359 // - There's no scope specifier and we're in a local class. Only look 16360 // for functions declared in the immediately-enclosing block scope. 16361 // We recover from invalid scope qualifiers as if they just weren't there. 16362 FunctionDecl *FunctionContainingLocalClass = nullptr; 16363 if ((SS.isInvalid() || !SS.isSet()) && 16364 (FunctionContainingLocalClass = 16365 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 16366 // C++11 [class.friend]p11: 16367 // If a friend declaration appears in a local class and the name 16368 // specified is an unqualified name, a prior declaration is 16369 // looked up without considering scopes that are outside the 16370 // innermost enclosing non-class scope. For a friend function 16371 // declaration, if there is no prior declaration, the program is 16372 // ill-formed. 16373 16374 // Find the innermost enclosing non-class scope. This is the block 16375 // scope containing the local class definition (or for a nested class, 16376 // the outer local class). 16377 DCScope = S->getFnParent(); 16378 16379 // Look up the function name in the scope. 16380 Previous.clear(LookupLocalFriendName); 16381 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 16382 16383 if (!Previous.empty()) { 16384 // All possible previous declarations must have the same context: 16385 // either they were declared at block scope or they are members of 16386 // one of the enclosing local classes. 16387 DC = Previous.getRepresentativeDecl()->getDeclContext(); 16388 } else { 16389 // This is ill-formed, but provide the context that we would have 16390 // declared the function in, if we were permitted to, for error recovery. 16391 DC = FunctionContainingLocalClass; 16392 } 16393 adjustContextForLocalExternDecl(DC); 16394 16395 // C++ [class.friend]p6: 16396 // A function can be defined in a friend declaration of a class if and 16397 // only if the class is a non-local class (9.8), the function name is 16398 // unqualified, and the function has namespace scope. 16399 if (D.isFunctionDefinition()) { 16400 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 16401 } 16402 16403 // - There's no scope specifier, in which case we just go to the 16404 // appropriate scope and look for a function or function template 16405 // there as appropriate. 16406 } else if (SS.isInvalid() || !SS.isSet()) { 16407 // C++11 [namespace.memdef]p3: 16408 // If the name in a friend declaration is neither qualified nor 16409 // a template-id and the declaration is a function or an 16410 // elaborated-type-specifier, the lookup to determine whether 16411 // the entity has been previously declared shall not consider 16412 // any scopes outside the innermost enclosing namespace. 16413 bool isTemplateId = 16414 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId; 16415 16416 // Find the appropriate context according to the above. 16417 DC = CurContext; 16418 16419 // Skip class contexts. If someone can cite chapter and verse 16420 // for this behavior, that would be nice --- it's what GCC and 16421 // EDG do, and it seems like a reasonable intent, but the spec 16422 // really only says that checks for unqualified existing 16423 // declarations should stop at the nearest enclosing namespace, 16424 // not that they should only consider the nearest enclosing 16425 // namespace. 16426 while (DC->isRecord()) 16427 DC = DC->getParent(); 16428 16429 DeclContext *LookupDC = DC; 16430 while (LookupDC->isTransparentContext()) 16431 LookupDC = LookupDC->getParent(); 16432 16433 while (true) { 16434 LookupQualifiedName(Previous, LookupDC); 16435 16436 if (!Previous.empty()) { 16437 DC = LookupDC; 16438 break; 16439 } 16440 16441 if (isTemplateId) { 16442 if (isa<TranslationUnitDecl>(LookupDC)) break; 16443 } else { 16444 if (LookupDC->isFileContext()) break; 16445 } 16446 LookupDC = LookupDC->getParent(); 16447 } 16448 16449 DCScope = getScopeForDeclContext(S, DC); 16450 16451 // - There's a non-dependent scope specifier, in which case we 16452 // compute it and do a previous lookup there for a function 16453 // or function template. 16454 } else if (!SS.getScopeRep()->isDependent()) { 16455 DC = computeDeclContext(SS); 16456 if (!DC) return nullptr; 16457 16458 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 16459 16460 LookupQualifiedName(Previous, DC); 16461 16462 // C++ [class.friend]p1: A friend of a class is a function or 16463 // class that is not a member of the class . . . 16464 if (DC->Equals(CurContext)) 16465 Diag(DS.getFriendSpecLoc(), 16466 getLangOpts().CPlusPlus11 ? 16467 diag::warn_cxx98_compat_friend_is_member : 16468 diag::err_friend_is_member); 16469 16470 if (D.isFunctionDefinition()) { 16471 // C++ [class.friend]p6: 16472 // A function can be defined in a friend declaration of a class if and 16473 // only if the class is a non-local class (9.8), the function name is 16474 // unqualified, and the function has namespace scope. 16475 // 16476 // FIXME: We should only do this if the scope specifier names the 16477 // innermost enclosing namespace; otherwise the fixit changes the 16478 // meaning of the code. 16479 SemaDiagnosticBuilder DB 16480 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 16481 16482 DB << SS.getScopeRep(); 16483 if (DC->isFileContext()) 16484 DB << FixItHint::CreateRemoval(SS.getRange()); 16485 SS.clear(); 16486 } 16487 16488 // - There's a scope specifier that does not match any template 16489 // parameter lists, in which case we use some arbitrary context, 16490 // create a method or method template, and wait for instantiation. 16491 // - There's a scope specifier that does match some template 16492 // parameter lists, which we don't handle right now. 16493 } else { 16494 if (D.isFunctionDefinition()) { 16495 // C++ [class.friend]p6: 16496 // A function can be defined in a friend declaration of a class if and 16497 // only if the class is a non-local class (9.8), the function name is 16498 // unqualified, and the function has namespace scope. 16499 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 16500 << SS.getScopeRep(); 16501 } 16502 16503 DC = CurContext; 16504 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 16505 } 16506 16507 if (!DC->isRecord()) { 16508 int DiagArg = -1; 16509 switch (D.getName().getKind()) { 16510 case UnqualifiedIdKind::IK_ConstructorTemplateId: 16511 case UnqualifiedIdKind::IK_ConstructorName: 16512 DiagArg = 0; 16513 break; 16514 case UnqualifiedIdKind::IK_DestructorName: 16515 DiagArg = 1; 16516 break; 16517 case UnqualifiedIdKind::IK_ConversionFunctionId: 16518 DiagArg = 2; 16519 break; 16520 case UnqualifiedIdKind::IK_DeductionGuideName: 16521 DiagArg = 3; 16522 break; 16523 case UnqualifiedIdKind::IK_Identifier: 16524 case UnqualifiedIdKind::IK_ImplicitSelfParam: 16525 case UnqualifiedIdKind::IK_LiteralOperatorId: 16526 case UnqualifiedIdKind::IK_OperatorFunctionId: 16527 case UnqualifiedIdKind::IK_TemplateId: 16528 break; 16529 } 16530 // This implies that it has to be an operator or function. 16531 if (DiagArg >= 0) { 16532 Diag(Loc, diag::err_introducing_special_friend) << DiagArg; 16533 return nullptr; 16534 } 16535 } 16536 16537 // FIXME: This is an egregious hack to cope with cases where the scope stack 16538 // does not contain the declaration context, i.e., in an out-of-line 16539 // definition of a class. 16540 Scope FakeDCScope(S, Scope::DeclScope, Diags); 16541 if (!DCScope) { 16542 FakeDCScope.setEntity(DC); 16543 DCScope = &FakeDCScope; 16544 } 16545 16546 bool AddToScope = true; 16547 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 16548 TemplateParams, AddToScope); 16549 if (!ND) return nullptr; 16550 16551 assert(ND->getLexicalDeclContext() == CurContext); 16552 16553 // If we performed typo correction, we might have added a scope specifier 16554 // and changed the decl context. 16555 DC = ND->getDeclContext(); 16556 16557 // Add the function declaration to the appropriate lookup tables, 16558 // adjusting the redeclarations list as necessary. We don't 16559 // want to do this yet if the friending class is dependent. 16560 // 16561 // Also update the scope-based lookup if the target context's 16562 // lookup context is in lexical scope. 16563 if (!CurContext->isDependentContext()) { 16564 DC = DC->getRedeclContext(); 16565 DC->makeDeclVisibleInContext(ND); 16566 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 16567 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 16568 } 16569 16570 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 16571 D.getIdentifierLoc(), ND, 16572 DS.getFriendSpecLoc()); 16573 FrD->setAccess(AS_public); 16574 CurContext->addDecl(FrD); 16575 16576 if (ND->isInvalidDecl()) { 16577 FrD->setInvalidDecl(); 16578 } else { 16579 if (DC->isRecord()) CheckFriendAccess(ND); 16580 16581 FunctionDecl *FD; 16582 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 16583 FD = FTD->getTemplatedDecl(); 16584 else 16585 FD = cast<FunctionDecl>(ND); 16586 16587 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 16588 // default argument expression, that declaration shall be a definition 16589 // and shall be the only declaration of the function or function 16590 // template in the translation unit. 16591 if (functionDeclHasDefaultArgument(FD)) { 16592 // We can't look at FD->getPreviousDecl() because it may not have been set 16593 // if we're in a dependent context. If the function is known to be a 16594 // redeclaration, we will have narrowed Previous down to the right decl. 16595 if (D.isRedeclaration()) { 16596 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 16597 Diag(Previous.getRepresentativeDecl()->getLocation(), 16598 diag::note_previous_declaration); 16599 } else if (!D.isFunctionDefinition()) 16600 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 16601 } 16602 16603 // Mark templated-scope function declarations as unsupported. 16604 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 16605 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 16606 << SS.getScopeRep() << SS.getRange() 16607 << cast<CXXRecordDecl>(CurContext); 16608 FrD->setUnsupportedFriend(true); 16609 } 16610 } 16611 16612 return ND; 16613 } 16614 16615 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 16616 AdjustDeclIfTemplate(Dcl); 16617 16618 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 16619 if (!Fn) { 16620 Diag(DelLoc, diag::err_deleted_non_function); 16621 return; 16622 } 16623 16624 // Deleted function does not have a body. 16625 Fn->setWillHaveBody(false); 16626 16627 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 16628 // Don't consider the implicit declaration we generate for explicit 16629 // specializations. FIXME: Do not generate these implicit declarations. 16630 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 16631 Prev->getPreviousDecl()) && 16632 !Prev->isDefined()) { 16633 Diag(DelLoc, diag::err_deleted_decl_not_first); 16634 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 16635 Prev->isImplicit() ? diag::note_previous_implicit_declaration 16636 : diag::note_previous_declaration); 16637 // We can't recover from this; the declaration might have already 16638 // been used. 16639 Fn->setInvalidDecl(); 16640 return; 16641 } 16642 16643 // To maintain the invariant that functions are only deleted on their first 16644 // declaration, mark the implicitly-instantiated declaration of the 16645 // explicitly-specialized function as deleted instead of marking the 16646 // instantiated redeclaration. 16647 Fn = Fn->getCanonicalDecl(); 16648 } 16649 16650 // dllimport/dllexport cannot be deleted. 16651 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 16652 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 16653 Fn->setInvalidDecl(); 16654 } 16655 16656 // C++11 [basic.start.main]p3: 16657 // A program that defines main as deleted [...] is ill-formed. 16658 if (Fn->isMain()) 16659 Diag(DelLoc, diag::err_deleted_main); 16660 16661 // C++11 [dcl.fct.def.delete]p4: 16662 // A deleted function is implicitly inline. 16663 Fn->setImplicitlyInline(); 16664 Fn->setDeletedAsWritten(); 16665 } 16666 16667 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 16668 if (!Dcl || Dcl->isInvalidDecl()) 16669 return; 16670 16671 auto *FD = dyn_cast<FunctionDecl>(Dcl); 16672 if (!FD) { 16673 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) { 16674 if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) { 16675 Diag(DefaultLoc, diag::err_defaulted_comparison_template); 16676 return; 16677 } 16678 } 16679 16680 Diag(DefaultLoc, diag::err_default_special_members) 16681 << getLangOpts().CPlusPlus20; 16682 return; 16683 } 16684 16685 // Reject if this can't possibly be a defaultable function. 16686 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD); 16687 if (!DefKind && 16688 // A dependent function that doesn't locally look defaultable can 16689 // still instantiate to a defaultable function if it's a constructor 16690 // or assignment operator. 16691 (!FD->isDependentContext() || 16692 (!isa<CXXConstructorDecl>(FD) && 16693 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) { 16694 Diag(DefaultLoc, diag::err_default_special_members) 16695 << getLangOpts().CPlusPlus20; 16696 return; 16697 } 16698 16699 if (DefKind.isComparison() && 16700 !isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 16701 Diag(FD->getLocation(), diag::err_defaulted_comparison_out_of_class) 16702 << (int)DefKind.asComparison(); 16703 return; 16704 } 16705 16706 // Issue compatibility warning. We already warned if the operator is 16707 // 'operator<=>' when parsing the '<=>' token. 16708 if (DefKind.isComparison() && 16709 DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) { 16710 Diag(DefaultLoc, getLangOpts().CPlusPlus20 16711 ? diag::warn_cxx17_compat_defaulted_comparison 16712 : diag::ext_defaulted_comparison); 16713 } 16714 16715 FD->setDefaulted(); 16716 FD->setExplicitlyDefaulted(); 16717 16718 // Defer checking functions that are defaulted in a dependent context. 16719 if (FD->isDependentContext()) 16720 return; 16721 16722 // Unset that we will have a body for this function. We might not, 16723 // if it turns out to be trivial, and we don't need this marking now 16724 // that we've marked it as defaulted. 16725 FD->setWillHaveBody(false); 16726 16727 // If this definition appears within the record, do the checking when 16728 // the record is complete. This is always the case for a defaulted 16729 // comparison. 16730 if (DefKind.isComparison()) 16731 return; 16732 auto *MD = cast<CXXMethodDecl>(FD); 16733 16734 const FunctionDecl *Primary = FD; 16735 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern()) 16736 // Ask the template instantiation pattern that actually had the 16737 // '= default' on it. 16738 Primary = Pattern; 16739 16740 // If the method was defaulted on its first declaration, we will have 16741 // already performed the checking in CheckCompletedCXXClass. Such a 16742 // declaration doesn't trigger an implicit definition. 16743 if (Primary->getCanonicalDecl()->isDefaulted()) 16744 return; 16745 16746 // FIXME: Once we support defining comparisons out of class, check for a 16747 // defaulted comparison here. 16748 if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember())) 16749 MD->setInvalidDecl(); 16750 else 16751 DefineDefaultedFunction(*this, MD, DefaultLoc); 16752 } 16753 16754 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 16755 for (Stmt *SubStmt : S->children()) { 16756 if (!SubStmt) 16757 continue; 16758 if (isa<ReturnStmt>(SubStmt)) 16759 Self.Diag(SubStmt->getBeginLoc(), 16760 diag::err_return_in_constructor_handler); 16761 if (!isa<Expr>(SubStmt)) 16762 SearchForReturnInStmt(Self, SubStmt); 16763 } 16764 } 16765 16766 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 16767 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 16768 CXXCatchStmt *Handler = TryBlock->getHandler(I); 16769 SearchForReturnInStmt(*this, Handler); 16770 } 16771 } 16772 16773 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 16774 const CXXMethodDecl *Old) { 16775 const auto *NewFT = New->getType()->castAs<FunctionProtoType>(); 16776 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>(); 16777 16778 if (OldFT->hasExtParameterInfos()) { 16779 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I) 16780 // A parameter of the overriding method should be annotated with noescape 16781 // if the corresponding parameter of the overridden method is annotated. 16782 if (OldFT->getExtParameterInfo(I).isNoEscape() && 16783 !NewFT->getExtParameterInfo(I).isNoEscape()) { 16784 Diag(New->getParamDecl(I)->getLocation(), 16785 diag::warn_overriding_method_missing_noescape); 16786 Diag(Old->getParamDecl(I)->getLocation(), 16787 diag::note_overridden_marked_noescape); 16788 } 16789 } 16790 16791 // Virtual overrides must have the same code_seg. 16792 const auto *OldCSA = Old->getAttr<CodeSegAttr>(); 16793 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 16794 if ((NewCSA || OldCSA) && 16795 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) { 16796 Diag(New->getLocation(), diag::err_mismatched_code_seg_override); 16797 Diag(Old->getLocation(), diag::note_previous_declaration); 16798 return true; 16799 } 16800 16801 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 16802 16803 // If the calling conventions match, everything is fine 16804 if (NewCC == OldCC) 16805 return false; 16806 16807 // If the calling conventions mismatch because the new function is static, 16808 // suppress the calling convention mismatch error; the error about static 16809 // function override (err_static_overrides_virtual from 16810 // Sema::CheckFunctionDeclaration) is more clear. 16811 if (New->getStorageClass() == SC_Static) 16812 return false; 16813 16814 Diag(New->getLocation(), 16815 diag::err_conflicting_overriding_cc_attributes) 16816 << New->getDeclName() << New->getType() << Old->getType(); 16817 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 16818 return true; 16819 } 16820 16821 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 16822 const CXXMethodDecl *Old) { 16823 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType(); 16824 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType(); 16825 16826 if (Context.hasSameType(NewTy, OldTy) || 16827 NewTy->isDependentType() || OldTy->isDependentType()) 16828 return false; 16829 16830 // Check if the return types are covariant 16831 QualType NewClassTy, OldClassTy; 16832 16833 /// Both types must be pointers or references to classes. 16834 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 16835 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 16836 NewClassTy = NewPT->getPointeeType(); 16837 OldClassTy = OldPT->getPointeeType(); 16838 } 16839 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 16840 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 16841 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 16842 NewClassTy = NewRT->getPointeeType(); 16843 OldClassTy = OldRT->getPointeeType(); 16844 } 16845 } 16846 } 16847 16848 // The return types aren't either both pointers or references to a class type. 16849 if (NewClassTy.isNull()) { 16850 Diag(New->getLocation(), 16851 diag::err_different_return_type_for_overriding_virtual_function) 16852 << New->getDeclName() << NewTy << OldTy 16853 << New->getReturnTypeSourceRange(); 16854 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 16855 << Old->getReturnTypeSourceRange(); 16856 16857 return true; 16858 } 16859 16860 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 16861 // C++14 [class.virtual]p8: 16862 // If the class type in the covariant return type of D::f differs from 16863 // that of B::f, the class type in the return type of D::f shall be 16864 // complete at the point of declaration of D::f or shall be the class 16865 // type D. 16866 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 16867 if (!RT->isBeingDefined() && 16868 RequireCompleteType(New->getLocation(), NewClassTy, 16869 diag::err_covariant_return_incomplete, 16870 New->getDeclName())) 16871 return true; 16872 } 16873 16874 // Check if the new class derives from the old class. 16875 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) { 16876 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 16877 << New->getDeclName() << NewTy << OldTy 16878 << New->getReturnTypeSourceRange(); 16879 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 16880 << Old->getReturnTypeSourceRange(); 16881 return true; 16882 } 16883 16884 // Check if we the conversion from derived to base is valid. 16885 if (CheckDerivedToBaseConversion( 16886 NewClassTy, OldClassTy, 16887 diag::err_covariant_return_inaccessible_base, 16888 diag::err_covariant_return_ambiguous_derived_to_base_conv, 16889 New->getLocation(), New->getReturnTypeSourceRange(), 16890 New->getDeclName(), nullptr)) { 16891 // FIXME: this note won't trigger for delayed access control 16892 // diagnostics, and it's impossible to get an undelayed error 16893 // here from access control during the original parse because 16894 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 16895 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 16896 << Old->getReturnTypeSourceRange(); 16897 return true; 16898 } 16899 } 16900 16901 // The qualifiers of the return types must be the same. 16902 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 16903 Diag(New->getLocation(), 16904 diag::err_covariant_return_type_different_qualifications) 16905 << New->getDeclName() << NewTy << OldTy 16906 << New->getReturnTypeSourceRange(); 16907 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 16908 << Old->getReturnTypeSourceRange(); 16909 return true; 16910 } 16911 16912 16913 // The new class type must have the same or less qualifiers as the old type. 16914 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 16915 Diag(New->getLocation(), 16916 diag::err_covariant_return_type_class_type_more_qualified) 16917 << New->getDeclName() << NewTy << OldTy 16918 << New->getReturnTypeSourceRange(); 16919 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 16920 << Old->getReturnTypeSourceRange(); 16921 return true; 16922 } 16923 16924 return false; 16925 } 16926 16927 /// Mark the given method pure. 16928 /// 16929 /// \param Method the method to be marked pure. 16930 /// 16931 /// \param InitRange the source range that covers the "0" initializer. 16932 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 16933 SourceLocation EndLoc = InitRange.getEnd(); 16934 if (EndLoc.isValid()) 16935 Method->setRangeEnd(EndLoc); 16936 16937 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 16938 Method->setPure(); 16939 return false; 16940 } 16941 16942 if (!Method->isInvalidDecl()) 16943 Diag(Method->getLocation(), diag::err_non_virtual_pure) 16944 << Method->getDeclName() << InitRange; 16945 return true; 16946 } 16947 16948 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) { 16949 if (D->getFriendObjectKind()) 16950 Diag(D->getLocation(), diag::err_pure_friend); 16951 else if (auto *M = dyn_cast<CXXMethodDecl>(D)) 16952 CheckPureMethod(M, ZeroLoc); 16953 else 16954 Diag(D->getLocation(), diag::err_illegal_initializer); 16955 } 16956 16957 /// Determine whether the given declaration is a global variable or 16958 /// static data member. 16959 static bool isNonlocalVariable(const Decl *D) { 16960 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 16961 return Var->hasGlobalStorage(); 16962 16963 return false; 16964 } 16965 16966 /// Invoked when we are about to parse an initializer for the declaration 16967 /// 'Dcl'. 16968 /// 16969 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 16970 /// static data member of class X, names should be looked up in the scope of 16971 /// class X. If the declaration had a scope specifier, a scope will have 16972 /// been created and passed in for this purpose. Otherwise, S will be null. 16973 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 16974 // If there is no declaration, there was an error parsing it. 16975 if (!D || D->isInvalidDecl()) 16976 return; 16977 16978 // We will always have a nested name specifier here, but this declaration 16979 // might not be out of line if the specifier names the current namespace: 16980 // extern int n; 16981 // int ::n = 0; 16982 if (S && D->isOutOfLine()) 16983 EnterDeclaratorContext(S, D->getDeclContext()); 16984 16985 // If we are parsing the initializer for a static data member, push a 16986 // new expression evaluation context that is associated with this static 16987 // data member. 16988 if (isNonlocalVariable(D)) 16989 PushExpressionEvaluationContext( 16990 ExpressionEvaluationContext::PotentiallyEvaluated, D); 16991 } 16992 16993 /// Invoked after we are finished parsing an initializer for the declaration D. 16994 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 16995 // If there is no declaration, there was an error parsing it. 16996 if (!D || D->isInvalidDecl()) 16997 return; 16998 16999 if (isNonlocalVariable(D)) 17000 PopExpressionEvaluationContext(); 17001 17002 if (S && D->isOutOfLine()) 17003 ExitDeclaratorContext(S); 17004 } 17005 17006 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 17007 /// C++ if/switch/while/for statement. 17008 /// e.g: "if (int x = f()) {...}" 17009 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 17010 // C++ 6.4p2: 17011 // The declarator shall not specify a function or an array. 17012 // The type-specifier-seq shall not contain typedef and shall not declare a 17013 // new class or enumeration. 17014 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 17015 "Parser allowed 'typedef' as storage class of condition decl."); 17016 17017 Decl *Dcl = ActOnDeclarator(S, D); 17018 if (!Dcl) 17019 return true; 17020 17021 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 17022 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 17023 << D.getSourceRange(); 17024 return true; 17025 } 17026 17027 return Dcl; 17028 } 17029 17030 void Sema::LoadExternalVTableUses() { 17031 if (!ExternalSource) 17032 return; 17033 17034 SmallVector<ExternalVTableUse, 4> VTables; 17035 ExternalSource->ReadUsedVTables(VTables); 17036 SmallVector<VTableUse, 4> NewUses; 17037 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 17038 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 17039 = VTablesUsed.find(VTables[I].Record); 17040 // Even if a definition wasn't required before, it may be required now. 17041 if (Pos != VTablesUsed.end()) { 17042 if (!Pos->second && VTables[I].DefinitionRequired) 17043 Pos->second = true; 17044 continue; 17045 } 17046 17047 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 17048 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 17049 } 17050 17051 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 17052 } 17053 17054 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 17055 bool DefinitionRequired) { 17056 // Ignore any vtable uses in unevaluated operands or for classes that do 17057 // not have a vtable. 17058 if (!Class->isDynamicClass() || Class->isDependentContext() || 17059 CurContext->isDependentContext() || isUnevaluatedContext()) 17060 return; 17061 // Do not mark as used if compiling for the device outside of the target 17062 // region. 17063 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice && 17064 !isInOpenMPDeclareTargetContext() && 17065 !isInOpenMPTargetExecutionDirective()) { 17066 if (!DefinitionRequired) 17067 MarkVirtualMembersReferenced(Loc, Class); 17068 return; 17069 } 17070 17071 // Try to insert this class into the map. 17072 LoadExternalVTableUses(); 17073 Class = Class->getCanonicalDecl(); 17074 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 17075 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 17076 if (!Pos.second) { 17077 // If we already had an entry, check to see if we are promoting this vtable 17078 // to require a definition. If so, we need to reappend to the VTableUses 17079 // list, since we may have already processed the first entry. 17080 if (DefinitionRequired && !Pos.first->second) { 17081 Pos.first->second = true; 17082 } else { 17083 // Otherwise, we can early exit. 17084 return; 17085 } 17086 } else { 17087 // The Microsoft ABI requires that we perform the destructor body 17088 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 17089 // the deleting destructor is emitted with the vtable, not with the 17090 // destructor definition as in the Itanium ABI. 17091 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 17092 CXXDestructorDecl *DD = Class->getDestructor(); 17093 if (DD && DD->isVirtual() && !DD->isDeleted()) { 17094 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) { 17095 // If this is an out-of-line declaration, marking it referenced will 17096 // not do anything. Manually call CheckDestructor to look up operator 17097 // delete(). 17098 ContextRAII SavedContext(*this, DD); 17099 CheckDestructor(DD); 17100 } else { 17101 MarkFunctionReferenced(Loc, Class->getDestructor()); 17102 } 17103 } 17104 } 17105 } 17106 17107 // Local classes need to have their virtual members marked 17108 // immediately. For all other classes, we mark their virtual members 17109 // at the end of the translation unit. 17110 if (Class->isLocalClass()) 17111 MarkVirtualMembersReferenced(Loc, Class); 17112 else 17113 VTableUses.push_back(std::make_pair(Class, Loc)); 17114 } 17115 17116 bool Sema::DefineUsedVTables() { 17117 LoadExternalVTableUses(); 17118 if (VTableUses.empty()) 17119 return false; 17120 17121 // Note: The VTableUses vector could grow as a result of marking 17122 // the members of a class as "used", so we check the size each 17123 // time through the loop and prefer indices (which are stable) to 17124 // iterators (which are not). 17125 bool DefinedAnything = false; 17126 for (unsigned I = 0; I != VTableUses.size(); ++I) { 17127 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 17128 if (!Class) 17129 continue; 17130 TemplateSpecializationKind ClassTSK = 17131 Class->getTemplateSpecializationKind(); 17132 17133 SourceLocation Loc = VTableUses[I].second; 17134 17135 bool DefineVTable = true; 17136 17137 // If this class has a key function, but that key function is 17138 // defined in another translation unit, we don't need to emit the 17139 // vtable even though we're using it. 17140 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 17141 if (KeyFunction && !KeyFunction->hasBody()) { 17142 // The key function is in another translation unit. 17143 DefineVTable = false; 17144 TemplateSpecializationKind TSK = 17145 KeyFunction->getTemplateSpecializationKind(); 17146 assert(TSK != TSK_ExplicitInstantiationDefinition && 17147 TSK != TSK_ImplicitInstantiation && 17148 "Instantiations don't have key functions"); 17149 (void)TSK; 17150 } else if (!KeyFunction) { 17151 // If we have a class with no key function that is the subject 17152 // of an explicit instantiation declaration, suppress the 17153 // vtable; it will live with the explicit instantiation 17154 // definition. 17155 bool IsExplicitInstantiationDeclaration = 17156 ClassTSK == TSK_ExplicitInstantiationDeclaration; 17157 for (auto R : Class->redecls()) { 17158 TemplateSpecializationKind TSK 17159 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 17160 if (TSK == TSK_ExplicitInstantiationDeclaration) 17161 IsExplicitInstantiationDeclaration = true; 17162 else if (TSK == TSK_ExplicitInstantiationDefinition) { 17163 IsExplicitInstantiationDeclaration = false; 17164 break; 17165 } 17166 } 17167 17168 if (IsExplicitInstantiationDeclaration) 17169 DefineVTable = false; 17170 } 17171 17172 // The exception specifications for all virtual members may be needed even 17173 // if we are not providing an authoritative form of the vtable in this TU. 17174 // We may choose to emit it available_externally anyway. 17175 if (!DefineVTable) { 17176 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 17177 continue; 17178 } 17179 17180 // Mark all of the virtual members of this class as referenced, so 17181 // that we can build a vtable. Then, tell the AST consumer that a 17182 // vtable for this class is required. 17183 DefinedAnything = true; 17184 MarkVirtualMembersReferenced(Loc, Class); 17185 CXXRecordDecl *Canonical = Class->getCanonicalDecl(); 17186 if (VTablesUsed[Canonical]) 17187 Consumer.HandleVTable(Class); 17188 17189 // Warn if we're emitting a weak vtable. The vtable will be weak if there is 17190 // no key function or the key function is inlined. Don't warn in C++ ABIs 17191 // that lack key functions, since the user won't be able to make one. 17192 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() && 17193 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) { 17194 const FunctionDecl *KeyFunctionDef = nullptr; 17195 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) && 17196 KeyFunctionDef->isInlined())) { 17197 Diag(Class->getLocation(), 17198 ClassTSK == TSK_ExplicitInstantiationDefinition 17199 ? diag::warn_weak_template_vtable 17200 : diag::warn_weak_vtable) 17201 << Class; 17202 } 17203 } 17204 } 17205 VTableUses.clear(); 17206 17207 return DefinedAnything; 17208 } 17209 17210 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 17211 const CXXRecordDecl *RD) { 17212 for (const auto *I : RD->methods()) 17213 if (I->isVirtual() && !I->isPure()) 17214 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 17215 } 17216 17217 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 17218 const CXXRecordDecl *RD, 17219 bool ConstexprOnly) { 17220 // Mark all functions which will appear in RD's vtable as used. 17221 CXXFinalOverriderMap FinalOverriders; 17222 RD->getFinalOverriders(FinalOverriders); 17223 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 17224 E = FinalOverriders.end(); 17225 I != E; ++I) { 17226 for (OverridingMethods::const_iterator OI = I->second.begin(), 17227 OE = I->second.end(); 17228 OI != OE; ++OI) { 17229 assert(OI->second.size() > 0 && "no final overrider"); 17230 CXXMethodDecl *Overrider = OI->second.front().Method; 17231 17232 // C++ [basic.def.odr]p2: 17233 // [...] A virtual member function is used if it is not pure. [...] 17234 if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr())) 17235 MarkFunctionReferenced(Loc, Overrider); 17236 } 17237 } 17238 17239 // Only classes that have virtual bases need a VTT. 17240 if (RD->getNumVBases() == 0) 17241 return; 17242 17243 for (const auto &I : RD->bases()) { 17244 const auto *Base = 17245 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 17246 if (Base->getNumVBases() == 0) 17247 continue; 17248 MarkVirtualMembersReferenced(Loc, Base); 17249 } 17250 } 17251 17252 /// SetIvarInitializers - This routine builds initialization ASTs for the 17253 /// Objective-C implementation whose ivars need be initialized. 17254 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 17255 if (!getLangOpts().CPlusPlus) 17256 return; 17257 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 17258 SmallVector<ObjCIvarDecl*, 8> ivars; 17259 CollectIvarsToConstructOrDestruct(OID, ivars); 17260 if (ivars.empty()) 17261 return; 17262 SmallVector<CXXCtorInitializer*, 32> AllToInit; 17263 for (unsigned i = 0; i < ivars.size(); i++) { 17264 FieldDecl *Field = ivars[i]; 17265 if (Field->isInvalidDecl()) 17266 continue; 17267 17268 CXXCtorInitializer *Member; 17269 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 17270 InitializationKind InitKind = 17271 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 17272 17273 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 17274 ExprResult MemberInit = 17275 InitSeq.Perform(*this, InitEntity, InitKind, None); 17276 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 17277 // Note, MemberInit could actually come back empty if no initialization 17278 // is required (e.g., because it would call a trivial default constructor) 17279 if (!MemberInit.get() || MemberInit.isInvalid()) 17280 continue; 17281 17282 Member = 17283 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 17284 SourceLocation(), 17285 MemberInit.getAs<Expr>(), 17286 SourceLocation()); 17287 AllToInit.push_back(Member); 17288 17289 // Be sure that the destructor is accessible and is marked as referenced. 17290 if (const RecordType *RecordTy = 17291 Context.getBaseElementType(Field->getType()) 17292 ->getAs<RecordType>()) { 17293 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 17294 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 17295 MarkFunctionReferenced(Field->getLocation(), Destructor); 17296 CheckDestructorAccess(Field->getLocation(), Destructor, 17297 PDiag(diag::err_access_dtor_ivar) 17298 << Context.getBaseElementType(Field->getType())); 17299 } 17300 } 17301 } 17302 ObjCImplementation->setIvarInitializers(Context, 17303 AllToInit.data(), AllToInit.size()); 17304 } 17305 } 17306 17307 static 17308 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 17309 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid, 17310 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid, 17311 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current, 17312 Sema &S) { 17313 if (Ctor->isInvalidDecl()) 17314 return; 17315 17316 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 17317 17318 // Target may not be determinable yet, for instance if this is a dependent 17319 // call in an uninstantiated template. 17320 if (Target) { 17321 const FunctionDecl *FNTarget = nullptr; 17322 (void)Target->hasBody(FNTarget); 17323 Target = const_cast<CXXConstructorDecl*>( 17324 cast_or_null<CXXConstructorDecl>(FNTarget)); 17325 } 17326 17327 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 17328 // Avoid dereferencing a null pointer here. 17329 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 17330 17331 if (!Current.insert(Canonical).second) 17332 return; 17333 17334 // We know that beyond here, we aren't chaining into a cycle. 17335 if (!Target || !Target->isDelegatingConstructor() || 17336 Target->isInvalidDecl() || Valid.count(TCanonical)) { 17337 Valid.insert(Current.begin(), Current.end()); 17338 Current.clear(); 17339 // We've hit a cycle. 17340 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 17341 Current.count(TCanonical)) { 17342 // If we haven't diagnosed this cycle yet, do so now. 17343 if (!Invalid.count(TCanonical)) { 17344 S.Diag((*Ctor->init_begin())->getSourceLocation(), 17345 diag::warn_delegating_ctor_cycle) 17346 << Ctor; 17347 17348 // Don't add a note for a function delegating directly to itself. 17349 if (TCanonical != Canonical) 17350 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 17351 17352 CXXConstructorDecl *C = Target; 17353 while (C->getCanonicalDecl() != Canonical) { 17354 const FunctionDecl *FNTarget = nullptr; 17355 (void)C->getTargetConstructor()->hasBody(FNTarget); 17356 assert(FNTarget && "Ctor cycle through bodiless function"); 17357 17358 C = const_cast<CXXConstructorDecl*>( 17359 cast<CXXConstructorDecl>(FNTarget)); 17360 S.Diag(C->getLocation(), diag::note_which_delegates_to); 17361 } 17362 } 17363 17364 Invalid.insert(Current.begin(), Current.end()); 17365 Current.clear(); 17366 } else { 17367 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 17368 } 17369 } 17370 17371 17372 void Sema::CheckDelegatingCtorCycles() { 17373 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 17374 17375 for (DelegatingCtorDeclsType::iterator 17376 I = DelegatingCtorDecls.begin(ExternalSource), 17377 E = DelegatingCtorDecls.end(); 17378 I != E; ++I) 17379 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 17380 17381 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI) 17382 (*CI)->setInvalidDecl(); 17383 } 17384 17385 namespace { 17386 /// AST visitor that finds references to the 'this' expression. 17387 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 17388 Sema &S; 17389 17390 public: 17391 explicit FindCXXThisExpr(Sema &S) : S(S) { } 17392 17393 bool VisitCXXThisExpr(CXXThisExpr *E) { 17394 S.Diag(E->getLocation(), diag::err_this_static_member_func) 17395 << E->isImplicit(); 17396 return false; 17397 } 17398 }; 17399 } 17400 17401 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 17402 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 17403 if (!TSInfo) 17404 return false; 17405 17406 TypeLoc TL = TSInfo->getTypeLoc(); 17407 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 17408 if (!ProtoTL) 17409 return false; 17410 17411 // C++11 [expr.prim.general]p3: 17412 // [The expression this] shall not appear before the optional 17413 // cv-qualifier-seq and it shall not appear within the declaration of a 17414 // static member function (although its type and value category are defined 17415 // within a static member function as they are within a non-static member 17416 // function). [ Note: this is because declaration matching does not occur 17417 // until the complete declarator is known. - end note ] 17418 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 17419 FindCXXThisExpr Finder(*this); 17420 17421 // If the return type came after the cv-qualifier-seq, check it now. 17422 if (Proto->hasTrailingReturn() && 17423 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 17424 return true; 17425 17426 // Check the exception specification. 17427 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 17428 return true; 17429 17430 // Check the trailing requires clause 17431 if (Expr *E = Method->getTrailingRequiresClause()) 17432 if (!Finder.TraverseStmt(E)) 17433 return true; 17434 17435 return checkThisInStaticMemberFunctionAttributes(Method); 17436 } 17437 17438 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 17439 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 17440 if (!TSInfo) 17441 return false; 17442 17443 TypeLoc TL = TSInfo->getTypeLoc(); 17444 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 17445 if (!ProtoTL) 17446 return false; 17447 17448 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 17449 FindCXXThisExpr Finder(*this); 17450 17451 switch (Proto->getExceptionSpecType()) { 17452 case EST_Unparsed: 17453 case EST_Uninstantiated: 17454 case EST_Unevaluated: 17455 case EST_BasicNoexcept: 17456 case EST_NoThrow: 17457 case EST_DynamicNone: 17458 case EST_MSAny: 17459 case EST_None: 17460 break; 17461 17462 case EST_DependentNoexcept: 17463 case EST_NoexceptFalse: 17464 case EST_NoexceptTrue: 17465 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 17466 return true; 17467 LLVM_FALLTHROUGH; 17468 17469 case EST_Dynamic: 17470 for (const auto &E : Proto->exceptions()) { 17471 if (!Finder.TraverseType(E)) 17472 return true; 17473 } 17474 break; 17475 } 17476 17477 return false; 17478 } 17479 17480 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 17481 FindCXXThisExpr Finder(*this); 17482 17483 // Check attributes. 17484 for (const auto *A : Method->attrs()) { 17485 // FIXME: This should be emitted by tblgen. 17486 Expr *Arg = nullptr; 17487 ArrayRef<Expr *> Args; 17488 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 17489 Arg = G->getArg(); 17490 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 17491 Arg = G->getArg(); 17492 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 17493 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 17494 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 17495 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 17496 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 17497 Arg = ETLF->getSuccessValue(); 17498 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 17499 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 17500 Arg = STLF->getSuccessValue(); 17501 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 17502 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 17503 Arg = LR->getArg(); 17504 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 17505 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 17506 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 17507 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 17508 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 17509 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 17510 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 17511 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 17512 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 17513 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 17514 17515 if (Arg && !Finder.TraverseStmt(Arg)) 17516 return true; 17517 17518 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 17519 if (!Finder.TraverseStmt(Args[I])) 17520 return true; 17521 } 17522 } 17523 17524 return false; 17525 } 17526 17527 void Sema::checkExceptionSpecification( 17528 bool IsTopLevel, ExceptionSpecificationType EST, 17529 ArrayRef<ParsedType> DynamicExceptions, 17530 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 17531 SmallVectorImpl<QualType> &Exceptions, 17532 FunctionProtoType::ExceptionSpecInfo &ESI) { 17533 Exceptions.clear(); 17534 ESI.Type = EST; 17535 if (EST == EST_Dynamic) { 17536 Exceptions.reserve(DynamicExceptions.size()); 17537 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 17538 // FIXME: Preserve type source info. 17539 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 17540 17541 if (IsTopLevel) { 17542 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 17543 collectUnexpandedParameterPacks(ET, Unexpanded); 17544 if (!Unexpanded.empty()) { 17545 DiagnoseUnexpandedParameterPacks( 17546 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 17547 Unexpanded); 17548 continue; 17549 } 17550 } 17551 17552 // Check that the type is valid for an exception spec, and 17553 // drop it if not. 17554 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 17555 Exceptions.push_back(ET); 17556 } 17557 ESI.Exceptions = Exceptions; 17558 return; 17559 } 17560 17561 if (isComputedNoexcept(EST)) { 17562 assert((NoexceptExpr->isTypeDependent() || 17563 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 17564 Context.BoolTy) && 17565 "Parser should have made sure that the expression is boolean"); 17566 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 17567 ESI.Type = EST_BasicNoexcept; 17568 return; 17569 } 17570 17571 ESI.NoexceptExpr = NoexceptExpr; 17572 return; 17573 } 17574 } 17575 17576 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 17577 ExceptionSpecificationType EST, 17578 SourceRange SpecificationRange, 17579 ArrayRef<ParsedType> DynamicExceptions, 17580 ArrayRef<SourceRange> DynamicExceptionRanges, 17581 Expr *NoexceptExpr) { 17582 if (!MethodD) 17583 return; 17584 17585 // Dig out the method we're referring to. 17586 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 17587 MethodD = FunTmpl->getTemplatedDecl(); 17588 17589 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 17590 if (!Method) 17591 return; 17592 17593 // Check the exception specification. 17594 llvm::SmallVector<QualType, 4> Exceptions; 17595 FunctionProtoType::ExceptionSpecInfo ESI; 17596 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 17597 DynamicExceptionRanges, NoexceptExpr, Exceptions, 17598 ESI); 17599 17600 // Update the exception specification on the function type. 17601 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 17602 17603 if (Method->isStatic()) 17604 checkThisInStaticMemberFunctionExceptionSpec(Method); 17605 17606 if (Method->isVirtual()) { 17607 // Check overrides, which we previously had to delay. 17608 for (const CXXMethodDecl *O : Method->overridden_methods()) 17609 CheckOverridingFunctionExceptionSpec(Method, O); 17610 } 17611 } 17612 17613 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 17614 /// 17615 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 17616 SourceLocation DeclStart, Declarator &D, 17617 Expr *BitWidth, 17618 InClassInitStyle InitStyle, 17619 AccessSpecifier AS, 17620 const ParsedAttr &MSPropertyAttr) { 17621 IdentifierInfo *II = D.getIdentifier(); 17622 if (!II) { 17623 Diag(DeclStart, diag::err_anonymous_property); 17624 return nullptr; 17625 } 17626 SourceLocation Loc = D.getIdentifierLoc(); 17627 17628 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 17629 QualType T = TInfo->getType(); 17630 if (getLangOpts().CPlusPlus) { 17631 CheckExtraCXXDefaultArguments(D); 17632 17633 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 17634 UPPC_DataMemberType)) { 17635 D.setInvalidType(); 17636 T = Context.IntTy; 17637 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 17638 } 17639 } 17640 17641 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 17642 17643 if (D.getDeclSpec().isInlineSpecified()) 17644 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 17645 << getLangOpts().CPlusPlus17; 17646 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 17647 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 17648 diag::err_invalid_thread) 17649 << DeclSpec::getSpecifierName(TSCS); 17650 17651 // Check to see if this name was declared as a member previously 17652 NamedDecl *PrevDecl = nullptr; 17653 LookupResult Previous(*this, II, Loc, LookupMemberName, 17654 ForVisibleRedeclaration); 17655 LookupName(Previous, S); 17656 switch (Previous.getResultKind()) { 17657 case LookupResult::Found: 17658 case LookupResult::FoundUnresolvedValue: 17659 PrevDecl = Previous.getAsSingle<NamedDecl>(); 17660 break; 17661 17662 case LookupResult::FoundOverloaded: 17663 PrevDecl = Previous.getRepresentativeDecl(); 17664 break; 17665 17666 case LookupResult::NotFound: 17667 case LookupResult::NotFoundInCurrentInstantiation: 17668 case LookupResult::Ambiguous: 17669 break; 17670 } 17671 17672 if (PrevDecl && PrevDecl->isTemplateParameter()) { 17673 // Maybe we will complain about the shadowed template parameter. 17674 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 17675 // Just pretend that we didn't see the previous declaration. 17676 PrevDecl = nullptr; 17677 } 17678 17679 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 17680 PrevDecl = nullptr; 17681 17682 SourceLocation TSSL = D.getBeginLoc(); 17683 MSPropertyDecl *NewPD = 17684 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL, 17685 MSPropertyAttr.getPropertyDataGetter(), 17686 MSPropertyAttr.getPropertyDataSetter()); 17687 ProcessDeclAttributes(TUScope, NewPD, D); 17688 NewPD->setAccess(AS); 17689 17690 if (NewPD->isInvalidDecl()) 17691 Record->setInvalidDecl(); 17692 17693 if (D.getDeclSpec().isModulePrivateSpecified()) 17694 NewPD->setModulePrivate(); 17695 17696 if (NewPD->isInvalidDecl() && PrevDecl) { 17697 // Don't introduce NewFD into scope; there's already something 17698 // with the same name in the same scope. 17699 } else if (II) { 17700 PushOnScopeChains(NewPD, S); 17701 } else 17702 Record->addDecl(NewPD); 17703 17704 return NewPD; 17705 } 17706 17707 void Sema::ActOnStartFunctionDeclarationDeclarator( 17708 Declarator &Declarator, unsigned TemplateParameterDepth) { 17709 auto &Info = InventedParameterInfos.emplace_back(); 17710 TemplateParameterList *ExplicitParams = nullptr; 17711 ArrayRef<TemplateParameterList *> ExplicitLists = 17712 Declarator.getTemplateParameterLists(); 17713 if (!ExplicitLists.empty()) { 17714 bool IsMemberSpecialization, IsInvalid; 17715 ExplicitParams = MatchTemplateParametersToScopeSpecifier( 17716 Declarator.getBeginLoc(), Declarator.getIdentifierLoc(), 17717 Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr, 17718 ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid, 17719 /*SuppressDiagnostic=*/true); 17720 } 17721 if (ExplicitParams) { 17722 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth(); 17723 for (NamedDecl *Param : *ExplicitParams) 17724 Info.TemplateParams.push_back(Param); 17725 Info.NumExplicitTemplateParams = ExplicitParams->size(); 17726 } else { 17727 Info.AutoTemplateParameterDepth = TemplateParameterDepth; 17728 Info.NumExplicitTemplateParams = 0; 17729 } 17730 } 17731 17732 void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) { 17733 auto &FSI = InventedParameterInfos.back(); 17734 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) { 17735 if (FSI.NumExplicitTemplateParams != 0) { 17736 TemplateParameterList *ExplicitParams = 17737 Declarator.getTemplateParameterLists().back(); 17738 Declarator.setInventedTemplateParameterList( 17739 TemplateParameterList::Create( 17740 Context, ExplicitParams->getTemplateLoc(), 17741 ExplicitParams->getLAngleLoc(), FSI.TemplateParams, 17742 ExplicitParams->getRAngleLoc(), 17743 ExplicitParams->getRequiresClause())); 17744 } else { 17745 Declarator.setInventedTemplateParameterList( 17746 TemplateParameterList::Create( 17747 Context, SourceLocation(), SourceLocation(), FSI.TemplateParams, 17748 SourceLocation(), /*RequiresClause=*/nullptr)); 17749 } 17750 } 17751 InventedParameterInfos.pop_back(); 17752 } 17753