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/STLExtras.h" 42 #include "llvm/ADT/SmallString.h" 43 #include "llvm/ADT/StringExtras.h" 44 #include <map> 45 #include <set> 46 47 using namespace clang; 48 49 //===----------------------------------------------------------------------===// 50 // CheckDefaultArgumentVisitor 51 //===----------------------------------------------------------------------===// 52 53 namespace { 54 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses 55 /// the default argument of a parameter to determine whether it 56 /// contains any ill-formed subexpressions. For example, this will 57 /// diagnose the use of local variables or parameters within the 58 /// default argument expression. 59 class CheckDefaultArgumentVisitor 60 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> { 61 Expr *DefaultArg; 62 Sema *S; 63 64 public: 65 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s) 66 : DefaultArg(defarg), S(s) {} 67 68 bool VisitExpr(Expr *Node); 69 bool VisitDeclRefExpr(DeclRefExpr *DRE); 70 bool VisitCXXThisExpr(CXXThisExpr *ThisE); 71 bool VisitLambdaExpr(LambdaExpr *Lambda); 72 bool VisitPseudoObjectExpr(PseudoObjectExpr *POE); 73 }; 74 75 /// VisitExpr - Visit all of the children of this expression. 76 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) { 77 bool IsInvalid = false; 78 for (Stmt *SubStmt : Node->children()) 79 IsInvalid |= Visit(SubStmt); 80 return IsInvalid; 81 } 82 83 /// VisitDeclRefExpr - Visit a reference to a declaration, to 84 /// determine whether this declaration can be used in the default 85 /// argument expression. 86 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) { 87 NamedDecl *Decl = DRE->getDecl(); 88 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) { 89 // C++ [dcl.fct.default]p9 90 // Default arguments are evaluated each time the function is 91 // called. The order of evaluation of function arguments is 92 // unspecified. Consequently, parameters of a function shall not 93 // be used in default argument expressions, even if they are not 94 // evaluated. Parameters of a function declared before a default 95 // argument expression are in scope and can hide namespace and 96 // class member names. 97 return S->Diag(DRE->getBeginLoc(), 98 diag::err_param_default_argument_references_param) 99 << Param->getDeclName() << DefaultArg->getSourceRange(); 100 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) { 101 // C++ [dcl.fct.default]p7 102 // Local variables shall not be used in default argument 103 // expressions. 104 if (VDecl->isLocalVarDecl()) 105 return S->Diag(DRE->getBeginLoc(), 106 diag::err_param_default_argument_references_local) 107 << VDecl->getDeclName() << DefaultArg->getSourceRange(); 108 } 109 110 return false; 111 } 112 113 /// VisitCXXThisExpr - Visit a C++ "this" expression. 114 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) { 115 // C++ [dcl.fct.default]p8: 116 // The keyword this shall not be used in a default argument of a 117 // member function. 118 return S->Diag(ThisE->getBeginLoc(), 119 diag::err_param_default_argument_references_this) 120 << ThisE->getSourceRange(); 121 } 122 123 bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(PseudoObjectExpr *POE) { 124 bool Invalid = false; 125 for (PseudoObjectExpr::semantics_iterator 126 i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) { 127 Expr *E = *i; 128 129 // Look through bindings. 130 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 131 E = OVE->getSourceExpr(); 132 assert(E && "pseudo-object binding without source expression?"); 133 } 134 135 Invalid |= Visit(E); 136 } 137 return Invalid; 138 } 139 140 bool CheckDefaultArgumentVisitor::VisitLambdaExpr(LambdaExpr *Lambda) { 141 // C++11 [expr.lambda.prim]p13: 142 // A lambda-expression appearing in a default argument shall not 143 // implicitly or explicitly capture any entity. 144 if (Lambda->capture_begin() == Lambda->capture_end()) 145 return false; 146 147 return S->Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg); 148 } 149 } 150 151 void 152 Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc, 153 const CXXMethodDecl *Method) { 154 // If we have an MSAny spec already, don't bother. 155 if (!Method || ComputedEST == EST_MSAny) 156 return; 157 158 const FunctionProtoType *Proto 159 = Method->getType()->getAs<FunctionProtoType>(); 160 Proto = Self->ResolveExceptionSpec(CallLoc, Proto); 161 if (!Proto) 162 return; 163 164 ExceptionSpecificationType EST = Proto->getExceptionSpecType(); 165 166 // If we have a throw-all spec at this point, ignore the function. 167 if (ComputedEST == EST_None) 168 return; 169 170 if (EST == EST_None && Method->hasAttr<NoThrowAttr>()) 171 EST = EST_BasicNoexcept; 172 173 switch (EST) { 174 case EST_Unparsed: 175 case EST_Uninstantiated: 176 case EST_Unevaluated: 177 llvm_unreachable("should not see unresolved exception specs here"); 178 179 // If this function can throw any exceptions, make a note of that. 180 case EST_MSAny: 181 case EST_None: 182 // FIXME: Whichever we see last of MSAny and None determines our result. 183 // We should make a consistent, order-independent choice here. 184 ClearExceptions(); 185 ComputedEST = EST; 186 return; 187 case EST_NoexceptFalse: 188 ClearExceptions(); 189 ComputedEST = EST_None; 190 return; 191 // FIXME: If the call to this decl is using any of its default arguments, we 192 // need to search them for potentially-throwing calls. 193 // If this function has a basic noexcept, it doesn't affect the outcome. 194 case EST_BasicNoexcept: 195 case EST_NoexceptTrue: 196 case EST_NoThrow: 197 return; 198 // If we're still at noexcept(true) and there's a throw() callee, 199 // change to that specification. 200 case EST_DynamicNone: 201 if (ComputedEST == EST_BasicNoexcept) 202 ComputedEST = EST_DynamicNone; 203 return; 204 case EST_DependentNoexcept: 205 llvm_unreachable( 206 "should not generate implicit declarations for dependent cases"); 207 case EST_Dynamic: 208 break; 209 } 210 assert(EST == EST_Dynamic && "EST case not considered earlier."); 211 assert(ComputedEST != EST_None && 212 "Shouldn't collect exceptions when throw-all is guaranteed."); 213 ComputedEST = EST_Dynamic; 214 // Record the exceptions in this function's exception specification. 215 for (const auto &E : Proto->exceptions()) 216 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second) 217 Exceptions.push_back(E); 218 } 219 220 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) { 221 if (!E || ComputedEST == EST_MSAny) 222 return; 223 224 // FIXME: 225 // 226 // C++0x [except.spec]p14: 227 // [An] implicit exception-specification specifies the type-id T if and 228 // only if T is allowed by the exception-specification of a function directly 229 // invoked by f's implicit definition; f shall allow all exceptions if any 230 // function it directly invokes allows all exceptions, and f shall allow no 231 // exceptions if every function it directly invokes allows no exceptions. 232 // 233 // Note in particular that if an implicit exception-specification is generated 234 // for a function containing a throw-expression, that specification can still 235 // be noexcept(true). 236 // 237 // Note also that 'directly invoked' is not defined in the standard, and there 238 // is no indication that we should only consider potentially-evaluated calls. 239 // 240 // Ultimately we should implement the intent of the standard: the exception 241 // specification should be the set of exceptions which can be thrown by the 242 // implicit definition. For now, we assume that any non-nothrow expression can 243 // throw any exception. 244 245 if (Self->canThrow(E)) 246 ComputedEST = EST_None; 247 } 248 249 bool 250 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg, 251 SourceLocation EqualLoc) { 252 if (RequireCompleteType(Param->getLocation(), Param->getType(), 253 diag::err_typecheck_decl_incomplete_type)) { 254 Param->setInvalidDecl(); 255 return true; 256 } 257 258 // C++ [dcl.fct.default]p5 259 // A default argument expression is implicitly converted (clause 260 // 4) to the parameter type. The default argument expression has 261 // the same semantic constraints as the initializer expression in 262 // a declaration of a variable of the parameter type, using the 263 // copy-initialization semantics (8.5). 264 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 265 Param); 266 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(), 267 EqualLoc); 268 InitializationSequence InitSeq(*this, Entity, Kind, Arg); 269 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg); 270 if (Result.isInvalid()) 271 return true; 272 Arg = Result.getAs<Expr>(); 273 274 CheckCompletedExpr(Arg, EqualLoc); 275 Arg = MaybeCreateExprWithCleanups(Arg); 276 277 // Okay: add the default argument to the parameter 278 Param->setDefaultArg(Arg); 279 280 // We have already instantiated this parameter; provide each of the 281 // instantiations with the uninstantiated default argument. 282 UnparsedDefaultArgInstantiationsMap::iterator InstPos 283 = UnparsedDefaultArgInstantiations.find(Param); 284 if (InstPos != UnparsedDefaultArgInstantiations.end()) { 285 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I) 286 InstPos->second[I]->setUninstantiatedDefaultArg(Arg); 287 288 // We're done tracking this parameter's instantiations. 289 UnparsedDefaultArgInstantiations.erase(InstPos); 290 } 291 292 return false; 293 } 294 295 /// ActOnParamDefaultArgument - Check whether the default argument 296 /// provided for a function parameter is well-formed. If so, attach it 297 /// to the parameter declaration. 298 void 299 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, 300 Expr *DefaultArg) { 301 if (!param || !DefaultArg) 302 return; 303 304 ParmVarDecl *Param = cast<ParmVarDecl>(param); 305 UnparsedDefaultArgLocs.erase(Param); 306 307 // Default arguments are only permitted in C++ 308 if (!getLangOpts().CPlusPlus) { 309 Diag(EqualLoc, diag::err_param_default_argument) 310 << DefaultArg->getSourceRange(); 311 Param->setInvalidDecl(); 312 return; 313 } 314 315 // Check for unexpanded parameter packs. 316 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) { 317 Param->setInvalidDecl(); 318 return; 319 } 320 321 // C++11 [dcl.fct.default]p3 322 // A default argument expression [...] shall not be specified for a 323 // parameter pack. 324 if (Param->isParameterPack()) { 325 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack) 326 << DefaultArg->getSourceRange(); 327 return; 328 } 329 330 // Check that the default argument is well-formed 331 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this); 332 if (DefaultArgChecker.Visit(DefaultArg)) { 333 Param->setInvalidDecl(); 334 return; 335 } 336 337 SetParamDefaultArgument(Param, DefaultArg, EqualLoc); 338 } 339 340 /// ActOnParamUnparsedDefaultArgument - We've seen a default 341 /// argument for a function parameter, but we can't parse it yet 342 /// because we're inside a class definition. Note that this default 343 /// argument will be parsed later. 344 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param, 345 SourceLocation EqualLoc, 346 SourceLocation ArgLoc) { 347 if (!param) 348 return; 349 350 ParmVarDecl *Param = cast<ParmVarDecl>(param); 351 Param->setUnparsedDefaultArg(); 352 UnparsedDefaultArgLocs[Param] = ArgLoc; 353 } 354 355 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of 356 /// the default argument for the parameter param failed. 357 void Sema::ActOnParamDefaultArgumentError(Decl *param, 358 SourceLocation EqualLoc) { 359 if (!param) 360 return; 361 362 ParmVarDecl *Param = cast<ParmVarDecl>(param); 363 Param->setInvalidDecl(); 364 UnparsedDefaultArgLocs.erase(Param); 365 Param->setDefaultArg(new(Context) 366 OpaqueValueExpr(EqualLoc, 367 Param->getType().getNonReferenceType(), 368 VK_RValue)); 369 } 370 371 /// CheckExtraCXXDefaultArguments - Check for any extra default 372 /// arguments in the declarator, which is not a function declaration 373 /// or definition and therefore is not permitted to have default 374 /// arguments. This routine should be invoked for every declarator 375 /// that is not a function declaration or definition. 376 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) { 377 // C++ [dcl.fct.default]p3 378 // A default argument expression shall be specified only in the 379 // parameter-declaration-clause of a function declaration or in a 380 // template-parameter (14.1). It shall not be specified for a 381 // parameter pack. If it is specified in a 382 // parameter-declaration-clause, it shall not occur within a 383 // declarator or abstract-declarator of a parameter-declaration. 384 bool MightBeFunction = D.isFunctionDeclarationContext(); 385 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 386 DeclaratorChunk &chunk = D.getTypeObject(i); 387 if (chunk.Kind == DeclaratorChunk::Function) { 388 if (MightBeFunction) { 389 // This is a function declaration. It can have default arguments, but 390 // keep looking in case its return type is a function type with default 391 // arguments. 392 MightBeFunction = false; 393 continue; 394 } 395 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e; 396 ++argIdx) { 397 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param); 398 if (Param->hasUnparsedDefaultArg()) { 399 std::unique_ptr<CachedTokens> Toks = 400 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens); 401 SourceRange SR; 402 if (Toks->size() > 1) 403 SR = SourceRange((*Toks)[1].getLocation(), 404 Toks->back().getLocation()); 405 else 406 SR = UnparsedDefaultArgLocs[Param]; 407 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 408 << SR; 409 } else if (Param->getDefaultArg()) { 410 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc) 411 << Param->getDefaultArg()->getSourceRange(); 412 Param->setDefaultArg(nullptr); 413 } 414 } 415 } else if (chunk.Kind != DeclaratorChunk::Paren) { 416 MightBeFunction = false; 417 } 418 } 419 } 420 421 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) { 422 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) { 423 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1); 424 if (!PVD->hasDefaultArg()) 425 return false; 426 if (!PVD->hasInheritedDefaultArg()) 427 return true; 428 } 429 return false; 430 } 431 432 /// MergeCXXFunctionDecl - Merge two declarations of the same C++ 433 /// function, once we already know that they have the same 434 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an 435 /// error, false otherwise. 436 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, 437 Scope *S) { 438 bool Invalid = false; 439 440 // The declaration context corresponding to the scope is the semantic 441 // parent, unless this is a local function declaration, in which case 442 // it is that surrounding function. 443 DeclContext *ScopeDC = New->isLocalExternDecl() 444 ? New->getLexicalDeclContext() 445 : New->getDeclContext(); 446 447 // Find the previous declaration for the purpose of default arguments. 448 FunctionDecl *PrevForDefaultArgs = Old; 449 for (/**/; PrevForDefaultArgs; 450 // Don't bother looking back past the latest decl if this is a local 451 // extern declaration; nothing else could work. 452 PrevForDefaultArgs = New->isLocalExternDecl() 453 ? nullptr 454 : PrevForDefaultArgs->getPreviousDecl()) { 455 // Ignore hidden declarations. 456 if (!LookupResult::isVisible(*this, PrevForDefaultArgs)) 457 continue; 458 459 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) && 460 !New->isCXXClassMember()) { 461 // Ignore default arguments of old decl if they are not in 462 // the same scope and this is not an out-of-line definition of 463 // a member function. 464 continue; 465 } 466 467 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) { 468 // If only one of these is a local function declaration, then they are 469 // declared in different scopes, even though isDeclInScope may think 470 // they're in the same scope. (If both are local, the scope check is 471 // sufficient, and if neither is local, then they are in the same scope.) 472 continue; 473 } 474 475 // We found the right previous declaration. 476 break; 477 } 478 479 // C++ [dcl.fct.default]p4: 480 // For non-template functions, default arguments can be added in 481 // later declarations of a function in the same 482 // scope. Declarations in different scopes have completely 483 // distinct sets of default arguments. That is, declarations in 484 // inner scopes do not acquire default arguments from 485 // declarations in outer scopes, and vice versa. In a given 486 // function declaration, all parameters subsequent to a 487 // parameter with a default argument shall have default 488 // arguments supplied in this or previous declarations. A 489 // default argument shall not be redefined by a later 490 // declaration (not even to the same value). 491 // 492 // C++ [dcl.fct.default]p6: 493 // Except for member functions of class templates, the default arguments 494 // in a member function definition that appears outside of the class 495 // definition are added to the set of default arguments provided by the 496 // member function declaration in the class definition. 497 for (unsigned p = 0, NumParams = PrevForDefaultArgs 498 ? PrevForDefaultArgs->getNumParams() 499 : 0; 500 p < NumParams; ++p) { 501 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p); 502 ParmVarDecl *NewParam = New->getParamDecl(p); 503 504 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false; 505 bool NewParamHasDfl = NewParam->hasDefaultArg(); 506 507 if (OldParamHasDfl && NewParamHasDfl) { 508 unsigned DiagDefaultParamID = 509 diag::err_param_default_argument_redefinition; 510 511 // MSVC accepts that default parameters be redefined for member functions 512 // of template class. The new default parameter's value is ignored. 513 Invalid = true; 514 if (getLangOpts().MicrosoftExt) { 515 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New); 516 if (MD && MD->getParent()->getDescribedClassTemplate()) { 517 // Merge the old default argument into the new parameter. 518 NewParam->setHasInheritedDefaultArg(); 519 if (OldParam->hasUninstantiatedDefaultArg()) 520 NewParam->setUninstantiatedDefaultArg( 521 OldParam->getUninstantiatedDefaultArg()); 522 else 523 NewParam->setDefaultArg(OldParam->getInit()); 524 DiagDefaultParamID = diag::ext_param_default_argument_redefinition; 525 Invalid = false; 526 } 527 } 528 529 // FIXME: If we knew where the '=' was, we could easily provide a fix-it 530 // hint here. Alternatively, we could walk the type-source information 531 // for NewParam to find the last source location in the type... but it 532 // isn't worth the effort right now. This is the kind of test case that 533 // is hard to get right: 534 // int f(int); 535 // void g(int (*fp)(int) = f); 536 // void g(int (*fp)(int) = &f); 537 Diag(NewParam->getLocation(), DiagDefaultParamID) 538 << NewParam->getDefaultArgRange(); 539 540 // Look for the function declaration where the default argument was 541 // actually written, which may be a declaration prior to Old. 542 for (auto Older = PrevForDefaultArgs; 543 OldParam->hasInheritedDefaultArg(); /**/) { 544 Older = Older->getPreviousDecl(); 545 OldParam = Older->getParamDecl(p); 546 } 547 548 Diag(OldParam->getLocation(), diag::note_previous_definition) 549 << OldParam->getDefaultArgRange(); 550 } else if (OldParamHasDfl) { 551 // Merge the old default argument into the new parameter unless the new 552 // function is a friend declaration in a template class. In the latter 553 // case the default arguments will be inherited when the friend 554 // declaration will be instantiated. 555 if (New->getFriendObjectKind() == Decl::FOK_None || 556 !New->getLexicalDeclContext()->isDependentContext()) { 557 // It's important to use getInit() here; getDefaultArg() 558 // strips off any top-level ExprWithCleanups. 559 NewParam->setHasInheritedDefaultArg(); 560 if (OldParam->hasUnparsedDefaultArg()) 561 NewParam->setUnparsedDefaultArg(); 562 else if (OldParam->hasUninstantiatedDefaultArg()) 563 NewParam->setUninstantiatedDefaultArg( 564 OldParam->getUninstantiatedDefaultArg()); 565 else 566 NewParam->setDefaultArg(OldParam->getInit()); 567 } 568 } else if (NewParamHasDfl) { 569 if (New->getDescribedFunctionTemplate()) { 570 // Paragraph 4, quoted above, only applies to non-template functions. 571 Diag(NewParam->getLocation(), 572 diag::err_param_default_argument_template_redecl) 573 << NewParam->getDefaultArgRange(); 574 Diag(PrevForDefaultArgs->getLocation(), 575 diag::note_template_prev_declaration) 576 << false; 577 } else if (New->getTemplateSpecializationKind() 578 != TSK_ImplicitInstantiation && 579 New->getTemplateSpecializationKind() != TSK_Undeclared) { 580 // C++ [temp.expr.spec]p21: 581 // Default function arguments shall not be specified in a declaration 582 // or a definition for one of the following explicit specializations: 583 // - the explicit specialization of a function template; 584 // - the explicit specialization of a member function template; 585 // - the explicit specialization of a member function of a class 586 // template where the class template specialization to which the 587 // member function specialization belongs is implicitly 588 // instantiated. 589 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg) 590 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization) 591 << New->getDeclName() 592 << NewParam->getDefaultArgRange(); 593 } else if (New->getDeclContext()->isDependentContext()) { 594 // C++ [dcl.fct.default]p6 (DR217): 595 // Default arguments for a member function of a class template shall 596 // be specified on the initial declaration of the member function 597 // within the class template. 598 // 599 // Reading the tea leaves a bit in DR217 and its reference to DR205 600 // leads me to the conclusion that one cannot add default function 601 // arguments for an out-of-line definition of a member function of a 602 // dependent type. 603 int WhichKind = 2; 604 if (CXXRecordDecl *Record 605 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) { 606 if (Record->getDescribedClassTemplate()) 607 WhichKind = 0; 608 else if (isa<ClassTemplatePartialSpecializationDecl>(Record)) 609 WhichKind = 1; 610 else 611 WhichKind = 2; 612 } 613 614 Diag(NewParam->getLocation(), 615 diag::err_param_default_argument_member_template_redecl) 616 << WhichKind 617 << NewParam->getDefaultArgRange(); 618 } 619 } 620 } 621 622 // DR1344: If a default argument is added outside a class definition and that 623 // default argument makes the function a special member function, the program 624 // is ill-formed. This can only happen for constructors. 625 if (isa<CXXConstructorDecl>(New) && 626 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) { 627 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)), 628 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old)); 629 if (NewSM != OldSM) { 630 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments()); 631 assert(NewParam->hasDefaultArg()); 632 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special) 633 << NewParam->getDefaultArgRange() << NewSM; 634 Diag(Old->getLocation(), diag::note_previous_declaration); 635 } 636 } 637 638 const FunctionDecl *Def; 639 // C++11 [dcl.constexpr]p1: If any declaration of a function or function 640 // template has a constexpr specifier then all its declarations shall 641 // contain the constexpr specifier. 642 if (New->getConstexprKind() != Old->getConstexprKind()) { 643 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch) 644 << New << New->getConstexprKind() << Old->getConstexprKind(); 645 Diag(Old->getLocation(), diag::note_previous_declaration); 646 Invalid = true; 647 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() && 648 Old->isDefined(Def) && 649 // If a friend function is inlined but does not have 'inline' 650 // specifier, it is a definition. Do not report attribute conflict 651 // in this case, redefinition will be diagnosed later. 652 (New->isInlineSpecified() || 653 New->getFriendObjectKind() == Decl::FOK_None)) { 654 // C++11 [dcl.fcn.spec]p4: 655 // If the definition of a function appears in a translation unit before its 656 // first declaration as inline, the program is ill-formed. 657 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 658 Diag(Def->getLocation(), diag::note_previous_definition); 659 Invalid = true; 660 } 661 662 // C++17 [temp.deduct.guide]p3: 663 // Two deduction guide declarations in the same translation unit 664 // for the same class template shall not have equivalent 665 // parameter-declaration-clauses. 666 if (isa<CXXDeductionGuideDecl>(New) && 667 !New->isFunctionTemplateSpecialization()) { 668 Diag(New->getLocation(), diag::err_deduction_guide_redeclared); 669 Diag(Old->getLocation(), diag::note_previous_declaration); 670 } 671 672 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default 673 // argument expression, that declaration shall be a definition and shall be 674 // the only declaration of the function or function template in the 675 // translation unit. 676 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared && 677 functionDeclHasDefaultArgument(Old)) { 678 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 679 Diag(Old->getLocation(), diag::note_previous_declaration); 680 Invalid = true; 681 } 682 683 return Invalid; 684 } 685 686 NamedDecl * 687 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D, 688 MultiTemplateParamsArg TemplateParamLists) { 689 assert(D.isDecompositionDeclarator()); 690 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 691 692 // The syntax only allows a decomposition declarator as a simple-declaration, 693 // a for-range-declaration, or a condition in Clang, but we parse it in more 694 // cases than that. 695 if (!D.mayHaveDecompositionDeclarator()) { 696 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 697 << Decomp.getSourceRange(); 698 return nullptr; 699 } 700 701 if (!TemplateParamLists.empty()) { 702 // FIXME: There's no rule against this, but there are also no rules that 703 // would actually make it usable, so we reject it for now. 704 Diag(TemplateParamLists.front()->getTemplateLoc(), 705 diag::err_decomp_decl_template); 706 return nullptr; 707 } 708 709 Diag(Decomp.getLSquareLoc(), 710 !getLangOpts().CPlusPlus17 711 ? diag::ext_decomp_decl 712 : D.getContext() == DeclaratorContext::ConditionContext 713 ? diag::ext_decomp_decl_cond 714 : diag::warn_cxx14_compat_decomp_decl) 715 << Decomp.getSourceRange(); 716 717 // The semantic context is always just the current context. 718 DeclContext *const DC = CurContext; 719 720 // C++17 [dcl.dcl]/8: 721 // The decl-specifier-seq shall contain only the type-specifier auto 722 // and cv-qualifiers. 723 // C++2a [dcl.dcl]/8: 724 // If decl-specifier-seq contains any decl-specifier other than static, 725 // thread_local, auto, or cv-qualifiers, the program is ill-formed. 726 auto &DS = D.getDeclSpec(); 727 { 728 SmallVector<StringRef, 8> BadSpecifiers; 729 SmallVector<SourceLocation, 8> BadSpecifierLocs; 730 SmallVector<StringRef, 8> CPlusPlus20Specifiers; 731 SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs; 732 if (auto SCS = DS.getStorageClassSpec()) { 733 if (SCS == DeclSpec::SCS_static) { 734 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS)); 735 CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 736 } else { 737 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS)); 738 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc()); 739 } 740 } 741 if (auto TSCS = DS.getThreadStorageClassSpec()) { 742 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS)); 743 CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc()); 744 } 745 if (DS.hasConstexprSpecifier()) { 746 BadSpecifiers.push_back( 747 DeclSpec::getSpecifierName(DS.getConstexprSpecifier())); 748 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc()); 749 } 750 if (DS.isInlineSpecified()) { 751 BadSpecifiers.push_back("inline"); 752 BadSpecifierLocs.push_back(DS.getInlineSpecLoc()); 753 } 754 if (!BadSpecifiers.empty()) { 755 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec); 756 Err << (int)BadSpecifiers.size() 757 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " "); 758 // Don't add FixItHints to remove the specifiers; we do still respect 759 // them when building the underlying variable. 760 for (auto Loc : BadSpecifierLocs) 761 Err << SourceRange(Loc, Loc); 762 } else if (!CPlusPlus20Specifiers.empty()) { 763 auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(), 764 getLangOpts().CPlusPlus2a 765 ? diag::warn_cxx17_compat_decomp_decl_spec 766 : diag::ext_decomp_decl_spec); 767 Warn << (int)CPlusPlus20Specifiers.size() 768 << llvm::join(CPlusPlus20Specifiers.begin(), 769 CPlusPlus20Specifiers.end(), " "); 770 for (auto Loc : CPlusPlus20SpecifierLocs) 771 Warn << SourceRange(Loc, Loc); 772 } 773 // We can't recover from it being declared as a typedef. 774 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 775 return nullptr; 776 } 777 778 // C++2a [dcl.struct.bind]p1: 779 // A cv that includes volatile is deprecated 780 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) && 781 getLangOpts().CPlusPlus2a) 782 Diag(DS.getVolatileSpecLoc(), 783 diag::warn_deprecated_volatile_structured_binding); 784 785 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 786 QualType R = TInfo->getType(); 787 788 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 789 UPPC_DeclarationType)) 790 D.setInvalidType(); 791 792 // The syntax only allows a single ref-qualifier prior to the decomposition 793 // declarator. No other declarator chunks are permitted. Also check the type 794 // specifier here. 795 if (DS.getTypeSpecType() != DeclSpec::TST_auto || 796 D.hasGroupingParens() || D.getNumTypeObjects() > 1 || 797 (D.getNumTypeObjects() == 1 && 798 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) { 799 Diag(Decomp.getLSquareLoc(), 800 (D.hasGroupingParens() || 801 (D.getNumTypeObjects() && 802 D.getTypeObject(0).Kind == DeclaratorChunk::Paren)) 803 ? diag::err_decomp_decl_parens 804 : diag::err_decomp_decl_type) 805 << R; 806 807 // In most cases, there's no actual problem with an explicitly-specified 808 // type, but a function type won't work here, and ActOnVariableDeclarator 809 // shouldn't be called for such a type. 810 if (R->isFunctionType()) 811 D.setInvalidType(); 812 } 813 814 // Build the BindingDecls. 815 SmallVector<BindingDecl*, 8> Bindings; 816 817 // Build the BindingDecls. 818 for (auto &B : D.getDecompositionDeclarator().bindings()) { 819 // Check for name conflicts. 820 DeclarationNameInfo NameInfo(B.Name, B.NameLoc); 821 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 822 ForVisibleRedeclaration); 823 LookupName(Previous, S, 824 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit()); 825 826 // It's not permitted to shadow a template parameter name. 827 if (Previous.isSingleResult() && 828 Previous.getFoundDecl()->isTemplateParameter()) { 829 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 830 Previous.getFoundDecl()); 831 Previous.clear(); 832 } 833 834 bool ConsiderLinkage = DC->isFunctionOrMethod() && 835 DS.getStorageClassSpec() == DeclSpec::SCS_extern; 836 FilterLookupForScope(Previous, DC, S, ConsiderLinkage, 837 /*AllowInlineNamespace*/false); 838 if (!Previous.empty()) { 839 auto *Old = Previous.getRepresentativeDecl(); 840 Diag(B.NameLoc, diag::err_redefinition) << B.Name; 841 Diag(Old->getLocation(), diag::note_previous_definition); 842 } 843 844 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name); 845 PushOnScopeChains(BD, S, true); 846 Bindings.push_back(BD); 847 ParsingInitForAutoVars.insert(BD); 848 } 849 850 // There are no prior lookup results for the variable itself, because it 851 // is unnamed. 852 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr, 853 Decomp.getLSquareLoc()); 854 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 855 ForVisibleRedeclaration); 856 857 // Build the variable that holds the non-decomposed object. 858 bool AddToScope = true; 859 NamedDecl *New = 860 ActOnVariableDeclarator(S, D, DC, TInfo, Previous, 861 MultiTemplateParamsArg(), AddToScope, Bindings); 862 if (AddToScope) { 863 S->AddDecl(New); 864 CurContext->addHiddenDecl(New); 865 } 866 867 if (isInOpenMPDeclareTargetContext()) 868 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 869 870 return New; 871 } 872 873 static bool checkSimpleDecomposition( 874 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src, 875 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType, 876 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) { 877 if ((int64_t)Bindings.size() != NumElems) { 878 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 879 << DecompType << (unsigned)Bindings.size() << NumElems.toString(10) 880 << (NumElems < Bindings.size()); 881 return true; 882 } 883 884 unsigned I = 0; 885 for (auto *B : Bindings) { 886 SourceLocation Loc = B->getLocation(); 887 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 888 if (E.isInvalid()) 889 return true; 890 E = GetInit(Loc, E.get(), I++); 891 if (E.isInvalid()) 892 return true; 893 B->setBinding(ElemType, E.get()); 894 } 895 896 return false; 897 } 898 899 static bool checkArrayLikeDecomposition(Sema &S, 900 ArrayRef<BindingDecl *> Bindings, 901 ValueDecl *Src, QualType DecompType, 902 const llvm::APSInt &NumElems, 903 QualType ElemType) { 904 return checkSimpleDecomposition( 905 S, Bindings, Src, DecompType, NumElems, ElemType, 906 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 907 ExprResult E = S.ActOnIntegerConstant(Loc, I); 908 if (E.isInvalid()) 909 return ExprError(); 910 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc); 911 }); 912 } 913 914 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 915 ValueDecl *Src, QualType DecompType, 916 const ConstantArrayType *CAT) { 917 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType, 918 llvm::APSInt(CAT->getSize()), 919 CAT->getElementType()); 920 } 921 922 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 923 ValueDecl *Src, QualType DecompType, 924 const VectorType *VT) { 925 return checkArrayLikeDecomposition( 926 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()), 927 S.Context.getQualifiedType(VT->getElementType(), 928 DecompType.getQualifiers())); 929 } 930 931 static bool checkComplexDecomposition(Sema &S, 932 ArrayRef<BindingDecl *> Bindings, 933 ValueDecl *Src, QualType DecompType, 934 const ComplexType *CT) { 935 return checkSimpleDecomposition( 936 S, Bindings, Src, DecompType, llvm::APSInt::get(2), 937 S.Context.getQualifiedType(CT->getElementType(), 938 DecompType.getQualifiers()), 939 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 940 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base); 941 }); 942 } 943 944 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy, 945 TemplateArgumentListInfo &Args) { 946 SmallString<128> SS; 947 llvm::raw_svector_ostream OS(SS); 948 bool First = true; 949 for (auto &Arg : Args.arguments()) { 950 if (!First) 951 OS << ", "; 952 Arg.getArgument().print(PrintingPolicy, OS); 953 First = false; 954 } 955 return OS.str(); 956 } 957 958 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup, 959 SourceLocation Loc, StringRef Trait, 960 TemplateArgumentListInfo &Args, 961 unsigned DiagID) { 962 auto DiagnoseMissing = [&] { 963 if (DiagID) 964 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(), 965 Args); 966 return true; 967 }; 968 969 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine. 970 NamespaceDecl *Std = S.getStdNamespace(); 971 if (!Std) 972 return DiagnoseMissing(); 973 974 // Look up the trait itself, within namespace std. We can diagnose various 975 // problems with this lookup even if we've been asked to not diagnose a 976 // missing specialization, because this can only fail if the user has been 977 // declaring their own names in namespace std or we don't support the 978 // standard library implementation in use. 979 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait), 980 Loc, Sema::LookupOrdinaryName); 981 if (!S.LookupQualifiedName(Result, Std)) 982 return DiagnoseMissing(); 983 if (Result.isAmbiguous()) 984 return true; 985 986 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>(); 987 if (!TraitTD) { 988 Result.suppressDiagnostics(); 989 NamedDecl *Found = *Result.begin(); 990 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait; 991 S.Diag(Found->getLocation(), diag::note_declared_at); 992 return true; 993 } 994 995 // Build the template-id. 996 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args); 997 if (TraitTy.isNull()) 998 return true; 999 if (!S.isCompleteType(Loc, TraitTy)) { 1000 if (DiagID) 1001 S.RequireCompleteType( 1002 Loc, TraitTy, DiagID, 1003 printTemplateArgs(S.Context.getPrintingPolicy(), Args)); 1004 return true; 1005 } 1006 1007 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl(); 1008 assert(RD && "specialization of class template is not a class?"); 1009 1010 // Look up the member of the trait type. 1011 S.LookupQualifiedName(TraitMemberLookup, RD); 1012 return TraitMemberLookup.isAmbiguous(); 1013 } 1014 1015 static TemplateArgumentLoc 1016 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, 1017 uint64_t I) { 1018 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T); 1019 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc); 1020 } 1021 1022 static TemplateArgumentLoc 1023 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) { 1024 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc); 1025 } 1026 1027 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; } 1028 1029 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, 1030 llvm::APSInt &Size) { 1031 EnterExpressionEvaluationContext ContextRAII( 1032 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 1033 1034 DeclarationName Value = S.PP.getIdentifierInfo("value"); 1035 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName); 1036 1037 // Form template argument list for tuple_size<T>. 1038 TemplateArgumentListInfo Args(Loc, Loc); 1039 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1040 1041 // If there's no tuple_size specialization or the lookup of 'value' is empty, 1042 // it's not tuple-like. 1043 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) || 1044 R.empty()) 1045 return IsTupleLike::NotTupleLike; 1046 1047 // If we get this far, we've committed to the tuple interpretation, but 1048 // we can still fail if there actually isn't a usable ::value. 1049 1050 struct ICEDiagnoser : Sema::VerifyICEDiagnoser { 1051 LookupResult &R; 1052 TemplateArgumentListInfo &Args; 1053 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args) 1054 : R(R), Args(Args) {} 1055 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { 1056 S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant) 1057 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1058 } 1059 } Diagnoser(R, Args); 1060 1061 ExprResult E = 1062 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false); 1063 if (E.isInvalid()) 1064 return IsTupleLike::Error; 1065 1066 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false); 1067 if (E.isInvalid()) 1068 return IsTupleLike::Error; 1069 1070 return IsTupleLike::TupleLike; 1071 } 1072 1073 /// \return std::tuple_element<I, T>::type. 1074 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, 1075 unsigned I, QualType T) { 1076 // Form template argument list for tuple_element<I, T>. 1077 TemplateArgumentListInfo Args(Loc, Loc); 1078 Args.addArgument( 1079 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1080 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1081 1082 DeclarationName TypeDN = S.PP.getIdentifierInfo("type"); 1083 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName); 1084 if (lookupStdTypeTraitMember( 1085 S, R, Loc, "tuple_element", Args, 1086 diag::err_decomp_decl_std_tuple_element_not_specialized)) 1087 return QualType(); 1088 1089 auto *TD = R.getAsSingle<TypeDecl>(); 1090 if (!TD) { 1091 R.suppressDiagnostics(); 1092 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized) 1093 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1094 if (!R.empty()) 1095 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at); 1096 return QualType(); 1097 } 1098 1099 return S.Context.getTypeDeclType(TD); 1100 } 1101 1102 namespace { 1103 struct BindingDiagnosticTrap { 1104 Sema &S; 1105 DiagnosticErrorTrap Trap; 1106 BindingDecl *BD; 1107 1108 BindingDiagnosticTrap(Sema &S, BindingDecl *BD) 1109 : S(S), Trap(S.Diags), BD(BD) {} 1110 ~BindingDiagnosticTrap() { 1111 if (Trap.hasErrorOccurred()) 1112 S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD; 1113 } 1114 }; 1115 } 1116 1117 static bool checkTupleLikeDecomposition(Sema &S, 1118 ArrayRef<BindingDecl *> Bindings, 1119 VarDecl *Src, QualType DecompType, 1120 const llvm::APSInt &TupleSize) { 1121 if ((int64_t)Bindings.size() != TupleSize) { 1122 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1123 << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10) 1124 << (TupleSize < Bindings.size()); 1125 return true; 1126 } 1127 1128 if (Bindings.empty()) 1129 return false; 1130 1131 DeclarationName GetDN = S.PP.getIdentifierInfo("get"); 1132 1133 // [dcl.decomp]p3: 1134 // The unqualified-id get is looked up in the scope of E by class member 1135 // access lookup ... 1136 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName); 1137 bool UseMemberGet = false; 1138 if (S.isCompleteType(Src->getLocation(), DecompType)) { 1139 if (auto *RD = DecompType->getAsCXXRecordDecl()) 1140 S.LookupQualifiedName(MemberGet, RD); 1141 if (MemberGet.isAmbiguous()) 1142 return true; 1143 // ... and if that finds at least one declaration that is a function 1144 // template whose first template parameter is a non-type parameter ... 1145 for (NamedDecl *D : MemberGet) { 1146 if (FunctionTemplateDecl *FTD = 1147 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) { 1148 TemplateParameterList *TPL = FTD->getTemplateParameters(); 1149 if (TPL->size() != 0 && 1150 isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) { 1151 // ... the initializer is e.get<i>(). 1152 UseMemberGet = true; 1153 break; 1154 } 1155 } 1156 } 1157 } 1158 1159 unsigned I = 0; 1160 for (auto *B : Bindings) { 1161 BindingDiagnosticTrap Trap(S, B); 1162 SourceLocation Loc = B->getLocation(); 1163 1164 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1165 if (E.isInvalid()) 1166 return true; 1167 1168 // e is an lvalue if the type of the entity is an lvalue reference and 1169 // an xvalue otherwise 1170 if (!Src->getType()->isLValueReferenceType()) 1171 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp, 1172 E.get(), nullptr, VK_XValue); 1173 1174 TemplateArgumentListInfo Args(Loc, Loc); 1175 Args.addArgument( 1176 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1177 1178 if (UseMemberGet) { 1179 // if [lookup of member get] finds at least one declaration, the 1180 // initializer is e.get<i-1>(). 1181 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false, 1182 CXXScopeSpec(), SourceLocation(), nullptr, 1183 MemberGet, &Args, nullptr); 1184 if (E.isInvalid()) 1185 return true; 1186 1187 E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc); 1188 } else { 1189 // Otherwise, the initializer is get<i-1>(e), where get is looked up 1190 // in the associated namespaces. 1191 Expr *Get = UnresolvedLookupExpr::Create( 1192 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(), 1193 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args, 1194 UnresolvedSetIterator(), UnresolvedSetIterator()); 1195 1196 Expr *Arg = E.get(); 1197 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc); 1198 } 1199 if (E.isInvalid()) 1200 return true; 1201 Expr *Init = E.get(); 1202 1203 // Given the type T designated by std::tuple_element<i - 1, E>::type, 1204 QualType T = getTupleLikeElementType(S, Loc, I, DecompType); 1205 if (T.isNull()) 1206 return true; 1207 1208 // each vi is a variable of type "reference to T" initialized with the 1209 // initializer, where the reference is an lvalue reference if the 1210 // initializer is an lvalue and an rvalue reference otherwise 1211 QualType RefType = 1212 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName()); 1213 if (RefType.isNull()) 1214 return true; 1215 auto *RefVD = VarDecl::Create( 1216 S.Context, Src->getDeclContext(), Loc, Loc, 1217 B->getDeclName().getAsIdentifierInfo(), RefType, 1218 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass()); 1219 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext()); 1220 RefVD->setTSCSpec(Src->getTSCSpec()); 1221 RefVD->setImplicit(); 1222 if (Src->isInlineSpecified()) 1223 RefVD->setInlineSpecified(); 1224 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD); 1225 1226 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD); 1227 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc); 1228 InitializationSequence Seq(S, Entity, Kind, Init); 1229 E = Seq.Perform(S, Entity, Kind, Init); 1230 if (E.isInvalid()) 1231 return true; 1232 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false); 1233 if (E.isInvalid()) 1234 return true; 1235 RefVD->setInit(E.get()); 1236 if (!E.get()->isValueDependent()) 1237 RefVD->checkInitIsICE(); 1238 1239 E = S.BuildDeclarationNameExpr(CXXScopeSpec(), 1240 DeclarationNameInfo(B->getDeclName(), Loc), 1241 RefVD); 1242 if (E.isInvalid()) 1243 return true; 1244 1245 B->setBinding(T, E.get()); 1246 I++; 1247 } 1248 1249 return false; 1250 } 1251 1252 /// Find the base class to decompose in a built-in decomposition of a class type. 1253 /// This base class search is, unfortunately, not quite like any other that we 1254 /// perform anywhere else in C++. 1255 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc, 1256 const CXXRecordDecl *RD, 1257 CXXCastPath &BasePath) { 1258 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier, 1259 CXXBasePath &Path) { 1260 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields(); 1261 }; 1262 1263 const CXXRecordDecl *ClassWithFields = nullptr; 1264 AccessSpecifier AS = AS_public; 1265 if (RD->hasDirectFields()) 1266 // [dcl.decomp]p4: 1267 // Otherwise, all of E's non-static data members shall be public direct 1268 // members of E ... 1269 ClassWithFields = RD; 1270 else { 1271 // ... or of ... 1272 CXXBasePaths Paths; 1273 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD)); 1274 if (!RD->lookupInBases(BaseHasFields, Paths)) { 1275 // If no classes have fields, just decompose RD itself. (This will work 1276 // if and only if zero bindings were provided.) 1277 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public); 1278 } 1279 1280 CXXBasePath *BestPath = nullptr; 1281 for (auto &P : Paths) { 1282 if (!BestPath) 1283 BestPath = &P; 1284 else if (!S.Context.hasSameType(P.back().Base->getType(), 1285 BestPath->back().Base->getType())) { 1286 // ... the same ... 1287 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1288 << false << RD << BestPath->back().Base->getType() 1289 << P.back().Base->getType(); 1290 return DeclAccessPair(); 1291 } else if (P.Access < BestPath->Access) { 1292 BestPath = &P; 1293 } 1294 } 1295 1296 // ... unambiguous ... 1297 QualType BaseType = BestPath->back().Base->getType(); 1298 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) { 1299 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base) 1300 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths); 1301 return DeclAccessPair(); 1302 } 1303 1304 // ... [accessible, implied by other rules] base class of E. 1305 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD), 1306 *BestPath, diag::err_decomp_decl_inaccessible_base); 1307 AS = BestPath->Access; 1308 1309 ClassWithFields = BaseType->getAsCXXRecordDecl(); 1310 S.BuildBasePathArray(Paths, BasePath); 1311 } 1312 1313 // The above search did not check whether the selected class itself has base 1314 // classes with fields, so check that now. 1315 CXXBasePaths Paths; 1316 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) { 1317 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1318 << (ClassWithFields == RD) << RD << ClassWithFields 1319 << Paths.front().back().Base->getType(); 1320 return DeclAccessPair(); 1321 } 1322 1323 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS); 1324 } 1325 1326 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 1327 ValueDecl *Src, QualType DecompType, 1328 const CXXRecordDecl *OrigRD) { 1329 if (S.RequireCompleteType(Src->getLocation(), DecompType, 1330 diag::err_incomplete_type)) 1331 return true; 1332 1333 CXXCastPath BasePath; 1334 DeclAccessPair BasePair = 1335 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath); 1336 const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl()); 1337 if (!RD) 1338 return true; 1339 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD), 1340 DecompType.getQualifiers()); 1341 1342 auto DiagnoseBadNumberOfBindings = [&]() -> bool { 1343 unsigned NumFields = 1344 std::count_if(RD->field_begin(), RD->field_end(), 1345 [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); }); 1346 assert(Bindings.size() != NumFields); 1347 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1348 << DecompType << (unsigned)Bindings.size() << NumFields 1349 << (NumFields < Bindings.size()); 1350 return true; 1351 }; 1352 1353 // all of E's non-static data members shall be [...] well-formed 1354 // when named as e.name in the context of the structured binding, 1355 // E shall not have an anonymous union member, ... 1356 unsigned I = 0; 1357 for (auto *FD : RD->fields()) { 1358 if (FD->isUnnamedBitfield()) 1359 continue; 1360 1361 if (FD->isAnonymousStructOrUnion()) { 1362 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member) 1363 << DecompType << FD->getType()->isUnionType(); 1364 S.Diag(FD->getLocation(), diag::note_declared_at); 1365 return true; 1366 } 1367 1368 // We have a real field to bind. 1369 if (I >= Bindings.size()) 1370 return DiagnoseBadNumberOfBindings(); 1371 auto *B = Bindings[I++]; 1372 SourceLocation Loc = B->getLocation(); 1373 1374 // The field must be accessible in the context of the structured binding. 1375 // We already checked that the base class is accessible. 1376 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the 1377 // const_cast here. 1378 S.CheckStructuredBindingMemberAccess( 1379 Loc, const_cast<CXXRecordDecl *>(OrigRD), 1380 DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess( 1381 BasePair.getAccess(), FD->getAccess()))); 1382 1383 // Initialize the binding to Src.FD. 1384 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1385 if (E.isInvalid()) 1386 return true; 1387 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase, 1388 VK_LValue, &BasePath); 1389 if (E.isInvalid()) 1390 return true; 1391 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc, 1392 CXXScopeSpec(), FD, 1393 DeclAccessPair::make(FD, FD->getAccess()), 1394 DeclarationNameInfo(FD->getDeclName(), Loc)); 1395 if (E.isInvalid()) 1396 return true; 1397 1398 // If the type of the member is T, the referenced type is cv T, where cv is 1399 // the cv-qualification of the decomposition expression. 1400 // 1401 // FIXME: We resolve a defect here: if the field is mutable, we do not add 1402 // 'const' to the type of the field. 1403 Qualifiers Q = DecompType.getQualifiers(); 1404 if (FD->isMutable()) 1405 Q.removeConst(); 1406 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get()); 1407 } 1408 1409 if (I != Bindings.size()) 1410 return DiagnoseBadNumberOfBindings(); 1411 1412 return false; 1413 } 1414 1415 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) { 1416 QualType DecompType = DD->getType(); 1417 1418 // If the type of the decomposition is dependent, then so is the type of 1419 // each binding. 1420 if (DecompType->isDependentType()) { 1421 for (auto *B : DD->bindings()) 1422 B->setType(Context.DependentTy); 1423 return; 1424 } 1425 1426 DecompType = DecompType.getNonReferenceType(); 1427 ArrayRef<BindingDecl*> Bindings = DD->bindings(); 1428 1429 // C++1z [dcl.decomp]/2: 1430 // If E is an array type [...] 1431 // As an extension, we also support decomposition of built-in complex and 1432 // vector types. 1433 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) { 1434 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT)) 1435 DD->setInvalidDecl(); 1436 return; 1437 } 1438 if (auto *VT = DecompType->getAs<VectorType>()) { 1439 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT)) 1440 DD->setInvalidDecl(); 1441 return; 1442 } 1443 if (auto *CT = DecompType->getAs<ComplexType>()) { 1444 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT)) 1445 DD->setInvalidDecl(); 1446 return; 1447 } 1448 1449 // C++1z [dcl.decomp]/3: 1450 // if the expression std::tuple_size<E>::value is a well-formed integral 1451 // constant expression, [...] 1452 llvm::APSInt TupleSize(32); 1453 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) { 1454 case IsTupleLike::Error: 1455 DD->setInvalidDecl(); 1456 return; 1457 1458 case IsTupleLike::TupleLike: 1459 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize)) 1460 DD->setInvalidDecl(); 1461 return; 1462 1463 case IsTupleLike::NotTupleLike: 1464 break; 1465 } 1466 1467 // C++1z [dcl.dcl]/8: 1468 // [E shall be of array or non-union class type] 1469 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl(); 1470 if (!RD || RD->isUnion()) { 1471 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type) 1472 << DD << !RD << DecompType; 1473 DD->setInvalidDecl(); 1474 return; 1475 } 1476 1477 // C++1z [dcl.decomp]/4: 1478 // all of E's non-static data members shall be [...] direct members of 1479 // E or of the same unambiguous public base class of E, ... 1480 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD)) 1481 DD->setInvalidDecl(); 1482 } 1483 1484 /// Merge the exception specifications of two variable declarations. 1485 /// 1486 /// This is called when there's a redeclaration of a VarDecl. The function 1487 /// checks if the redeclaration might have an exception specification and 1488 /// validates compatibility and merges the specs if necessary. 1489 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 1490 // Shortcut if exceptions are disabled. 1491 if (!getLangOpts().CXXExceptions) 1492 return; 1493 1494 assert(Context.hasSameType(New->getType(), Old->getType()) && 1495 "Should only be called if types are otherwise the same."); 1496 1497 QualType NewType = New->getType(); 1498 QualType OldType = Old->getType(); 1499 1500 // We're only interested in pointers and references to functions, as well 1501 // as pointers to member functions. 1502 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 1503 NewType = R->getPointeeType(); 1504 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 1505 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 1506 NewType = P->getPointeeType(); 1507 OldType = OldType->getAs<PointerType>()->getPointeeType(); 1508 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 1509 NewType = M->getPointeeType(); 1510 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 1511 } 1512 1513 if (!NewType->isFunctionProtoType()) 1514 return; 1515 1516 // There's lots of special cases for functions. For function pointers, system 1517 // libraries are hopefully not as broken so that we don't need these 1518 // workarounds. 1519 if (CheckEquivalentExceptionSpec( 1520 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 1521 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 1522 New->setInvalidDecl(); 1523 } 1524 } 1525 1526 /// CheckCXXDefaultArguments - Verify that the default arguments for a 1527 /// function declaration are well-formed according to C++ 1528 /// [dcl.fct.default]. 1529 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 1530 unsigned NumParams = FD->getNumParams(); 1531 unsigned p; 1532 1533 // Find first parameter with a default argument 1534 for (p = 0; p < NumParams; ++p) { 1535 ParmVarDecl *Param = FD->getParamDecl(p); 1536 if (Param->hasDefaultArg()) 1537 break; 1538 } 1539 1540 // C++11 [dcl.fct.default]p4: 1541 // In a given function declaration, each parameter subsequent to a parameter 1542 // with a default argument shall have a default argument supplied in this or 1543 // a previous declaration or shall be a function parameter pack. A default 1544 // argument shall not be redefined by a later declaration (not even to the 1545 // same value). 1546 unsigned LastMissingDefaultArg = 0; 1547 for (; p < NumParams; ++p) { 1548 ParmVarDecl *Param = FD->getParamDecl(p); 1549 if (!Param->hasDefaultArg() && !Param->isParameterPack()) { 1550 if (Param->isInvalidDecl()) 1551 /* We already complained about this parameter. */; 1552 else if (Param->getIdentifier()) 1553 Diag(Param->getLocation(), 1554 diag::err_param_default_argument_missing_name) 1555 << Param->getIdentifier(); 1556 else 1557 Diag(Param->getLocation(), 1558 diag::err_param_default_argument_missing); 1559 1560 LastMissingDefaultArg = p; 1561 } 1562 } 1563 1564 if (LastMissingDefaultArg > 0) { 1565 // Some default arguments were missing. Clear out all of the 1566 // default arguments up to (and including) the last missing 1567 // default argument, so that we leave the function parameters 1568 // in a semantically valid state. 1569 for (p = 0; p <= LastMissingDefaultArg; ++p) { 1570 ParmVarDecl *Param = FD->getParamDecl(p); 1571 if (Param->hasDefaultArg()) { 1572 Param->setDefaultArg(nullptr); 1573 } 1574 } 1575 } 1576 } 1577 1578 /// Check that the given type is a literal type. Issue a diagnostic if not, 1579 /// if Kind is Diagnose. 1580 /// \return \c true if a problem has been found (and optionally diagnosed). 1581 template <typename... Ts> 1582 static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind, 1583 SourceLocation Loc, QualType T, unsigned DiagID, 1584 Ts &&...DiagArgs) { 1585 if (T->isDependentType()) 1586 return false; 1587 1588 switch (Kind) { 1589 case Sema::CheckConstexprKind::Diagnose: 1590 return SemaRef.RequireLiteralType(Loc, T, DiagID, 1591 std::forward<Ts>(DiagArgs)...); 1592 1593 case Sema::CheckConstexprKind::CheckValid: 1594 return !T->isLiteralType(SemaRef.Context); 1595 } 1596 1597 llvm_unreachable("unknown CheckConstexprKind"); 1598 } 1599 1600 /// Determine whether a destructor cannot be constexpr due to 1601 static bool CheckConstexprDestructorSubobjects(Sema &SemaRef, 1602 const CXXDestructorDecl *DD, 1603 Sema::CheckConstexprKind Kind) { 1604 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) { 1605 const CXXRecordDecl *RD = 1606 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 1607 if (!RD || RD->hasConstexprDestructor()) 1608 return true; 1609 1610 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1611 SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject) 1612 << DD->getConstexprKind() << !FD 1613 << (FD ? FD->getDeclName() : DeclarationName()) << T; 1614 SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject) 1615 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T; 1616 } 1617 return false; 1618 }; 1619 1620 const CXXRecordDecl *RD = DD->getParent(); 1621 for (const CXXBaseSpecifier &B : RD->bases()) 1622 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr)) 1623 return false; 1624 for (const FieldDecl *FD : RD->fields()) 1625 if (!Check(FD->getLocation(), FD->getType(), FD)) 1626 return false; 1627 return true; 1628 } 1629 1630 /// Check whether a function's parameter types are all literal types. If so, 1631 /// return true. If not, produce a suitable diagnostic and return false. 1632 static bool CheckConstexprParameterTypes(Sema &SemaRef, 1633 const FunctionDecl *FD, 1634 Sema::CheckConstexprKind Kind) { 1635 unsigned ArgIndex = 0; 1636 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 1637 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 1638 e = FT->param_type_end(); 1639 i != e; ++i, ++ArgIndex) { 1640 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 1641 SourceLocation ParamLoc = PD->getLocation(); 1642 if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i, 1643 diag::err_constexpr_non_literal_param, ArgIndex + 1, 1644 PD->getSourceRange(), isa<CXXConstructorDecl>(FD), 1645 FD->isConsteval())) 1646 return false; 1647 } 1648 return true; 1649 } 1650 1651 /// Check whether a function's return type is a literal type. If so, return 1652 /// true. If not, produce a suitable diagnostic and return false. 1653 static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD, 1654 Sema::CheckConstexprKind Kind) { 1655 if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(), 1656 diag::err_constexpr_non_literal_return, 1657 FD->isConsteval())) 1658 return false; 1659 return true; 1660 } 1661 1662 /// Get diagnostic %select index for tag kind for 1663 /// record diagnostic message. 1664 /// WARNING: Indexes apply to particular diagnostics only! 1665 /// 1666 /// \returns diagnostic %select index. 1667 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 1668 switch (Tag) { 1669 case TTK_Struct: return 0; 1670 case TTK_Interface: return 1; 1671 case TTK_Class: return 2; 1672 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 1673 } 1674 } 1675 1676 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, 1677 Stmt *Body, 1678 Sema::CheckConstexprKind Kind); 1679 1680 // Check whether a function declaration satisfies the requirements of a 1681 // constexpr function definition or a constexpr constructor definition. If so, 1682 // return true. If not, produce appropriate diagnostics (unless asked not to by 1683 // Kind) and return false. 1684 // 1685 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 1686 bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD, 1687 CheckConstexprKind Kind) { 1688 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 1689 if (MD && MD->isInstance()) { 1690 // C++11 [dcl.constexpr]p4: 1691 // The definition of a constexpr constructor shall satisfy the following 1692 // constraints: 1693 // - the class shall not have any virtual base classes; 1694 // 1695 // FIXME: This only applies to constructors and destructors, not arbitrary 1696 // member functions. 1697 const CXXRecordDecl *RD = MD->getParent(); 1698 if (RD->getNumVBases()) { 1699 if (Kind == CheckConstexprKind::CheckValid) 1700 return false; 1701 1702 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 1703 << isa<CXXConstructorDecl>(NewFD) 1704 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 1705 for (const auto &I : RD->vbases()) 1706 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here) 1707 << I.getSourceRange(); 1708 return false; 1709 } 1710 } 1711 1712 if (!isa<CXXConstructorDecl>(NewFD)) { 1713 // C++11 [dcl.constexpr]p3: 1714 // The definition of a constexpr function shall satisfy the following 1715 // constraints: 1716 // - it shall not be virtual; (removed in C++20) 1717 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 1718 if (Method && Method->isVirtual()) { 1719 if (getLangOpts().CPlusPlus2a) { 1720 if (Kind == CheckConstexprKind::Diagnose) 1721 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual); 1722 } else { 1723 if (Kind == CheckConstexprKind::CheckValid) 1724 return false; 1725 1726 Method = Method->getCanonicalDecl(); 1727 Diag(Method->getLocation(), diag::err_constexpr_virtual); 1728 1729 // If it's not obvious why this function is virtual, find an overridden 1730 // function which uses the 'virtual' keyword. 1731 const CXXMethodDecl *WrittenVirtual = Method; 1732 while (!WrittenVirtual->isVirtualAsWritten()) 1733 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 1734 if (WrittenVirtual != Method) 1735 Diag(WrittenVirtual->getLocation(), 1736 diag::note_overridden_virtual_function); 1737 return false; 1738 } 1739 } 1740 1741 // - its return type shall be a literal type; 1742 if (!CheckConstexprReturnType(*this, NewFD, Kind)) 1743 return false; 1744 } 1745 1746 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) { 1747 // A destructor can be constexpr only if the defaulted destructor could be; 1748 // we don't need to check the members and bases if we already know they all 1749 // have constexpr destructors. 1750 if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) { 1751 if (Kind == CheckConstexprKind::CheckValid) 1752 return false; 1753 if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind)) 1754 return false; 1755 } 1756 } 1757 1758 // - each of its parameter types shall be a literal type; 1759 if (!CheckConstexprParameterTypes(*this, NewFD, Kind)) 1760 return false; 1761 1762 Stmt *Body = NewFD->getBody(); 1763 assert(Body && 1764 "CheckConstexprFunctionDefinition called on function with no body"); 1765 return CheckConstexprFunctionBody(*this, NewFD, Body, Kind); 1766 } 1767 1768 /// Check the given declaration statement is legal within a constexpr function 1769 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 1770 /// 1771 /// \return true if the body is OK (maybe only as an extension), false if we 1772 /// have diagnosed a problem. 1773 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 1774 DeclStmt *DS, SourceLocation &Cxx1yLoc, 1775 Sema::CheckConstexprKind Kind) { 1776 // C++11 [dcl.constexpr]p3 and p4: 1777 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 1778 // contain only 1779 for (const auto *DclIt : DS->decls()) { 1780 switch (DclIt->getKind()) { 1781 case Decl::StaticAssert: 1782 case Decl::Using: 1783 case Decl::UsingShadow: 1784 case Decl::UsingDirective: 1785 case Decl::UnresolvedUsingTypename: 1786 case Decl::UnresolvedUsingValue: 1787 // - static_assert-declarations 1788 // - using-declarations, 1789 // - using-directives, 1790 continue; 1791 1792 case Decl::Typedef: 1793 case Decl::TypeAlias: { 1794 // - typedef declarations and alias-declarations that do not define 1795 // classes or enumerations, 1796 const auto *TN = cast<TypedefNameDecl>(DclIt); 1797 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 1798 // Don't allow variably-modified types in constexpr functions. 1799 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1800 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 1801 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 1802 << TL.getSourceRange() << TL.getType() 1803 << isa<CXXConstructorDecl>(Dcl); 1804 } 1805 return false; 1806 } 1807 continue; 1808 } 1809 1810 case Decl::Enum: 1811 case Decl::CXXRecord: 1812 // C++1y allows types to be defined, not just declared. 1813 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) { 1814 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1815 SemaRef.Diag(DS->getBeginLoc(), 1816 SemaRef.getLangOpts().CPlusPlus14 1817 ? diag::warn_cxx11_compat_constexpr_type_definition 1818 : diag::ext_constexpr_type_definition) 1819 << isa<CXXConstructorDecl>(Dcl); 1820 } else if (!SemaRef.getLangOpts().CPlusPlus14) { 1821 return false; 1822 } 1823 } 1824 continue; 1825 1826 case Decl::EnumConstant: 1827 case Decl::IndirectField: 1828 case Decl::ParmVar: 1829 // These can only appear with other declarations which are banned in 1830 // C++11 and permitted in C++1y, so ignore them. 1831 continue; 1832 1833 case Decl::Var: 1834 case Decl::Decomposition: { 1835 // C++1y [dcl.constexpr]p3 allows anything except: 1836 // a definition of a variable of non-literal type or of static or 1837 // thread storage duration or [before C++2a] for which no 1838 // initialization is performed. 1839 const auto *VD = cast<VarDecl>(DclIt); 1840 if (VD->isThisDeclarationADefinition()) { 1841 if (VD->isStaticLocal()) { 1842 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1843 SemaRef.Diag(VD->getLocation(), 1844 diag::err_constexpr_local_var_static) 1845 << isa<CXXConstructorDecl>(Dcl) 1846 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 1847 } 1848 return false; 1849 } 1850 if (CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(), 1851 diag::err_constexpr_local_var_non_literal_type, 1852 isa<CXXConstructorDecl>(Dcl))) 1853 return false; 1854 if (!VD->getType()->isDependentType() && 1855 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 1856 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1857 SemaRef.Diag( 1858 VD->getLocation(), 1859 SemaRef.getLangOpts().CPlusPlus2a 1860 ? diag::warn_cxx17_compat_constexpr_local_var_no_init 1861 : diag::ext_constexpr_local_var_no_init) 1862 << isa<CXXConstructorDecl>(Dcl); 1863 } else if (!SemaRef.getLangOpts().CPlusPlus2a) { 1864 return false; 1865 } 1866 continue; 1867 } 1868 } 1869 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1870 SemaRef.Diag(VD->getLocation(), 1871 SemaRef.getLangOpts().CPlusPlus14 1872 ? diag::warn_cxx11_compat_constexpr_local_var 1873 : diag::ext_constexpr_local_var) 1874 << isa<CXXConstructorDecl>(Dcl); 1875 } else if (!SemaRef.getLangOpts().CPlusPlus14) { 1876 return false; 1877 } 1878 continue; 1879 } 1880 1881 case Decl::NamespaceAlias: 1882 case Decl::Function: 1883 // These are disallowed in C++11 and permitted in C++1y. Allow them 1884 // everywhere as an extension. 1885 if (!Cxx1yLoc.isValid()) 1886 Cxx1yLoc = DS->getBeginLoc(); 1887 continue; 1888 1889 default: 1890 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1891 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 1892 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 1893 } 1894 return false; 1895 } 1896 } 1897 1898 return true; 1899 } 1900 1901 /// Check that the given field is initialized within a constexpr constructor. 1902 /// 1903 /// \param Dcl The constexpr constructor being checked. 1904 /// \param Field The field being checked. This may be a member of an anonymous 1905 /// struct or union nested within the class being checked. 1906 /// \param Inits All declarations, including anonymous struct/union members and 1907 /// indirect members, for which any initialization was provided. 1908 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach 1909 /// multiple notes for different members to the same error. 1910 /// \param Kind Whether we're diagnosing a constructor as written or determining 1911 /// whether the formal requirements are satisfied. 1912 /// \return \c false if we're checking for validity and the constructor does 1913 /// not satisfy the requirements on a constexpr constructor. 1914 static bool CheckConstexprCtorInitializer(Sema &SemaRef, 1915 const FunctionDecl *Dcl, 1916 FieldDecl *Field, 1917 llvm::SmallSet<Decl*, 16> &Inits, 1918 bool &Diagnosed, 1919 Sema::CheckConstexprKind Kind) { 1920 // In C++20 onwards, there's nothing to check for validity. 1921 if (Kind == Sema::CheckConstexprKind::CheckValid && 1922 SemaRef.getLangOpts().CPlusPlus2a) 1923 return true; 1924 1925 if (Field->isInvalidDecl()) 1926 return true; 1927 1928 if (Field->isUnnamedBitfield()) 1929 return true; 1930 1931 // Anonymous unions with no variant members and empty anonymous structs do not 1932 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 1933 // indirect fields don't need initializing. 1934 if (Field->isAnonymousStructOrUnion() && 1935 (Field->getType()->isUnionType() 1936 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 1937 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 1938 return true; 1939 1940 if (!Inits.count(Field)) { 1941 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1942 if (!Diagnosed) { 1943 SemaRef.Diag(Dcl->getLocation(), 1944 SemaRef.getLangOpts().CPlusPlus2a 1945 ? diag::warn_cxx17_compat_constexpr_ctor_missing_init 1946 : diag::ext_constexpr_ctor_missing_init); 1947 Diagnosed = true; 1948 } 1949 SemaRef.Diag(Field->getLocation(), 1950 diag::note_constexpr_ctor_missing_init); 1951 } else if (!SemaRef.getLangOpts().CPlusPlus2a) { 1952 return false; 1953 } 1954 } else if (Field->isAnonymousStructOrUnion()) { 1955 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 1956 for (auto *I : RD->fields()) 1957 // If an anonymous union contains an anonymous struct of which any member 1958 // is initialized, all members must be initialized. 1959 if (!RD->isUnion() || Inits.count(I)) 1960 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, 1961 Kind)) 1962 return false; 1963 } 1964 return true; 1965 } 1966 1967 /// Check the provided statement is allowed in a constexpr function 1968 /// definition. 1969 static bool 1970 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 1971 SmallVectorImpl<SourceLocation> &ReturnStmts, 1972 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc, 1973 Sema::CheckConstexprKind Kind) { 1974 // - its function-body shall be [...] a compound-statement that contains only 1975 switch (S->getStmtClass()) { 1976 case Stmt::NullStmtClass: 1977 // - null statements, 1978 return true; 1979 1980 case Stmt::DeclStmtClass: 1981 // - static_assert-declarations 1982 // - using-declarations, 1983 // - using-directives, 1984 // - typedef declarations and alias-declarations that do not define 1985 // classes or enumerations, 1986 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind)) 1987 return false; 1988 return true; 1989 1990 case Stmt::ReturnStmtClass: 1991 // - and exactly one return statement; 1992 if (isa<CXXConstructorDecl>(Dcl)) { 1993 // C++1y allows return statements in constexpr constructors. 1994 if (!Cxx1yLoc.isValid()) 1995 Cxx1yLoc = S->getBeginLoc(); 1996 return true; 1997 } 1998 1999 ReturnStmts.push_back(S->getBeginLoc()); 2000 return true; 2001 2002 case Stmt::CompoundStmtClass: { 2003 // C++1y allows compound-statements. 2004 if (!Cxx1yLoc.isValid()) 2005 Cxx1yLoc = S->getBeginLoc(); 2006 2007 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 2008 for (auto *BodyIt : CompStmt->body()) { 2009 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 2010 Cxx1yLoc, Cxx2aLoc, Kind)) 2011 return false; 2012 } 2013 return true; 2014 } 2015 2016 case Stmt::AttributedStmtClass: 2017 if (!Cxx1yLoc.isValid()) 2018 Cxx1yLoc = S->getBeginLoc(); 2019 return true; 2020 2021 case Stmt::IfStmtClass: { 2022 // C++1y allows if-statements. 2023 if (!Cxx1yLoc.isValid()) 2024 Cxx1yLoc = S->getBeginLoc(); 2025 2026 IfStmt *If = cast<IfStmt>(S); 2027 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 2028 Cxx1yLoc, Cxx2aLoc, Kind)) 2029 return false; 2030 if (If->getElse() && 2031 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 2032 Cxx1yLoc, Cxx2aLoc, Kind)) 2033 return false; 2034 return true; 2035 } 2036 2037 case Stmt::WhileStmtClass: 2038 case Stmt::DoStmtClass: 2039 case Stmt::ForStmtClass: 2040 case Stmt::CXXForRangeStmtClass: 2041 case Stmt::ContinueStmtClass: 2042 // C++1y allows all of these. We don't allow them as extensions in C++11, 2043 // because they don't make sense without variable mutation. 2044 if (!SemaRef.getLangOpts().CPlusPlus14) 2045 break; 2046 if (!Cxx1yLoc.isValid()) 2047 Cxx1yLoc = S->getBeginLoc(); 2048 for (Stmt *SubStmt : S->children()) 2049 if (SubStmt && 2050 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2051 Cxx1yLoc, Cxx2aLoc, Kind)) 2052 return false; 2053 return true; 2054 2055 case Stmt::SwitchStmtClass: 2056 case Stmt::CaseStmtClass: 2057 case Stmt::DefaultStmtClass: 2058 case Stmt::BreakStmtClass: 2059 // C++1y allows switch-statements, and since they don't need variable 2060 // mutation, we can reasonably allow them in C++11 as an extension. 2061 if (!Cxx1yLoc.isValid()) 2062 Cxx1yLoc = S->getBeginLoc(); 2063 for (Stmt *SubStmt : S->children()) 2064 if (SubStmt && 2065 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2066 Cxx1yLoc, Cxx2aLoc, Kind)) 2067 return false; 2068 return true; 2069 2070 case Stmt::GCCAsmStmtClass: 2071 case Stmt::MSAsmStmtClass: 2072 // C++2a allows inline assembly statements. 2073 case Stmt::CXXTryStmtClass: 2074 if (Cxx2aLoc.isInvalid()) 2075 Cxx2aLoc = S->getBeginLoc(); 2076 for (Stmt *SubStmt : S->children()) { 2077 if (SubStmt && 2078 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2079 Cxx1yLoc, Cxx2aLoc, Kind)) 2080 return false; 2081 } 2082 return true; 2083 2084 case Stmt::CXXCatchStmtClass: 2085 // Do not bother checking the language mode (already covered by the 2086 // try block check). 2087 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, 2088 cast<CXXCatchStmt>(S)->getHandlerBlock(), 2089 ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind)) 2090 return false; 2091 return true; 2092 2093 default: 2094 if (!isa<Expr>(S)) 2095 break; 2096 2097 // C++1y allows expression-statements. 2098 if (!Cxx1yLoc.isValid()) 2099 Cxx1yLoc = S->getBeginLoc(); 2100 return true; 2101 } 2102 2103 if (Kind == Sema::CheckConstexprKind::Diagnose) { 2104 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 2105 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 2106 } 2107 return false; 2108 } 2109 2110 /// Check the body for the given constexpr function declaration only contains 2111 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 2112 /// 2113 /// \return true if the body is OK, false if we have found or diagnosed a 2114 /// problem. 2115 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, 2116 Stmt *Body, 2117 Sema::CheckConstexprKind Kind) { 2118 SmallVector<SourceLocation, 4> ReturnStmts; 2119 2120 if (isa<CXXTryStmt>(Body)) { 2121 // C++11 [dcl.constexpr]p3: 2122 // The definition of a constexpr function shall satisfy the following 2123 // constraints: [...] 2124 // - its function-body shall be = delete, = default, or a 2125 // compound-statement 2126 // 2127 // C++11 [dcl.constexpr]p4: 2128 // In the definition of a constexpr constructor, [...] 2129 // - its function-body shall not be a function-try-block; 2130 // 2131 // This restriction is lifted in C++2a, as long as inner statements also 2132 // apply the general constexpr rules. 2133 switch (Kind) { 2134 case Sema::CheckConstexprKind::CheckValid: 2135 if (!SemaRef.getLangOpts().CPlusPlus2a) 2136 return false; 2137 break; 2138 2139 case Sema::CheckConstexprKind::Diagnose: 2140 SemaRef.Diag(Body->getBeginLoc(), 2141 !SemaRef.getLangOpts().CPlusPlus2a 2142 ? diag::ext_constexpr_function_try_block_cxx2a 2143 : diag::warn_cxx17_compat_constexpr_function_try_block) 2144 << isa<CXXConstructorDecl>(Dcl); 2145 break; 2146 } 2147 } 2148 2149 // - its function-body shall be [...] a compound-statement that contains only 2150 // [... list of cases ...] 2151 // 2152 // Note that walking the children here is enough to properly check for 2153 // CompoundStmt and CXXTryStmt body. 2154 SourceLocation Cxx1yLoc, Cxx2aLoc; 2155 for (Stmt *SubStmt : Body->children()) { 2156 if (SubStmt && 2157 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2158 Cxx1yLoc, Cxx2aLoc, Kind)) 2159 return false; 2160 } 2161 2162 if (Kind == Sema::CheckConstexprKind::CheckValid) { 2163 // If this is only valid as an extension, report that we don't satisfy the 2164 // constraints of the current language. 2165 if ((Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus2a) || 2166 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17)) 2167 return false; 2168 } else if (Cxx2aLoc.isValid()) { 2169 SemaRef.Diag(Cxx2aLoc, 2170 SemaRef.getLangOpts().CPlusPlus2a 2171 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt 2172 : diag::ext_constexpr_body_invalid_stmt_cxx2a) 2173 << isa<CXXConstructorDecl>(Dcl); 2174 } else if (Cxx1yLoc.isValid()) { 2175 SemaRef.Diag(Cxx1yLoc, 2176 SemaRef.getLangOpts().CPlusPlus14 2177 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 2178 : diag::ext_constexpr_body_invalid_stmt) 2179 << isa<CXXConstructorDecl>(Dcl); 2180 } 2181 2182 if (const CXXConstructorDecl *Constructor 2183 = dyn_cast<CXXConstructorDecl>(Dcl)) { 2184 const CXXRecordDecl *RD = Constructor->getParent(); 2185 // DR1359: 2186 // - every non-variant non-static data member and base class sub-object 2187 // shall be initialized; 2188 // DR1460: 2189 // - if the class is a union having variant members, exactly one of them 2190 // shall be initialized; 2191 if (RD->isUnion()) { 2192 if (Constructor->getNumCtorInitializers() == 0 && 2193 RD->hasVariantMembers()) { 2194 if (Kind == Sema::CheckConstexprKind::Diagnose) { 2195 SemaRef.Diag( 2196 Dcl->getLocation(), 2197 SemaRef.getLangOpts().CPlusPlus2a 2198 ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init 2199 : diag::ext_constexpr_union_ctor_no_init); 2200 } else if (!SemaRef.getLangOpts().CPlusPlus2a) { 2201 return false; 2202 } 2203 } 2204 } else if (!Constructor->isDependentContext() && 2205 !Constructor->isDelegatingConstructor()) { 2206 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 2207 2208 // Skip detailed checking if we have enough initializers, and we would 2209 // allow at most one initializer per member. 2210 bool AnyAnonStructUnionMembers = false; 2211 unsigned Fields = 0; 2212 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 2213 E = RD->field_end(); I != E; ++I, ++Fields) { 2214 if (I->isAnonymousStructOrUnion()) { 2215 AnyAnonStructUnionMembers = true; 2216 break; 2217 } 2218 } 2219 // DR1460: 2220 // - if the class is a union-like class, but is not a union, for each of 2221 // its anonymous union members having variant members, exactly one of 2222 // them shall be initialized; 2223 if (AnyAnonStructUnionMembers || 2224 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 2225 // Check initialization of non-static data members. Base classes are 2226 // always initialized so do not need to be checked. Dependent bases 2227 // might not have initializers in the member initializer list. 2228 llvm::SmallSet<Decl*, 16> Inits; 2229 for (const auto *I: Constructor->inits()) { 2230 if (FieldDecl *FD = I->getMember()) 2231 Inits.insert(FD); 2232 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 2233 Inits.insert(ID->chain_begin(), ID->chain_end()); 2234 } 2235 2236 bool Diagnosed = false; 2237 for (auto *I : RD->fields()) 2238 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, 2239 Kind)) 2240 return false; 2241 } 2242 } 2243 } else { 2244 if (ReturnStmts.empty()) { 2245 // C++1y doesn't require constexpr functions to contain a 'return' 2246 // statement. We still do, unless the return type might be void, because 2247 // otherwise if there's no return statement, the function cannot 2248 // be used in a core constant expression. 2249 bool OK = SemaRef.getLangOpts().CPlusPlus14 && 2250 (Dcl->getReturnType()->isVoidType() || 2251 Dcl->getReturnType()->isDependentType()); 2252 switch (Kind) { 2253 case Sema::CheckConstexprKind::Diagnose: 2254 SemaRef.Diag(Dcl->getLocation(), 2255 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 2256 : diag::err_constexpr_body_no_return) 2257 << Dcl->isConsteval(); 2258 if (!OK) 2259 return false; 2260 break; 2261 2262 case Sema::CheckConstexprKind::CheckValid: 2263 // The formal requirements don't include this rule in C++14, even 2264 // though the "must be able to produce a constant expression" rules 2265 // still imply it in some cases. 2266 if (!SemaRef.getLangOpts().CPlusPlus14) 2267 return false; 2268 break; 2269 } 2270 } else if (ReturnStmts.size() > 1) { 2271 switch (Kind) { 2272 case Sema::CheckConstexprKind::Diagnose: 2273 SemaRef.Diag( 2274 ReturnStmts.back(), 2275 SemaRef.getLangOpts().CPlusPlus14 2276 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 2277 : diag::ext_constexpr_body_multiple_return); 2278 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 2279 SemaRef.Diag(ReturnStmts[I], 2280 diag::note_constexpr_body_previous_return); 2281 break; 2282 2283 case Sema::CheckConstexprKind::CheckValid: 2284 if (!SemaRef.getLangOpts().CPlusPlus14) 2285 return false; 2286 break; 2287 } 2288 } 2289 } 2290 2291 // C++11 [dcl.constexpr]p5: 2292 // if no function argument values exist such that the function invocation 2293 // substitution would produce a constant expression, the program is 2294 // ill-formed; no diagnostic required. 2295 // C++11 [dcl.constexpr]p3: 2296 // - every constructor call and implicit conversion used in initializing the 2297 // return value shall be one of those allowed in a constant expression. 2298 // C++11 [dcl.constexpr]p4: 2299 // - every constructor involved in initializing non-static data members and 2300 // base class sub-objects shall be a constexpr constructor. 2301 // 2302 // Note that this rule is distinct from the "requirements for a constexpr 2303 // function", so is not checked in CheckValid mode. 2304 SmallVector<PartialDiagnosticAt, 8> Diags; 2305 if (Kind == Sema::CheckConstexprKind::Diagnose && 2306 !Expr::isPotentialConstantExpr(Dcl, Diags)) { 2307 SemaRef.Diag(Dcl->getLocation(), 2308 diag::ext_constexpr_function_never_constant_expr) 2309 << isa<CXXConstructorDecl>(Dcl); 2310 for (size_t I = 0, N = Diags.size(); I != N; ++I) 2311 SemaRef.Diag(Diags[I].first, Diags[I].second); 2312 // Don't return false here: we allow this for compatibility in 2313 // system headers. 2314 } 2315 2316 return true; 2317 } 2318 2319 /// Get the class that is directly named by the current context. This is the 2320 /// class for which an unqualified-id in this scope could name a constructor 2321 /// or destructor. 2322 /// 2323 /// If the scope specifier denotes a class, this will be that class. 2324 /// If the scope specifier is empty, this will be the class whose 2325 /// member-specification we are currently within. Otherwise, there 2326 /// is no such class. 2327 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) { 2328 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2329 2330 if (SS && SS->isInvalid()) 2331 return nullptr; 2332 2333 if (SS && SS->isNotEmpty()) { 2334 DeclContext *DC = computeDeclContext(*SS, true); 2335 return dyn_cast_or_null<CXXRecordDecl>(DC); 2336 } 2337 2338 return dyn_cast_or_null<CXXRecordDecl>(CurContext); 2339 } 2340 2341 /// isCurrentClassName - Determine whether the identifier II is the 2342 /// name of the class type currently being defined. In the case of 2343 /// nested classes, this will only return true if II is the name of 2344 /// the innermost class. 2345 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S, 2346 const CXXScopeSpec *SS) { 2347 CXXRecordDecl *CurDecl = getCurrentClass(S, SS); 2348 return CurDecl && &II == CurDecl->getIdentifier(); 2349 } 2350 2351 /// Determine whether the identifier II is a typo for the name of 2352 /// the class type currently being defined. If so, update it to the identifier 2353 /// that should have been used. 2354 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 2355 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2356 2357 if (!getLangOpts().SpellChecking) 2358 return false; 2359 2360 CXXRecordDecl *CurDecl; 2361 if (SS && SS->isSet() && !SS->isInvalid()) { 2362 DeclContext *DC = computeDeclContext(*SS, true); 2363 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 2364 } else 2365 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 2366 2367 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 2368 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 2369 < II->getLength()) { 2370 II = CurDecl->getIdentifier(); 2371 return true; 2372 } 2373 2374 return false; 2375 } 2376 2377 /// Determine whether the given class is a base class of the given 2378 /// class, including looking at dependent bases. 2379 static bool findCircularInheritance(const CXXRecordDecl *Class, 2380 const CXXRecordDecl *Current) { 2381 SmallVector<const CXXRecordDecl*, 8> Queue; 2382 2383 Class = Class->getCanonicalDecl(); 2384 while (true) { 2385 for (const auto &I : Current->bases()) { 2386 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 2387 if (!Base) 2388 continue; 2389 2390 Base = Base->getDefinition(); 2391 if (!Base) 2392 continue; 2393 2394 if (Base->getCanonicalDecl() == Class) 2395 return true; 2396 2397 Queue.push_back(Base); 2398 } 2399 2400 if (Queue.empty()) 2401 return false; 2402 2403 Current = Queue.pop_back_val(); 2404 } 2405 2406 return false; 2407 } 2408 2409 /// Check the validity of a C++ base class specifier. 2410 /// 2411 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 2412 /// and returns NULL otherwise. 2413 CXXBaseSpecifier * 2414 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 2415 SourceRange SpecifierRange, 2416 bool Virtual, AccessSpecifier Access, 2417 TypeSourceInfo *TInfo, 2418 SourceLocation EllipsisLoc) { 2419 QualType BaseType = TInfo->getType(); 2420 2421 // C++ [class.union]p1: 2422 // A union shall not have base classes. 2423 if (Class->isUnion()) { 2424 Diag(Class->getLocation(), diag::err_base_clause_on_union) 2425 << SpecifierRange; 2426 return nullptr; 2427 } 2428 2429 if (EllipsisLoc.isValid() && 2430 !TInfo->getType()->containsUnexpandedParameterPack()) { 2431 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2432 << TInfo->getTypeLoc().getSourceRange(); 2433 EllipsisLoc = SourceLocation(); 2434 } 2435 2436 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 2437 2438 if (BaseType->isDependentType()) { 2439 // Make sure that we don't have circular inheritance among our dependent 2440 // bases. For non-dependent bases, the check for completeness below handles 2441 // this. 2442 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 2443 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 2444 ((BaseDecl = BaseDecl->getDefinition()) && 2445 findCircularInheritance(Class, BaseDecl))) { 2446 Diag(BaseLoc, diag::err_circular_inheritance) 2447 << BaseType << Context.getTypeDeclType(Class); 2448 2449 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 2450 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 2451 << BaseType; 2452 2453 return nullptr; 2454 } 2455 } 2456 2457 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2458 Class->getTagKind() == TTK_Class, 2459 Access, TInfo, EllipsisLoc); 2460 } 2461 2462 // Base specifiers must be record types. 2463 if (!BaseType->isRecordType()) { 2464 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 2465 return nullptr; 2466 } 2467 2468 // C++ [class.union]p1: 2469 // A union shall not be used as a base class. 2470 if (BaseType->isUnionType()) { 2471 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 2472 return nullptr; 2473 } 2474 2475 // For the MS ABI, propagate DLL attributes to base class templates. 2476 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 2477 if (Attr *ClassAttr = getDLLAttr(Class)) { 2478 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 2479 BaseType->getAsCXXRecordDecl())) { 2480 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate, 2481 BaseLoc); 2482 } 2483 } 2484 } 2485 2486 // C++ [class.derived]p2: 2487 // The class-name in a base-specifier shall not be an incompletely 2488 // defined class. 2489 if (RequireCompleteType(BaseLoc, BaseType, 2490 diag::err_incomplete_base_class, SpecifierRange)) { 2491 Class->setInvalidDecl(); 2492 return nullptr; 2493 } 2494 2495 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 2496 RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl(); 2497 assert(BaseDecl && "Record type has no declaration"); 2498 BaseDecl = BaseDecl->getDefinition(); 2499 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 2500 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 2501 assert(CXXBaseDecl && "Base type is not a C++ type"); 2502 2503 // Microsoft docs say: 2504 // "If a base-class has a code_seg attribute, derived classes must have the 2505 // same attribute." 2506 const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>(); 2507 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>(); 2508 if ((DerivedCSA || BaseCSA) && 2509 (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) { 2510 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base); 2511 Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here) 2512 << CXXBaseDecl; 2513 return nullptr; 2514 } 2515 2516 // A class which contains a flexible array member is not suitable for use as a 2517 // base class: 2518 // - If the layout determines that a base comes before another base, 2519 // the flexible array member would index into the subsequent base. 2520 // - If the layout determines that base comes before the derived class, 2521 // the flexible array member would index into the derived class. 2522 if (CXXBaseDecl->hasFlexibleArrayMember()) { 2523 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 2524 << CXXBaseDecl->getDeclName(); 2525 return nullptr; 2526 } 2527 2528 // C++ [class]p3: 2529 // If a class is marked final and it appears as a base-type-specifier in 2530 // base-clause, the program is ill-formed. 2531 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 2532 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 2533 << CXXBaseDecl->getDeclName() 2534 << FA->isSpelledAsSealed(); 2535 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 2536 << CXXBaseDecl->getDeclName() << FA->getRange(); 2537 return nullptr; 2538 } 2539 2540 if (BaseDecl->isInvalidDecl()) 2541 Class->setInvalidDecl(); 2542 2543 // Create the base specifier. 2544 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2545 Class->getTagKind() == TTK_Class, 2546 Access, TInfo, EllipsisLoc); 2547 } 2548 2549 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 2550 /// one entry in the base class list of a class specifier, for 2551 /// example: 2552 /// class foo : public bar, virtual private baz { 2553 /// 'public bar' and 'virtual private baz' are each base-specifiers. 2554 BaseResult 2555 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 2556 ParsedAttributes &Attributes, 2557 bool Virtual, AccessSpecifier Access, 2558 ParsedType basetype, SourceLocation BaseLoc, 2559 SourceLocation EllipsisLoc) { 2560 if (!classdecl) 2561 return true; 2562 2563 AdjustDeclIfTemplate(classdecl); 2564 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 2565 if (!Class) 2566 return true; 2567 2568 // We haven't yet attached the base specifiers. 2569 Class->setIsParsingBaseSpecifiers(); 2570 2571 // We do not support any C++11 attributes on base-specifiers yet. 2572 // Diagnose any attributes we see. 2573 for (const ParsedAttr &AL : Attributes) { 2574 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute) 2575 continue; 2576 Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute 2577 ? (unsigned)diag::warn_unknown_attribute_ignored 2578 : (unsigned)diag::err_base_specifier_attribute) 2579 << AL; 2580 } 2581 2582 TypeSourceInfo *TInfo = nullptr; 2583 GetTypeFromParser(basetype, &TInfo); 2584 2585 if (EllipsisLoc.isInvalid() && 2586 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 2587 UPPC_BaseType)) 2588 return true; 2589 2590 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 2591 Virtual, Access, TInfo, 2592 EllipsisLoc)) 2593 return BaseSpec; 2594 else 2595 Class->setInvalidDecl(); 2596 2597 return true; 2598 } 2599 2600 /// Use small set to collect indirect bases. As this is only used 2601 /// locally, there's no need to abstract the small size parameter. 2602 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet; 2603 2604 /// Recursively add the bases of Type. Don't add Type itself. 2605 static void 2606 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, 2607 const QualType &Type) 2608 { 2609 // Even though the incoming type is a base, it might not be 2610 // a class -- it could be a template parm, for instance. 2611 if (auto Rec = Type->getAs<RecordType>()) { 2612 auto Decl = Rec->getAsCXXRecordDecl(); 2613 2614 // Iterate over its bases. 2615 for (const auto &BaseSpec : Decl->bases()) { 2616 QualType Base = Context.getCanonicalType(BaseSpec.getType()) 2617 .getUnqualifiedType(); 2618 if (Set.insert(Base).second) 2619 // If we've not already seen it, recurse. 2620 NoteIndirectBases(Context, Set, Base); 2621 } 2622 } 2623 } 2624 2625 /// Performs the actual work of attaching the given base class 2626 /// specifiers to a C++ class. 2627 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, 2628 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2629 if (Bases.empty()) 2630 return false; 2631 2632 // Used to keep track of which base types we have already seen, so 2633 // that we can properly diagnose redundant direct base types. Note 2634 // that the key is always the unqualified canonical type of the base 2635 // class. 2636 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 2637 2638 // Used to track indirect bases so we can see if a direct base is 2639 // ambiguous. 2640 IndirectBaseSet IndirectBaseTypes; 2641 2642 // Copy non-redundant base specifiers into permanent storage. 2643 unsigned NumGoodBases = 0; 2644 bool Invalid = false; 2645 for (unsigned idx = 0; idx < Bases.size(); ++idx) { 2646 QualType NewBaseType 2647 = Context.getCanonicalType(Bases[idx]->getType()); 2648 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 2649 2650 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 2651 if (KnownBase) { 2652 // C++ [class.mi]p3: 2653 // A class shall not be specified as a direct base class of a 2654 // derived class more than once. 2655 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class) 2656 << KnownBase->getType() << Bases[idx]->getSourceRange(); 2657 2658 // Delete the duplicate base class specifier; we're going to 2659 // overwrite its pointer later. 2660 Context.Deallocate(Bases[idx]); 2661 2662 Invalid = true; 2663 } else { 2664 // Okay, add this new base class. 2665 KnownBase = Bases[idx]; 2666 Bases[NumGoodBases++] = Bases[idx]; 2667 2668 // Note this base's direct & indirect bases, if there could be ambiguity. 2669 if (Bases.size() > 1) 2670 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType); 2671 2672 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 2673 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 2674 if (Class->isInterface() && 2675 (!RD->isInterfaceLike() || 2676 KnownBase->getAccessSpecifier() != AS_public)) { 2677 // The Microsoft extension __interface does not permit bases that 2678 // are not themselves public interfaces. 2679 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface) 2680 << getRecordDiagFromTagKind(RD->getTagKind()) << RD 2681 << RD->getSourceRange(); 2682 Invalid = true; 2683 } 2684 if (RD->hasAttr<WeakAttr>()) 2685 Class->addAttr(WeakAttr::CreateImplicit(Context)); 2686 } 2687 } 2688 } 2689 2690 // Attach the remaining base class specifiers to the derived class. 2691 Class->setBases(Bases.data(), NumGoodBases); 2692 2693 // Check that the only base classes that are duplicate are virtual. 2694 for (unsigned idx = 0; idx < NumGoodBases; ++idx) { 2695 // Check whether this direct base is inaccessible due to ambiguity. 2696 QualType BaseType = Bases[idx]->getType(); 2697 2698 // Skip all dependent types in templates being used as base specifiers. 2699 // Checks below assume that the base specifier is a CXXRecord. 2700 if (BaseType->isDependentType()) 2701 continue; 2702 2703 CanQualType CanonicalBase = Context.getCanonicalType(BaseType) 2704 .getUnqualifiedType(); 2705 2706 if (IndirectBaseTypes.count(CanonicalBase)) { 2707 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2708 /*DetectVirtual=*/true); 2709 bool found 2710 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); 2711 assert(found); 2712 (void)found; 2713 2714 if (Paths.isAmbiguous(CanonicalBase)) 2715 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class) 2716 << BaseType << getAmbiguousPathsDisplayString(Paths) 2717 << Bases[idx]->getSourceRange(); 2718 else 2719 assert(Bases[idx]->isVirtual()); 2720 } 2721 2722 // Delete the base class specifier, since its data has been copied 2723 // into the CXXRecordDecl. 2724 Context.Deallocate(Bases[idx]); 2725 } 2726 2727 return Invalid; 2728 } 2729 2730 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 2731 /// class, after checking whether there are any duplicate base 2732 /// classes. 2733 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, 2734 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2735 if (!ClassDecl || Bases.empty()) 2736 return; 2737 2738 AdjustDeclIfTemplate(ClassDecl); 2739 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases); 2740 } 2741 2742 /// Determine whether the type \p Derived is a C++ class that is 2743 /// derived from the type \p Base. 2744 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) { 2745 if (!getLangOpts().CPlusPlus) 2746 return false; 2747 2748 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2749 if (!DerivedRD) 2750 return false; 2751 2752 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2753 if (!BaseRD) 2754 return false; 2755 2756 // If either the base or the derived type is invalid, don't try to 2757 // check whether one is derived from the other. 2758 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 2759 return false; 2760 2761 // FIXME: In a modules build, do we need the entire path to be visible for us 2762 // to be able to use the inheritance relationship? 2763 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2764 return false; 2765 2766 return DerivedRD->isDerivedFrom(BaseRD); 2767 } 2768 2769 /// Determine whether the type \p Derived is a C++ class that is 2770 /// derived from the type \p Base. 2771 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, 2772 CXXBasePaths &Paths) { 2773 if (!getLangOpts().CPlusPlus) 2774 return false; 2775 2776 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2777 if (!DerivedRD) 2778 return false; 2779 2780 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2781 if (!BaseRD) 2782 return false; 2783 2784 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2785 return false; 2786 2787 return DerivedRD->isDerivedFrom(BaseRD, Paths); 2788 } 2789 2790 static void BuildBasePathArray(const CXXBasePath &Path, 2791 CXXCastPath &BasePathArray) { 2792 // We first go backward and check if we have a virtual base. 2793 // FIXME: It would be better if CXXBasePath had the base specifier for 2794 // the nearest virtual base. 2795 unsigned Start = 0; 2796 for (unsigned I = Path.size(); I != 0; --I) { 2797 if (Path[I - 1].Base->isVirtual()) { 2798 Start = I - 1; 2799 break; 2800 } 2801 } 2802 2803 // Now add all bases. 2804 for (unsigned I = Start, E = Path.size(); I != E; ++I) 2805 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 2806 } 2807 2808 2809 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 2810 CXXCastPath &BasePathArray) { 2811 assert(BasePathArray.empty() && "Base path array must be empty!"); 2812 assert(Paths.isRecordingPaths() && "Must record paths!"); 2813 return ::BuildBasePathArray(Paths.front(), BasePathArray); 2814 } 2815 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 2816 /// conversion (where Derived and Base are class types) is 2817 /// well-formed, meaning that the conversion is unambiguous (and 2818 /// that all of the base classes are accessible). Returns true 2819 /// and emits a diagnostic if the code is ill-formed, returns false 2820 /// otherwise. Loc is the location where this routine should point to 2821 /// if there is an error, and Range is the source range to highlight 2822 /// if there is an error. 2823 /// 2824 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the 2825 /// diagnostic for the respective type of error will be suppressed, but the 2826 /// check for ill-formed code will still be performed. 2827 bool 2828 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2829 unsigned InaccessibleBaseID, 2830 unsigned AmbigiousBaseConvID, 2831 SourceLocation Loc, SourceRange Range, 2832 DeclarationName Name, 2833 CXXCastPath *BasePath, 2834 bool IgnoreAccess) { 2835 // First, determine whether the path from Derived to Base is 2836 // ambiguous. This is slightly more expensive than checking whether 2837 // the Derived to Base conversion exists, because here we need to 2838 // explore multiple paths to determine if there is an ambiguity. 2839 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2840 /*DetectVirtual=*/false); 2841 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2842 if (!DerivationOkay) 2843 return true; 2844 2845 const CXXBasePath *Path = nullptr; 2846 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) 2847 Path = &Paths.front(); 2848 2849 // For MSVC compatibility, check if Derived directly inherits from Base. Clang 2850 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the 2851 // user to access such bases. 2852 if (!Path && getLangOpts().MSVCCompat) { 2853 for (const CXXBasePath &PossiblePath : Paths) { 2854 if (PossiblePath.size() == 1) { 2855 Path = &PossiblePath; 2856 if (AmbigiousBaseConvID) 2857 Diag(Loc, diag::ext_ms_ambiguous_direct_base) 2858 << Base << Derived << Range; 2859 break; 2860 } 2861 } 2862 } 2863 2864 if (Path) { 2865 if (!IgnoreAccess) { 2866 // Check that the base class can be accessed. 2867 switch ( 2868 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) { 2869 case AR_inaccessible: 2870 return true; 2871 case AR_accessible: 2872 case AR_dependent: 2873 case AR_delayed: 2874 break; 2875 } 2876 } 2877 2878 // Build a base path if necessary. 2879 if (BasePath) 2880 ::BuildBasePathArray(*Path, *BasePath); 2881 return false; 2882 } 2883 2884 if (AmbigiousBaseConvID) { 2885 // We know that the derived-to-base conversion is ambiguous, and 2886 // we're going to produce a diagnostic. Perform the derived-to-base 2887 // search just one more time to compute all of the possible paths so 2888 // that we can print them out. This is more expensive than any of 2889 // the previous derived-to-base checks we've done, but at this point 2890 // performance isn't as much of an issue. 2891 Paths.clear(); 2892 Paths.setRecordingPaths(true); 2893 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2894 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 2895 (void)StillOkay; 2896 2897 // Build up a textual representation of the ambiguous paths, e.g., 2898 // D -> B -> A, that will be used to illustrate the ambiguous 2899 // conversions in the diagnostic. We only print one of the paths 2900 // to each base class subobject. 2901 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2902 2903 Diag(Loc, AmbigiousBaseConvID) 2904 << Derived << Base << PathDisplayStr << Range << Name; 2905 } 2906 return true; 2907 } 2908 2909 bool 2910 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2911 SourceLocation Loc, SourceRange Range, 2912 CXXCastPath *BasePath, 2913 bool IgnoreAccess) { 2914 return CheckDerivedToBaseConversion( 2915 Derived, Base, diag::err_upcast_to_inaccessible_base, 2916 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(), 2917 BasePath, IgnoreAccess); 2918 } 2919 2920 2921 /// Builds a string representing ambiguous paths from a 2922 /// specific derived class to different subobjects of the same base 2923 /// class. 2924 /// 2925 /// This function builds a string that can be used in error messages 2926 /// to show the different paths that one can take through the 2927 /// inheritance hierarchy to go from the derived class to different 2928 /// subobjects of a base class. The result looks something like this: 2929 /// @code 2930 /// struct D -> struct B -> struct A 2931 /// struct D -> struct C -> struct A 2932 /// @endcode 2933 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 2934 std::string PathDisplayStr; 2935 std::set<unsigned> DisplayedPaths; 2936 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2937 Path != Paths.end(); ++Path) { 2938 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 2939 // We haven't displayed a path to this particular base 2940 // class subobject yet. 2941 PathDisplayStr += "\n "; 2942 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 2943 for (CXXBasePath::const_iterator Element = Path->begin(); 2944 Element != Path->end(); ++Element) 2945 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 2946 } 2947 } 2948 2949 return PathDisplayStr; 2950 } 2951 2952 //===----------------------------------------------------------------------===// 2953 // C++ class member Handling 2954 //===----------------------------------------------------------------------===// 2955 2956 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 2957 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, 2958 SourceLocation ColonLoc, 2959 const ParsedAttributesView &Attrs) { 2960 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 2961 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 2962 ASLoc, ColonLoc); 2963 CurContext->addHiddenDecl(ASDecl); 2964 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 2965 } 2966 2967 /// CheckOverrideControl - Check C++11 override control semantics. 2968 void Sema::CheckOverrideControl(NamedDecl *D) { 2969 if (D->isInvalidDecl()) 2970 return; 2971 2972 // We only care about "override" and "final" declarations. 2973 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 2974 return; 2975 2976 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 2977 2978 // We can't check dependent instance methods. 2979 if (MD && MD->isInstance() && 2980 (MD->getParent()->hasAnyDependentBases() || 2981 MD->getType()->isDependentType())) 2982 return; 2983 2984 if (MD && !MD->isVirtual()) { 2985 // If we have a non-virtual method, check if if hides a virtual method. 2986 // (In that case, it's most likely the method has the wrong type.) 2987 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 2988 FindHiddenVirtualMethods(MD, OverloadedMethods); 2989 2990 if (!OverloadedMethods.empty()) { 2991 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 2992 Diag(OA->getLocation(), 2993 diag::override_keyword_hides_virtual_member_function) 2994 << "override" << (OverloadedMethods.size() > 1); 2995 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 2996 Diag(FA->getLocation(), 2997 diag::override_keyword_hides_virtual_member_function) 2998 << (FA->isSpelledAsSealed() ? "sealed" : "final") 2999 << (OverloadedMethods.size() > 1); 3000 } 3001 NoteHiddenVirtualMethods(MD, OverloadedMethods); 3002 MD->setInvalidDecl(); 3003 return; 3004 } 3005 // Fall through into the general case diagnostic. 3006 // FIXME: We might want to attempt typo correction here. 3007 } 3008 3009 if (!MD || !MD->isVirtual()) { 3010 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 3011 Diag(OA->getLocation(), 3012 diag::override_keyword_only_allowed_on_virtual_member_functions) 3013 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 3014 D->dropAttr<OverrideAttr>(); 3015 } 3016 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 3017 Diag(FA->getLocation(), 3018 diag::override_keyword_only_allowed_on_virtual_member_functions) 3019 << (FA->isSpelledAsSealed() ? "sealed" : "final") 3020 << FixItHint::CreateRemoval(FA->getLocation()); 3021 D->dropAttr<FinalAttr>(); 3022 } 3023 return; 3024 } 3025 3026 // C++11 [class.virtual]p5: 3027 // If a function is marked with the virt-specifier override and 3028 // does not override a member function of a base class, the program is 3029 // ill-formed. 3030 bool HasOverriddenMethods = MD->size_overridden_methods() != 0; 3031 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 3032 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 3033 << MD->getDeclName(); 3034 } 3035 3036 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) { 3037 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) 3038 return; 3039 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 3040 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>()) 3041 return; 3042 3043 SourceLocation Loc = MD->getLocation(); 3044 SourceLocation SpellingLoc = Loc; 3045 if (getSourceManager().isMacroArgExpansion(Loc)) 3046 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin(); 3047 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); 3048 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) 3049 return; 3050 3051 if (MD->size_overridden_methods() > 0) { 3052 unsigned DiagID = isa<CXXDestructorDecl>(MD) 3053 ? diag::warn_destructor_marked_not_override_overriding 3054 : diag::warn_function_marked_not_override_overriding; 3055 Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 3056 const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); 3057 Diag(OMD->getLocation(), diag::note_overridden_virtual_function); 3058 } 3059 } 3060 3061 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 3062 /// function overrides a virtual member function marked 'final', according to 3063 /// C++11 [class.virtual]p4. 3064 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 3065 const CXXMethodDecl *Old) { 3066 FinalAttr *FA = Old->getAttr<FinalAttr>(); 3067 if (!FA) 3068 return false; 3069 3070 Diag(New->getLocation(), diag::err_final_function_overridden) 3071 << New->getDeclName() 3072 << FA->isSpelledAsSealed(); 3073 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 3074 return true; 3075 } 3076 3077 static bool InitializationHasSideEffects(const FieldDecl &FD) { 3078 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 3079 // FIXME: Destruction of ObjC lifetime types has side-effects. 3080 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 3081 return !RD->isCompleteDefinition() || 3082 !RD->hasTrivialDefaultConstructor() || 3083 !RD->hasTrivialDestructor(); 3084 return false; 3085 } 3086 3087 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) { 3088 ParsedAttributesView::const_iterator Itr = 3089 llvm::find_if(list, [](const ParsedAttr &AL) { 3090 return AL.isDeclspecPropertyAttribute(); 3091 }); 3092 if (Itr != list.end()) 3093 return &*Itr; 3094 return nullptr; 3095 } 3096 3097 // Check if there is a field shadowing. 3098 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc, 3099 DeclarationName FieldName, 3100 const CXXRecordDecl *RD, 3101 bool DeclIsField) { 3102 if (Diags.isIgnored(diag::warn_shadow_field, Loc)) 3103 return; 3104 3105 // To record a shadowed field in a base 3106 std::map<CXXRecordDecl*, NamedDecl*> Bases; 3107 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier, 3108 CXXBasePath &Path) { 3109 const auto Base = Specifier->getType()->getAsCXXRecordDecl(); 3110 // Record an ambiguous path directly 3111 if (Bases.find(Base) != Bases.end()) 3112 return true; 3113 for (const auto Field : Base->lookup(FieldName)) { 3114 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) && 3115 Field->getAccess() != AS_private) { 3116 assert(Field->getAccess() != AS_none); 3117 assert(Bases.find(Base) == Bases.end()); 3118 Bases[Base] = Field; 3119 return true; 3120 } 3121 } 3122 return false; 3123 }; 3124 3125 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3126 /*DetectVirtual=*/true); 3127 if (!RD->lookupInBases(FieldShadowed, Paths)) 3128 return; 3129 3130 for (const auto &P : Paths) { 3131 auto Base = P.back().Base->getType()->getAsCXXRecordDecl(); 3132 auto It = Bases.find(Base); 3133 // Skip duplicated bases 3134 if (It == Bases.end()) 3135 continue; 3136 auto BaseField = It->second; 3137 assert(BaseField->getAccess() != AS_private); 3138 if (AS_none != 3139 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) { 3140 Diag(Loc, diag::warn_shadow_field) 3141 << FieldName << RD << Base << DeclIsField; 3142 Diag(BaseField->getLocation(), diag::note_shadow_field); 3143 Bases.erase(It); 3144 } 3145 } 3146 } 3147 3148 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 3149 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 3150 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 3151 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 3152 /// present (but parsing it has been deferred). 3153 NamedDecl * 3154 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 3155 MultiTemplateParamsArg TemplateParameterLists, 3156 Expr *BW, const VirtSpecifiers &VS, 3157 InClassInitStyle InitStyle) { 3158 const DeclSpec &DS = D.getDeclSpec(); 3159 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 3160 DeclarationName Name = NameInfo.getName(); 3161 SourceLocation Loc = NameInfo.getLoc(); 3162 3163 // For anonymous bitfields, the location should point to the type. 3164 if (Loc.isInvalid()) 3165 Loc = D.getBeginLoc(); 3166 3167 Expr *BitWidth = static_cast<Expr*>(BW); 3168 3169 assert(isa<CXXRecordDecl>(CurContext)); 3170 assert(!DS.isFriendSpecified()); 3171 3172 bool isFunc = D.isDeclarationOfFunction(); 3173 const ParsedAttr *MSPropertyAttr = 3174 getMSPropertyAttr(D.getDeclSpec().getAttributes()); 3175 3176 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 3177 // The Microsoft extension __interface only permits public member functions 3178 // and prohibits constructors, destructors, operators, non-public member 3179 // functions, static methods and data members. 3180 unsigned InvalidDecl; 3181 bool ShowDeclName = true; 3182 if (!isFunc && 3183 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr)) 3184 InvalidDecl = 0; 3185 else if (!isFunc) 3186 InvalidDecl = 1; 3187 else if (AS != AS_public) 3188 InvalidDecl = 2; 3189 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 3190 InvalidDecl = 3; 3191 else switch (Name.getNameKind()) { 3192 case DeclarationName::CXXConstructorName: 3193 InvalidDecl = 4; 3194 ShowDeclName = false; 3195 break; 3196 3197 case DeclarationName::CXXDestructorName: 3198 InvalidDecl = 5; 3199 ShowDeclName = false; 3200 break; 3201 3202 case DeclarationName::CXXOperatorName: 3203 case DeclarationName::CXXConversionFunctionName: 3204 InvalidDecl = 6; 3205 break; 3206 3207 default: 3208 InvalidDecl = 0; 3209 break; 3210 } 3211 3212 if (InvalidDecl) { 3213 if (ShowDeclName) 3214 Diag(Loc, diag::err_invalid_member_in_interface) 3215 << (InvalidDecl-1) << Name; 3216 else 3217 Diag(Loc, diag::err_invalid_member_in_interface) 3218 << (InvalidDecl-1) << ""; 3219 return nullptr; 3220 } 3221 } 3222 3223 // C++ 9.2p6: A member shall not be declared to have automatic storage 3224 // duration (auto, register) or with the extern storage-class-specifier. 3225 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 3226 // data members and cannot be applied to names declared const or static, 3227 // and cannot be applied to reference members. 3228 switch (DS.getStorageClassSpec()) { 3229 case DeclSpec::SCS_unspecified: 3230 case DeclSpec::SCS_typedef: 3231 case DeclSpec::SCS_static: 3232 break; 3233 case DeclSpec::SCS_mutable: 3234 if (isFunc) { 3235 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 3236 3237 // FIXME: It would be nicer if the keyword was ignored only for this 3238 // declarator. Otherwise we could get follow-up errors. 3239 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3240 } 3241 break; 3242 default: 3243 Diag(DS.getStorageClassSpecLoc(), 3244 diag::err_storageclass_invalid_for_member); 3245 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3246 break; 3247 } 3248 3249 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 3250 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 3251 !isFunc); 3252 3253 if (DS.hasConstexprSpecifier() && isInstField) { 3254 SemaDiagnosticBuilder B = 3255 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 3256 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 3257 if (InitStyle == ICIS_NoInit) { 3258 B << 0 << 0; 3259 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 3260 B << FixItHint::CreateRemoval(ConstexprLoc); 3261 else { 3262 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 3263 D.getMutableDeclSpec().ClearConstexprSpec(); 3264 const char *PrevSpec; 3265 unsigned DiagID; 3266 bool Failed = D.getMutableDeclSpec().SetTypeQual( 3267 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 3268 (void)Failed; 3269 assert(!Failed && "Making a constexpr member const shouldn't fail"); 3270 } 3271 } else { 3272 B << 1; 3273 const char *PrevSpec; 3274 unsigned DiagID; 3275 if (D.getMutableDeclSpec().SetStorageClassSpec( 3276 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 3277 Context.getPrintingPolicy())) { 3278 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 3279 "This is the only DeclSpec that should fail to be applied"); 3280 B << 1; 3281 } else { 3282 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 3283 isInstField = false; 3284 } 3285 } 3286 } 3287 3288 NamedDecl *Member; 3289 if (isInstField) { 3290 CXXScopeSpec &SS = D.getCXXScopeSpec(); 3291 3292 // Data members must have identifiers for names. 3293 if (!Name.isIdentifier()) { 3294 Diag(Loc, diag::err_bad_variable_name) 3295 << Name; 3296 return nullptr; 3297 } 3298 3299 IdentifierInfo *II = Name.getAsIdentifierInfo(); 3300 3301 // Member field could not be with "template" keyword. 3302 // So TemplateParameterLists should be empty in this case. 3303 if (TemplateParameterLists.size()) { 3304 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 3305 if (TemplateParams->size()) { 3306 // There is no such thing as a member field template. 3307 Diag(D.getIdentifierLoc(), diag::err_template_member) 3308 << II 3309 << SourceRange(TemplateParams->getTemplateLoc(), 3310 TemplateParams->getRAngleLoc()); 3311 } else { 3312 // There is an extraneous 'template<>' for this member. 3313 Diag(TemplateParams->getTemplateLoc(), 3314 diag::err_template_member_noparams) 3315 << II 3316 << SourceRange(TemplateParams->getTemplateLoc(), 3317 TemplateParams->getRAngleLoc()); 3318 } 3319 return nullptr; 3320 } 3321 3322 if (SS.isSet() && !SS.isInvalid()) { 3323 // The user provided a superfluous scope specifier inside a class 3324 // definition: 3325 // 3326 // class X { 3327 // int X::member; 3328 // }; 3329 if (DeclContext *DC = computeDeclContext(SS, false)) 3330 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(), 3331 D.getName().getKind() == 3332 UnqualifiedIdKind::IK_TemplateId); 3333 else 3334 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 3335 << Name << SS.getRange(); 3336 3337 SS.clear(); 3338 } 3339 3340 if (MSPropertyAttr) { 3341 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3342 BitWidth, InitStyle, AS, *MSPropertyAttr); 3343 if (!Member) 3344 return nullptr; 3345 isInstField = false; 3346 } else { 3347 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3348 BitWidth, InitStyle, AS); 3349 if (!Member) 3350 return nullptr; 3351 } 3352 3353 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext)); 3354 } else { 3355 Member = HandleDeclarator(S, D, TemplateParameterLists); 3356 if (!Member) 3357 return nullptr; 3358 3359 // Non-instance-fields can't have a bitfield. 3360 if (BitWidth) { 3361 if (Member->isInvalidDecl()) { 3362 // don't emit another diagnostic. 3363 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) { 3364 // C++ 9.6p3: A bit-field shall not be a static member. 3365 // "static member 'A' cannot be a bit-field" 3366 Diag(Loc, diag::err_static_not_bitfield) 3367 << Name << BitWidth->getSourceRange(); 3368 } else if (isa<TypedefDecl>(Member)) { 3369 // "typedef member 'x' cannot be a bit-field" 3370 Diag(Loc, diag::err_typedef_not_bitfield) 3371 << Name << BitWidth->getSourceRange(); 3372 } else { 3373 // A function typedef ("typedef int f(); f a;"). 3374 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 3375 Diag(Loc, diag::err_not_integral_type_bitfield) 3376 << Name << cast<ValueDecl>(Member)->getType() 3377 << BitWidth->getSourceRange(); 3378 } 3379 3380 BitWidth = nullptr; 3381 Member->setInvalidDecl(); 3382 } 3383 3384 NamedDecl *NonTemplateMember = Member; 3385 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 3386 NonTemplateMember = FunTmpl->getTemplatedDecl(); 3387 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 3388 NonTemplateMember = VarTmpl->getTemplatedDecl(); 3389 3390 Member->setAccess(AS); 3391 3392 // If we have declared a member function template or static data member 3393 // template, set the access of the templated declaration as well. 3394 if (NonTemplateMember != Member) 3395 NonTemplateMember->setAccess(AS); 3396 3397 // C++ [temp.deduct.guide]p3: 3398 // A deduction guide [...] for a member class template [shall be 3399 // declared] with the same access [as the template]. 3400 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) { 3401 auto *TD = DG->getDeducedTemplate(); 3402 // Access specifiers are only meaningful if both the template and the 3403 // deduction guide are from the same scope. 3404 if (AS != TD->getAccess() && 3405 TD->getDeclContext()->getRedeclContext()->Equals( 3406 DG->getDeclContext()->getRedeclContext())) { 3407 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access); 3408 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access) 3409 << TD->getAccess(); 3410 const AccessSpecDecl *LastAccessSpec = nullptr; 3411 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) { 3412 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D)) 3413 LastAccessSpec = AccessSpec; 3414 } 3415 assert(LastAccessSpec && "differing access with no access specifier"); 3416 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access) 3417 << AS; 3418 } 3419 } 3420 } 3421 3422 if (VS.isOverrideSpecified()) 3423 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(), 3424 AttributeCommonInfo::AS_Keyword)); 3425 if (VS.isFinalSpecified()) 3426 Member->addAttr(FinalAttr::Create( 3427 Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword, 3428 static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed()))); 3429 3430 if (VS.getLastLocation().isValid()) { 3431 // Update the end location of a method that has a virt-specifiers. 3432 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 3433 MD->setRangeEnd(VS.getLastLocation()); 3434 } 3435 3436 CheckOverrideControl(Member); 3437 3438 assert((Name || isInstField) && "No identifier for non-field ?"); 3439 3440 if (isInstField) { 3441 FieldDecl *FD = cast<FieldDecl>(Member); 3442 FieldCollector->Add(FD); 3443 3444 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 3445 // Remember all explicit private FieldDecls that have a name, no side 3446 // effects and are not part of a dependent type declaration. 3447 if (!FD->isImplicit() && FD->getDeclName() && 3448 FD->getAccess() == AS_private && 3449 !FD->hasAttr<UnusedAttr>() && 3450 !FD->getParent()->isDependentContext() && 3451 !InitializationHasSideEffects(*FD)) 3452 UnusedPrivateFields.insert(FD); 3453 } 3454 } 3455 3456 return Member; 3457 } 3458 3459 namespace { 3460 class UninitializedFieldVisitor 3461 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 3462 Sema &S; 3463 // List of Decls to generate a warning on. Also remove Decls that become 3464 // initialized. 3465 llvm::SmallPtrSetImpl<ValueDecl*> &Decls; 3466 // List of base classes of the record. Classes are removed after their 3467 // initializers. 3468 llvm::SmallPtrSetImpl<QualType> &BaseClasses; 3469 // Vector of decls to be removed from the Decl set prior to visiting the 3470 // nodes. These Decls may have been initialized in the prior initializer. 3471 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; 3472 // If non-null, add a note to the warning pointing back to the constructor. 3473 const CXXConstructorDecl *Constructor; 3474 // Variables to hold state when processing an initializer list. When 3475 // InitList is true, special case initialization of FieldDecls matching 3476 // InitListFieldDecl. 3477 bool InitList; 3478 FieldDecl *InitListFieldDecl; 3479 llvm::SmallVector<unsigned, 4> InitFieldIndex; 3480 3481 public: 3482 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 3483 UninitializedFieldVisitor(Sema &S, 3484 llvm::SmallPtrSetImpl<ValueDecl*> &Decls, 3485 llvm::SmallPtrSetImpl<QualType> &BaseClasses) 3486 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), 3487 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} 3488 3489 // Returns true if the use of ME is not an uninitialized use. 3490 bool IsInitListMemberExprInitialized(MemberExpr *ME, 3491 bool CheckReferenceOnly) { 3492 llvm::SmallVector<FieldDecl*, 4> Fields; 3493 bool ReferenceField = false; 3494 while (ME) { 3495 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 3496 if (!FD) 3497 return false; 3498 Fields.push_back(FD); 3499 if (FD->getType()->isReferenceType()) 3500 ReferenceField = true; 3501 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); 3502 } 3503 3504 // Binding a reference to an uninitialized field is not an 3505 // uninitialized use. 3506 if (CheckReferenceOnly && !ReferenceField) 3507 return true; 3508 3509 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 3510 // Discard the first field since it is the field decl that is being 3511 // initialized. 3512 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) { 3513 UsedFieldIndex.push_back((*I)->getFieldIndex()); 3514 } 3515 3516 for (auto UsedIter = UsedFieldIndex.begin(), 3517 UsedEnd = UsedFieldIndex.end(), 3518 OrigIter = InitFieldIndex.begin(), 3519 OrigEnd = InitFieldIndex.end(); 3520 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 3521 if (*UsedIter < *OrigIter) 3522 return true; 3523 if (*UsedIter > *OrigIter) 3524 break; 3525 } 3526 3527 return false; 3528 } 3529 3530 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, 3531 bool AddressOf) { 3532 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 3533 return; 3534 3535 // FieldME is the inner-most MemberExpr that is not an anonymous struct 3536 // or union. 3537 MemberExpr *FieldME = ME; 3538 3539 bool AllPODFields = FieldME->getType().isPODType(S.Context); 3540 3541 Expr *Base = ME; 3542 while (MemberExpr *SubME = 3543 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { 3544 3545 if (isa<VarDecl>(SubME->getMemberDecl())) 3546 return; 3547 3548 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) 3549 if (!FD->isAnonymousStructOrUnion()) 3550 FieldME = SubME; 3551 3552 if (!FieldME->getType().isPODType(S.Context)) 3553 AllPODFields = false; 3554 3555 Base = SubME->getBase(); 3556 } 3557 3558 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) 3559 return; 3560 3561 if (AddressOf && AllPODFields) 3562 return; 3563 3564 ValueDecl* FoundVD = FieldME->getMemberDecl(); 3565 3566 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { 3567 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { 3568 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); 3569 } 3570 3571 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { 3572 QualType T = BaseCast->getType(); 3573 if (T->isPointerType() && 3574 BaseClasses.count(T->getPointeeType())) { 3575 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) 3576 << T->getPointeeType() << FoundVD; 3577 } 3578 } 3579 } 3580 3581 if (!Decls.count(FoundVD)) 3582 return; 3583 3584 const bool IsReference = FoundVD->getType()->isReferenceType(); 3585 3586 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { 3587 // Special checking for initializer lists. 3588 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { 3589 return; 3590 } 3591 } else { 3592 // Prevent double warnings on use of unbounded references. 3593 if (CheckReferenceOnly && !IsReference) 3594 return; 3595 } 3596 3597 unsigned diag = IsReference 3598 ? diag::warn_reference_field_is_uninit 3599 : diag::warn_field_is_uninit; 3600 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 3601 if (Constructor) 3602 S.Diag(Constructor->getLocation(), 3603 diag::note_uninit_in_this_constructor) 3604 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 3605 3606 } 3607 3608 void HandleValue(Expr *E, bool AddressOf) { 3609 E = E->IgnoreParens(); 3610 3611 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3612 HandleMemberExpr(ME, false /*CheckReferenceOnly*/, 3613 AddressOf /*AddressOf*/); 3614 return; 3615 } 3616 3617 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 3618 Visit(CO->getCond()); 3619 HandleValue(CO->getTrueExpr(), AddressOf); 3620 HandleValue(CO->getFalseExpr(), AddressOf); 3621 return; 3622 } 3623 3624 if (BinaryConditionalOperator *BCO = 3625 dyn_cast<BinaryConditionalOperator>(E)) { 3626 Visit(BCO->getCond()); 3627 HandleValue(BCO->getFalseExpr(), AddressOf); 3628 return; 3629 } 3630 3631 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 3632 HandleValue(OVE->getSourceExpr(), AddressOf); 3633 return; 3634 } 3635 3636 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 3637 switch (BO->getOpcode()) { 3638 default: 3639 break; 3640 case(BO_PtrMemD): 3641 case(BO_PtrMemI): 3642 HandleValue(BO->getLHS(), AddressOf); 3643 Visit(BO->getRHS()); 3644 return; 3645 case(BO_Comma): 3646 Visit(BO->getLHS()); 3647 HandleValue(BO->getRHS(), AddressOf); 3648 return; 3649 } 3650 } 3651 3652 Visit(E); 3653 } 3654 3655 void CheckInitListExpr(InitListExpr *ILE) { 3656 InitFieldIndex.push_back(0); 3657 for (auto Child : ILE->children()) { 3658 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { 3659 CheckInitListExpr(SubList); 3660 } else { 3661 Visit(Child); 3662 } 3663 ++InitFieldIndex.back(); 3664 } 3665 InitFieldIndex.pop_back(); 3666 } 3667 3668 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, 3669 FieldDecl *Field, const Type *BaseClass) { 3670 // Remove Decls that may have been initialized in the previous 3671 // initializer. 3672 for (ValueDecl* VD : DeclsToRemove) 3673 Decls.erase(VD); 3674 DeclsToRemove.clear(); 3675 3676 Constructor = FieldConstructor; 3677 InitListExpr *ILE = dyn_cast<InitListExpr>(E); 3678 3679 if (ILE && Field) { 3680 InitList = true; 3681 InitListFieldDecl = Field; 3682 InitFieldIndex.clear(); 3683 CheckInitListExpr(ILE); 3684 } else { 3685 InitList = false; 3686 Visit(E); 3687 } 3688 3689 if (Field) 3690 Decls.erase(Field); 3691 if (BaseClass) 3692 BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); 3693 } 3694 3695 void VisitMemberExpr(MemberExpr *ME) { 3696 // All uses of unbounded reference fields will warn. 3697 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); 3698 } 3699 3700 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 3701 if (E->getCastKind() == CK_LValueToRValue) { 3702 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3703 return; 3704 } 3705 3706 Inherited::VisitImplicitCastExpr(E); 3707 } 3708 3709 void VisitCXXConstructExpr(CXXConstructExpr *E) { 3710 if (E->getConstructor()->isCopyConstructor()) { 3711 Expr *ArgExpr = E->getArg(0); 3712 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 3713 if (ILE->getNumInits() == 1) 3714 ArgExpr = ILE->getInit(0); 3715 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 3716 if (ICE->getCastKind() == CK_NoOp) 3717 ArgExpr = ICE->getSubExpr(); 3718 HandleValue(ArgExpr, false /*AddressOf*/); 3719 return; 3720 } 3721 Inherited::VisitCXXConstructExpr(E); 3722 } 3723 3724 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 3725 Expr *Callee = E->getCallee(); 3726 if (isa<MemberExpr>(Callee)) { 3727 HandleValue(Callee, false /*AddressOf*/); 3728 for (auto Arg : E->arguments()) 3729 Visit(Arg); 3730 return; 3731 } 3732 3733 Inherited::VisitCXXMemberCallExpr(E); 3734 } 3735 3736 void VisitCallExpr(CallExpr *E) { 3737 // Treat std::move as a use. 3738 if (E->isCallToStdMove()) { 3739 HandleValue(E->getArg(0), /*AddressOf=*/false); 3740 return; 3741 } 3742 3743 Inherited::VisitCallExpr(E); 3744 } 3745 3746 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 3747 Expr *Callee = E->getCallee(); 3748 3749 if (isa<UnresolvedLookupExpr>(Callee)) 3750 return Inherited::VisitCXXOperatorCallExpr(E); 3751 3752 Visit(Callee); 3753 for (auto Arg : E->arguments()) 3754 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); 3755 } 3756 3757 void VisitBinaryOperator(BinaryOperator *E) { 3758 // If a field assignment is detected, remove the field from the 3759 // uninitiailized field set. 3760 if (E->getOpcode() == BO_Assign) 3761 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 3762 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 3763 if (!FD->getType()->isReferenceType()) 3764 DeclsToRemove.push_back(FD); 3765 3766 if (E->isCompoundAssignmentOp()) { 3767 HandleValue(E->getLHS(), false /*AddressOf*/); 3768 Visit(E->getRHS()); 3769 return; 3770 } 3771 3772 Inherited::VisitBinaryOperator(E); 3773 } 3774 3775 void VisitUnaryOperator(UnaryOperator *E) { 3776 if (E->isIncrementDecrementOp()) { 3777 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3778 return; 3779 } 3780 if (E->getOpcode() == UO_AddrOf) { 3781 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { 3782 HandleValue(ME->getBase(), true /*AddressOf*/); 3783 return; 3784 } 3785 } 3786 3787 Inherited::VisitUnaryOperator(E); 3788 } 3789 }; 3790 3791 // Diagnose value-uses of fields to initialize themselves, e.g. 3792 // foo(foo) 3793 // where foo is not also a parameter to the constructor. 3794 // Also diagnose across field uninitialized use such as 3795 // x(y), y(x) 3796 // TODO: implement -Wuninitialized and fold this into that framework. 3797 static void DiagnoseUninitializedFields( 3798 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 3799 3800 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 3801 Constructor->getLocation())) { 3802 return; 3803 } 3804 3805 if (Constructor->isInvalidDecl()) 3806 return; 3807 3808 const CXXRecordDecl *RD = Constructor->getParent(); 3809 3810 if (RD->getDescribedClassTemplate()) 3811 return; 3812 3813 // Holds fields that are uninitialized. 3814 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 3815 3816 // At the beginning, all fields are uninitialized. 3817 for (auto *I : RD->decls()) { 3818 if (auto *FD = dyn_cast<FieldDecl>(I)) { 3819 UninitializedFields.insert(FD); 3820 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 3821 UninitializedFields.insert(IFD->getAnonField()); 3822 } 3823 } 3824 3825 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; 3826 for (auto I : RD->bases()) 3827 UninitializedBaseClasses.insert(I.getType().getCanonicalType()); 3828 3829 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3830 return; 3831 3832 UninitializedFieldVisitor UninitializedChecker(SemaRef, 3833 UninitializedFields, 3834 UninitializedBaseClasses); 3835 3836 for (const auto *FieldInit : Constructor->inits()) { 3837 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3838 break; 3839 3840 Expr *InitExpr = FieldInit->getInit(); 3841 if (!InitExpr) 3842 continue; 3843 3844 if (CXXDefaultInitExpr *Default = 3845 dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 3846 InitExpr = Default->getExpr(); 3847 if (!InitExpr) 3848 continue; 3849 // In class initializers will point to the constructor. 3850 UninitializedChecker.CheckInitializer(InitExpr, Constructor, 3851 FieldInit->getAnyMember(), 3852 FieldInit->getBaseClass()); 3853 } else { 3854 UninitializedChecker.CheckInitializer(InitExpr, nullptr, 3855 FieldInit->getAnyMember(), 3856 FieldInit->getBaseClass()); 3857 } 3858 } 3859 } 3860 } // namespace 3861 3862 /// Enter a new C++ default initializer scope. After calling this, the 3863 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 3864 /// parsing or instantiating the initializer failed. 3865 void Sema::ActOnStartCXXInClassMemberInitializer() { 3866 // Create a synthetic function scope to represent the call to the constructor 3867 // that notionally surrounds a use of this initializer. 3868 PushFunctionScope(); 3869 } 3870 3871 /// This is invoked after parsing an in-class initializer for a 3872 /// non-static C++ class member, and after instantiating an in-class initializer 3873 /// in a class template. Such actions are deferred until the class is complete. 3874 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 3875 SourceLocation InitLoc, 3876 Expr *InitExpr) { 3877 // Pop the notional constructor scope we created earlier. 3878 PopFunctionScopeInfo(nullptr, D); 3879 3880 FieldDecl *FD = dyn_cast<FieldDecl>(D); 3881 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && 3882 "must set init style when field is created"); 3883 3884 if (!InitExpr) { 3885 D->setInvalidDecl(); 3886 if (FD) 3887 FD->removeInClassInitializer(); 3888 return; 3889 } 3890 3891 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 3892 FD->setInvalidDecl(); 3893 FD->removeInClassInitializer(); 3894 return; 3895 } 3896 3897 ExprResult Init = InitExpr; 3898 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 3899 InitializedEntity Entity = 3900 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD); 3901 InitializationKind Kind = 3902 FD->getInClassInitStyle() == ICIS_ListInit 3903 ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(), 3904 InitExpr->getBeginLoc(), 3905 InitExpr->getEndLoc()) 3906 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc); 3907 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 3908 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 3909 if (Init.isInvalid()) { 3910 FD->setInvalidDecl(); 3911 return; 3912 } 3913 } 3914 3915 // C++11 [class.base.init]p7: 3916 // The initialization of each base and member constitutes a 3917 // full-expression. 3918 Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false); 3919 if (Init.isInvalid()) { 3920 FD->setInvalidDecl(); 3921 return; 3922 } 3923 3924 InitExpr = Init.get(); 3925 3926 FD->setInClassInitializer(InitExpr); 3927 } 3928 3929 /// Find the direct and/or virtual base specifiers that 3930 /// correspond to the given base type, for use in base initialization 3931 /// within a constructor. 3932 static bool FindBaseInitializer(Sema &SemaRef, 3933 CXXRecordDecl *ClassDecl, 3934 QualType BaseType, 3935 const CXXBaseSpecifier *&DirectBaseSpec, 3936 const CXXBaseSpecifier *&VirtualBaseSpec) { 3937 // First, check for a direct base class. 3938 DirectBaseSpec = nullptr; 3939 for (const auto &Base : ClassDecl->bases()) { 3940 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 3941 // We found a direct base of this type. That's what we're 3942 // initializing. 3943 DirectBaseSpec = &Base; 3944 break; 3945 } 3946 } 3947 3948 // Check for a virtual base class. 3949 // FIXME: We might be able to short-circuit this if we know in advance that 3950 // there are no virtual bases. 3951 VirtualBaseSpec = nullptr; 3952 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 3953 // We haven't found a base yet; search the class hierarchy for a 3954 // virtual base class. 3955 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3956 /*DetectVirtual=*/false); 3957 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(), 3958 SemaRef.Context.getTypeDeclType(ClassDecl), 3959 BaseType, Paths)) { 3960 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 3961 Path != Paths.end(); ++Path) { 3962 if (Path->back().Base->isVirtual()) { 3963 VirtualBaseSpec = Path->back().Base; 3964 break; 3965 } 3966 } 3967 } 3968 } 3969 3970 return DirectBaseSpec || VirtualBaseSpec; 3971 } 3972 3973 /// Handle a C++ member initializer using braced-init-list syntax. 3974 MemInitResult 3975 Sema::ActOnMemInitializer(Decl *ConstructorD, 3976 Scope *S, 3977 CXXScopeSpec &SS, 3978 IdentifierInfo *MemberOrBase, 3979 ParsedType TemplateTypeTy, 3980 const DeclSpec &DS, 3981 SourceLocation IdLoc, 3982 Expr *InitList, 3983 SourceLocation EllipsisLoc) { 3984 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 3985 DS, IdLoc, InitList, 3986 EllipsisLoc); 3987 } 3988 3989 /// Handle a C++ member initializer using parentheses syntax. 3990 MemInitResult 3991 Sema::ActOnMemInitializer(Decl *ConstructorD, 3992 Scope *S, 3993 CXXScopeSpec &SS, 3994 IdentifierInfo *MemberOrBase, 3995 ParsedType TemplateTypeTy, 3996 const DeclSpec &DS, 3997 SourceLocation IdLoc, 3998 SourceLocation LParenLoc, 3999 ArrayRef<Expr *> Args, 4000 SourceLocation RParenLoc, 4001 SourceLocation EllipsisLoc) { 4002 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc); 4003 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 4004 DS, IdLoc, List, EllipsisLoc); 4005 } 4006 4007 namespace { 4008 4009 // Callback to only accept typo corrections that can be a valid C++ member 4010 // intializer: either a non-static field member or a base class. 4011 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback { 4012 public: 4013 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 4014 : ClassDecl(ClassDecl) {} 4015 4016 bool ValidateCandidate(const TypoCorrection &candidate) override { 4017 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 4018 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 4019 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 4020 return isa<TypeDecl>(ND); 4021 } 4022 return false; 4023 } 4024 4025 std::unique_ptr<CorrectionCandidateCallback> clone() override { 4026 return std::make_unique<MemInitializerValidatorCCC>(*this); 4027 } 4028 4029 private: 4030 CXXRecordDecl *ClassDecl; 4031 }; 4032 4033 } 4034 4035 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, 4036 CXXScopeSpec &SS, 4037 ParsedType TemplateTypeTy, 4038 IdentifierInfo *MemberOrBase) { 4039 if (SS.getScopeRep() || TemplateTypeTy) 4040 return nullptr; 4041 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase); 4042 if (Result.empty()) 4043 return nullptr; 4044 ValueDecl *Member; 4045 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 4046 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) 4047 return Member; 4048 return nullptr; 4049 } 4050 4051 /// Handle a C++ member initializer. 4052 MemInitResult 4053 Sema::BuildMemInitializer(Decl *ConstructorD, 4054 Scope *S, 4055 CXXScopeSpec &SS, 4056 IdentifierInfo *MemberOrBase, 4057 ParsedType TemplateTypeTy, 4058 const DeclSpec &DS, 4059 SourceLocation IdLoc, 4060 Expr *Init, 4061 SourceLocation EllipsisLoc) { 4062 ExprResult Res = CorrectDelayedTyposInExpr(Init); 4063 if (!Res.isUsable()) 4064 return true; 4065 Init = Res.get(); 4066 4067 if (!ConstructorD) 4068 return true; 4069 4070 AdjustDeclIfTemplate(ConstructorD); 4071 4072 CXXConstructorDecl *Constructor 4073 = dyn_cast<CXXConstructorDecl>(ConstructorD); 4074 if (!Constructor) { 4075 // The user wrote a constructor initializer on a function that is 4076 // not a C++ constructor. Ignore the error for now, because we may 4077 // have more member initializers coming; we'll diagnose it just 4078 // once in ActOnMemInitializers. 4079 return true; 4080 } 4081 4082 CXXRecordDecl *ClassDecl = Constructor->getParent(); 4083 4084 // C++ [class.base.init]p2: 4085 // Names in a mem-initializer-id are looked up in the scope of the 4086 // constructor's class and, if not found in that scope, are looked 4087 // up in the scope containing the constructor's definition. 4088 // [Note: if the constructor's class contains a member with the 4089 // same name as a direct or virtual base class of the class, a 4090 // mem-initializer-id naming the member or base class and composed 4091 // of a single identifier refers to the class member. A 4092 // mem-initializer-id for the hidden base class may be specified 4093 // using a qualified name. ] 4094 4095 // Look for a member, first. 4096 if (ValueDecl *Member = tryLookupCtorInitMemberDecl( 4097 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) { 4098 if (EllipsisLoc.isValid()) 4099 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 4100 << MemberOrBase 4101 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 4102 4103 return BuildMemberInitializer(Member, Init, IdLoc); 4104 } 4105 // It didn't name a member, so see if it names a class. 4106 QualType BaseType; 4107 TypeSourceInfo *TInfo = nullptr; 4108 4109 if (TemplateTypeTy) { 4110 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 4111 if (BaseType.isNull()) 4112 return true; 4113 } else if (DS.getTypeSpecType() == TST_decltype) { 4114 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 4115 } else if (DS.getTypeSpecType() == TST_decltype_auto) { 4116 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); 4117 return true; 4118 } else { 4119 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 4120 LookupParsedName(R, S, &SS); 4121 4122 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 4123 if (!TyD) { 4124 if (R.isAmbiguous()) return true; 4125 4126 // We don't want access-control diagnostics here. 4127 R.suppressDiagnostics(); 4128 4129 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 4130 bool NotUnknownSpecialization = false; 4131 DeclContext *DC = computeDeclContext(SS, false); 4132 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 4133 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 4134 4135 if (!NotUnknownSpecialization) { 4136 // When the scope specifier can refer to a member of an unknown 4137 // specialization, we take it as a type name. 4138 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 4139 SS.getWithLocInContext(Context), 4140 *MemberOrBase, IdLoc); 4141 if (BaseType.isNull()) 4142 return true; 4143 4144 TInfo = Context.CreateTypeSourceInfo(BaseType); 4145 DependentNameTypeLoc TL = 4146 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>(); 4147 if (!TL.isNull()) { 4148 TL.setNameLoc(IdLoc); 4149 TL.setElaboratedKeywordLoc(SourceLocation()); 4150 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4151 } 4152 4153 R.clear(); 4154 R.setLookupName(MemberOrBase); 4155 } 4156 } 4157 4158 // If no results were found, try to correct typos. 4159 TypoCorrection Corr; 4160 MemInitializerValidatorCCC CCC(ClassDecl); 4161 if (R.empty() && BaseType.isNull() && 4162 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 4163 CCC, CTK_ErrorRecovery, ClassDecl))) { 4164 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 4165 // We have found a non-static data member with a similar 4166 // name to what was typed; complain and initialize that 4167 // member. 4168 diagnoseTypo(Corr, 4169 PDiag(diag::err_mem_init_not_member_or_class_suggest) 4170 << MemberOrBase << true); 4171 return BuildMemberInitializer(Member, Init, IdLoc); 4172 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 4173 const CXXBaseSpecifier *DirectBaseSpec; 4174 const CXXBaseSpecifier *VirtualBaseSpec; 4175 if (FindBaseInitializer(*this, ClassDecl, 4176 Context.getTypeDeclType(Type), 4177 DirectBaseSpec, VirtualBaseSpec)) { 4178 // We have found a direct or virtual base class with a 4179 // similar name to what was typed; complain and initialize 4180 // that base class. 4181 diagnoseTypo(Corr, 4182 PDiag(diag::err_mem_init_not_member_or_class_suggest) 4183 << MemberOrBase << false, 4184 PDiag() /*Suppress note, we provide our own.*/); 4185 4186 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 4187 : VirtualBaseSpec; 4188 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here) 4189 << BaseSpec->getType() << BaseSpec->getSourceRange(); 4190 4191 TyD = Type; 4192 } 4193 } 4194 } 4195 4196 if (!TyD && BaseType.isNull()) { 4197 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 4198 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 4199 return true; 4200 } 4201 } 4202 4203 if (BaseType.isNull()) { 4204 BaseType = Context.getTypeDeclType(TyD); 4205 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); 4206 if (SS.isSet()) { 4207 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 4208 BaseType); 4209 TInfo = Context.CreateTypeSourceInfo(BaseType); 4210 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>(); 4211 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc); 4212 TL.setElaboratedKeywordLoc(SourceLocation()); 4213 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4214 } 4215 } 4216 } 4217 4218 if (!TInfo) 4219 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 4220 4221 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 4222 } 4223 4224 MemInitResult 4225 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 4226 SourceLocation IdLoc) { 4227 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 4228 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 4229 assert((DirectMember || IndirectMember) && 4230 "Member must be a FieldDecl or IndirectFieldDecl"); 4231 4232 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4233 return true; 4234 4235 if (Member->isInvalidDecl()) 4236 return true; 4237 4238 MultiExprArg Args; 4239 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4240 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4241 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 4242 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 4243 } else { 4244 // Template instantiation doesn't reconstruct ParenListExprs for us. 4245 Args = Init; 4246 } 4247 4248 SourceRange InitRange = Init->getSourceRange(); 4249 4250 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 4251 // Can't check initialization for a member of dependent type or when 4252 // any of the arguments are type-dependent expressions. 4253 DiscardCleanupsInEvaluationContext(); 4254 } else { 4255 bool InitList = false; 4256 if (isa<InitListExpr>(Init)) { 4257 InitList = true; 4258 Args = Init; 4259 } 4260 4261 // Initialize the member. 4262 InitializedEntity MemberEntity = 4263 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 4264 : InitializedEntity::InitializeMember(IndirectMember, 4265 nullptr); 4266 InitializationKind Kind = 4267 InitList ? InitializationKind::CreateDirectList( 4268 IdLoc, Init->getBeginLoc(), Init->getEndLoc()) 4269 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 4270 InitRange.getEnd()); 4271 4272 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 4273 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 4274 nullptr); 4275 if (MemberInit.isInvalid()) 4276 return true; 4277 4278 // C++11 [class.base.init]p7: 4279 // The initialization of each base and member constitutes a 4280 // full-expression. 4281 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(), 4282 /*DiscardedValue*/ false); 4283 if (MemberInit.isInvalid()) 4284 return true; 4285 4286 Init = MemberInit.get(); 4287 } 4288 4289 if (DirectMember) { 4290 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 4291 InitRange.getBegin(), Init, 4292 InitRange.getEnd()); 4293 } else { 4294 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 4295 InitRange.getBegin(), Init, 4296 InitRange.getEnd()); 4297 } 4298 } 4299 4300 MemInitResult 4301 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 4302 CXXRecordDecl *ClassDecl) { 4303 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4304 if (!LangOpts.CPlusPlus11) 4305 return Diag(NameLoc, diag::err_delegating_ctor) 4306 << TInfo->getTypeLoc().getLocalSourceRange(); 4307 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 4308 4309 bool InitList = true; 4310 MultiExprArg Args = Init; 4311 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4312 InitList = false; 4313 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4314 } 4315 4316 SourceRange InitRange = Init->getSourceRange(); 4317 // Initialize the object. 4318 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 4319 QualType(ClassDecl->getTypeForDecl(), 0)); 4320 InitializationKind Kind = 4321 InitList ? InitializationKind::CreateDirectList( 4322 NameLoc, Init->getBeginLoc(), Init->getEndLoc()) 4323 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 4324 InitRange.getEnd()); 4325 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 4326 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 4327 Args, nullptr); 4328 if (DelegationInit.isInvalid()) 4329 return true; 4330 4331 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 4332 "Delegating constructor with no target?"); 4333 4334 // C++11 [class.base.init]p7: 4335 // The initialization of each base and member constitutes a 4336 // full-expression. 4337 DelegationInit = ActOnFinishFullExpr( 4338 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false); 4339 if (DelegationInit.isInvalid()) 4340 return true; 4341 4342 // If we are in a dependent context, template instantiation will 4343 // perform this type-checking again. Just save the arguments that we 4344 // received in a ParenListExpr. 4345 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4346 // of the information that we have about the base 4347 // initializer. However, deconstructing the ASTs is a dicey process, 4348 // and this approach is far more likely to get the corner cases right. 4349 if (CurContext->isDependentContext()) 4350 DelegationInit = Init; 4351 4352 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 4353 DelegationInit.getAs<Expr>(), 4354 InitRange.getEnd()); 4355 } 4356 4357 MemInitResult 4358 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 4359 Expr *Init, CXXRecordDecl *ClassDecl, 4360 SourceLocation EllipsisLoc) { 4361 SourceLocation BaseLoc 4362 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4363 4364 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 4365 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 4366 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4367 4368 // C++ [class.base.init]p2: 4369 // [...] Unless the mem-initializer-id names a nonstatic data 4370 // member of the constructor's class or a direct or virtual base 4371 // of that class, the mem-initializer is ill-formed. A 4372 // mem-initializer-list can initialize a base class using any 4373 // name that denotes that base class type. 4374 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 4375 4376 SourceRange InitRange = Init->getSourceRange(); 4377 if (EllipsisLoc.isValid()) { 4378 // This is a pack expansion. 4379 if (!BaseType->containsUnexpandedParameterPack()) { 4380 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 4381 << SourceRange(BaseLoc, InitRange.getEnd()); 4382 4383 EllipsisLoc = SourceLocation(); 4384 } 4385 } else { 4386 // Check for any unexpanded parameter packs. 4387 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 4388 return true; 4389 4390 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4391 return true; 4392 } 4393 4394 // Check for direct and virtual base classes. 4395 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 4396 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 4397 if (!Dependent) { 4398 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 4399 BaseType)) 4400 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 4401 4402 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 4403 VirtualBaseSpec); 4404 4405 // C++ [base.class.init]p2: 4406 // Unless the mem-initializer-id names a nonstatic data member of the 4407 // constructor's class or a direct or virtual base of that class, the 4408 // mem-initializer is ill-formed. 4409 if (!DirectBaseSpec && !VirtualBaseSpec) { 4410 // If the class has any dependent bases, then it's possible that 4411 // one of those types will resolve to the same type as 4412 // BaseType. Therefore, just treat this as a dependent base 4413 // class initialization. FIXME: Should we try to check the 4414 // initialization anyway? It seems odd. 4415 if (ClassDecl->hasAnyDependentBases()) 4416 Dependent = true; 4417 else 4418 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 4419 << BaseType << Context.getTypeDeclType(ClassDecl) 4420 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4421 } 4422 } 4423 4424 if (Dependent) { 4425 DiscardCleanupsInEvaluationContext(); 4426 4427 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4428 /*IsVirtual=*/false, 4429 InitRange.getBegin(), Init, 4430 InitRange.getEnd(), EllipsisLoc); 4431 } 4432 4433 // C++ [base.class.init]p2: 4434 // If a mem-initializer-id is ambiguous because it designates both 4435 // a direct non-virtual base class and an inherited virtual base 4436 // class, the mem-initializer is ill-formed. 4437 if (DirectBaseSpec && VirtualBaseSpec) 4438 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 4439 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4440 4441 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 4442 if (!BaseSpec) 4443 BaseSpec = VirtualBaseSpec; 4444 4445 // Initialize the base. 4446 bool InitList = true; 4447 MultiExprArg Args = Init; 4448 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4449 InitList = false; 4450 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4451 } 4452 4453 InitializedEntity BaseEntity = 4454 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 4455 InitializationKind Kind = 4456 InitList ? InitializationKind::CreateDirectList(BaseLoc) 4457 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 4458 InitRange.getEnd()); 4459 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 4460 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 4461 if (BaseInit.isInvalid()) 4462 return true; 4463 4464 // C++11 [class.base.init]p7: 4465 // The initialization of each base and member constitutes a 4466 // full-expression. 4467 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(), 4468 /*DiscardedValue*/ false); 4469 if (BaseInit.isInvalid()) 4470 return true; 4471 4472 // If we are in a dependent context, template instantiation will 4473 // perform this type-checking again. Just save the arguments that we 4474 // received in a ParenListExpr. 4475 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4476 // of the information that we have about the base 4477 // initializer. However, deconstructing the ASTs is a dicey process, 4478 // and this approach is far more likely to get the corner cases right. 4479 if (CurContext->isDependentContext()) 4480 BaseInit = Init; 4481 4482 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4483 BaseSpec->isVirtual(), 4484 InitRange.getBegin(), 4485 BaseInit.getAs<Expr>(), 4486 InitRange.getEnd(), EllipsisLoc); 4487 } 4488 4489 // Create a static_cast\<T&&>(expr). 4490 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 4491 if (T.isNull()) T = E->getType(); 4492 QualType TargetType = SemaRef.BuildReferenceType( 4493 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 4494 SourceLocation ExprLoc = E->getBeginLoc(); 4495 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 4496 TargetType, ExprLoc); 4497 4498 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 4499 SourceRange(ExprLoc, ExprLoc), 4500 E->getSourceRange()).get(); 4501 } 4502 4503 /// ImplicitInitializerKind - How an implicit base or member initializer should 4504 /// initialize its base or member. 4505 enum ImplicitInitializerKind { 4506 IIK_Default, 4507 IIK_Copy, 4508 IIK_Move, 4509 IIK_Inherit 4510 }; 4511 4512 static bool 4513 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4514 ImplicitInitializerKind ImplicitInitKind, 4515 CXXBaseSpecifier *BaseSpec, 4516 bool IsInheritedVirtualBase, 4517 CXXCtorInitializer *&CXXBaseInit) { 4518 InitializedEntity InitEntity 4519 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 4520 IsInheritedVirtualBase); 4521 4522 ExprResult BaseInit; 4523 4524 switch (ImplicitInitKind) { 4525 case IIK_Inherit: 4526 case IIK_Default: { 4527 InitializationKind InitKind 4528 = InitializationKind::CreateDefault(Constructor->getLocation()); 4529 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4530 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4531 break; 4532 } 4533 4534 case IIK_Move: 4535 case IIK_Copy: { 4536 bool Moving = ImplicitInitKind == IIK_Move; 4537 ParmVarDecl *Param = Constructor->getParamDecl(0); 4538 QualType ParamType = Param->getType().getNonReferenceType(); 4539 4540 Expr *CopyCtorArg = 4541 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4542 SourceLocation(), Param, false, 4543 Constructor->getLocation(), ParamType, 4544 VK_LValue, nullptr); 4545 4546 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 4547 4548 // Cast to the base class to avoid ambiguities. 4549 QualType ArgTy = 4550 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 4551 ParamType.getQualifiers()); 4552 4553 if (Moving) { 4554 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 4555 } 4556 4557 CXXCastPath BasePath; 4558 BasePath.push_back(BaseSpec); 4559 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 4560 CK_UncheckedDerivedToBase, 4561 Moving ? VK_XValue : VK_LValue, 4562 &BasePath).get(); 4563 4564 InitializationKind InitKind 4565 = InitializationKind::CreateDirect(Constructor->getLocation(), 4566 SourceLocation(), SourceLocation()); 4567 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 4568 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 4569 break; 4570 } 4571 } 4572 4573 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 4574 if (BaseInit.isInvalid()) 4575 return true; 4576 4577 CXXBaseInit = 4578 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4579 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 4580 SourceLocation()), 4581 BaseSpec->isVirtual(), 4582 SourceLocation(), 4583 BaseInit.getAs<Expr>(), 4584 SourceLocation(), 4585 SourceLocation()); 4586 4587 return false; 4588 } 4589 4590 static bool RefersToRValueRef(Expr *MemRef) { 4591 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 4592 return Referenced->getType()->isRValueReferenceType(); 4593 } 4594 4595 static bool 4596 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4597 ImplicitInitializerKind ImplicitInitKind, 4598 FieldDecl *Field, IndirectFieldDecl *Indirect, 4599 CXXCtorInitializer *&CXXMemberInit) { 4600 if (Field->isInvalidDecl()) 4601 return true; 4602 4603 SourceLocation Loc = Constructor->getLocation(); 4604 4605 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 4606 bool Moving = ImplicitInitKind == IIK_Move; 4607 ParmVarDecl *Param = Constructor->getParamDecl(0); 4608 QualType ParamType = Param->getType().getNonReferenceType(); 4609 4610 // Suppress copying zero-width bitfields. 4611 if (Field->isZeroLengthBitField(SemaRef.Context)) 4612 return false; 4613 4614 Expr *MemberExprBase = 4615 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4616 SourceLocation(), Param, false, 4617 Loc, ParamType, VK_LValue, nullptr); 4618 4619 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 4620 4621 if (Moving) { 4622 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 4623 } 4624 4625 // Build a reference to this field within the parameter. 4626 CXXScopeSpec SS; 4627 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 4628 Sema::LookupMemberName); 4629 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 4630 : cast<ValueDecl>(Field), AS_public); 4631 MemberLookup.resolveKind(); 4632 ExprResult CtorArg 4633 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 4634 ParamType, Loc, 4635 /*IsArrow=*/false, 4636 SS, 4637 /*TemplateKWLoc=*/SourceLocation(), 4638 /*FirstQualifierInScope=*/nullptr, 4639 MemberLookup, 4640 /*TemplateArgs=*/nullptr, 4641 /*S*/nullptr); 4642 if (CtorArg.isInvalid()) 4643 return true; 4644 4645 // C++11 [class.copy]p15: 4646 // - if a member m has rvalue reference type T&&, it is direct-initialized 4647 // with static_cast<T&&>(x.m); 4648 if (RefersToRValueRef(CtorArg.get())) { 4649 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 4650 } 4651 4652 InitializedEntity Entity = 4653 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4654 /*Implicit*/ true) 4655 : InitializedEntity::InitializeMember(Field, nullptr, 4656 /*Implicit*/ true); 4657 4658 // Direct-initialize to use the copy constructor. 4659 InitializationKind InitKind = 4660 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 4661 4662 Expr *CtorArgE = CtorArg.getAs<Expr>(); 4663 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE); 4664 ExprResult MemberInit = 4665 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1)); 4666 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4667 if (MemberInit.isInvalid()) 4668 return true; 4669 4670 if (Indirect) 4671 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4672 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4673 else 4674 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4675 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4676 return false; 4677 } 4678 4679 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 4680 "Unhandled implicit init kind!"); 4681 4682 QualType FieldBaseElementType = 4683 SemaRef.Context.getBaseElementType(Field->getType()); 4684 4685 if (FieldBaseElementType->isRecordType()) { 4686 InitializedEntity InitEntity = 4687 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4688 /*Implicit*/ true) 4689 : InitializedEntity::InitializeMember(Field, nullptr, 4690 /*Implicit*/ true); 4691 InitializationKind InitKind = 4692 InitializationKind::CreateDefault(Loc); 4693 4694 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4695 ExprResult MemberInit = 4696 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4697 4698 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4699 if (MemberInit.isInvalid()) 4700 return true; 4701 4702 if (Indirect) 4703 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4704 Indirect, Loc, 4705 Loc, 4706 MemberInit.get(), 4707 Loc); 4708 else 4709 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4710 Field, Loc, Loc, 4711 MemberInit.get(), 4712 Loc); 4713 return false; 4714 } 4715 4716 if (!Field->getParent()->isUnion()) { 4717 if (FieldBaseElementType->isReferenceType()) { 4718 SemaRef.Diag(Constructor->getLocation(), 4719 diag::err_uninitialized_member_in_ctor) 4720 << (int)Constructor->isImplicit() 4721 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4722 << 0 << Field->getDeclName(); 4723 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4724 return true; 4725 } 4726 4727 if (FieldBaseElementType.isConstQualified()) { 4728 SemaRef.Diag(Constructor->getLocation(), 4729 diag::err_uninitialized_member_in_ctor) 4730 << (int)Constructor->isImplicit() 4731 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4732 << 1 << Field->getDeclName(); 4733 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4734 return true; 4735 } 4736 } 4737 4738 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) { 4739 // ARC and Weak: 4740 // Default-initialize Objective-C pointers to NULL. 4741 CXXMemberInit 4742 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 4743 Loc, Loc, 4744 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 4745 Loc); 4746 return false; 4747 } 4748 4749 // Nothing to initialize. 4750 CXXMemberInit = nullptr; 4751 return false; 4752 } 4753 4754 namespace { 4755 struct BaseAndFieldInfo { 4756 Sema &S; 4757 CXXConstructorDecl *Ctor; 4758 bool AnyErrorsInInits; 4759 ImplicitInitializerKind IIK; 4760 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 4761 SmallVector<CXXCtorInitializer*, 8> AllToInit; 4762 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 4763 4764 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 4765 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 4766 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 4767 if (Ctor->getInheritedConstructor()) 4768 IIK = IIK_Inherit; 4769 else if (Generated && Ctor->isCopyConstructor()) 4770 IIK = IIK_Copy; 4771 else if (Generated && Ctor->isMoveConstructor()) 4772 IIK = IIK_Move; 4773 else 4774 IIK = IIK_Default; 4775 } 4776 4777 bool isImplicitCopyOrMove() const { 4778 switch (IIK) { 4779 case IIK_Copy: 4780 case IIK_Move: 4781 return true; 4782 4783 case IIK_Default: 4784 case IIK_Inherit: 4785 return false; 4786 } 4787 4788 llvm_unreachable("Invalid ImplicitInitializerKind!"); 4789 } 4790 4791 bool addFieldInitializer(CXXCtorInitializer *Init) { 4792 AllToInit.push_back(Init); 4793 4794 // Check whether this initializer makes the field "used". 4795 if (Init->getInit()->HasSideEffects(S.Context)) 4796 S.UnusedPrivateFields.remove(Init->getAnyMember()); 4797 4798 return false; 4799 } 4800 4801 bool isInactiveUnionMember(FieldDecl *Field) { 4802 RecordDecl *Record = Field->getParent(); 4803 if (!Record->isUnion()) 4804 return false; 4805 4806 if (FieldDecl *Active = 4807 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 4808 return Active != Field->getCanonicalDecl(); 4809 4810 // In an implicit copy or move constructor, ignore any in-class initializer. 4811 if (isImplicitCopyOrMove()) 4812 return true; 4813 4814 // If there's no explicit initialization, the field is active only if it 4815 // has an in-class initializer... 4816 if (Field->hasInClassInitializer()) 4817 return false; 4818 // ... or it's an anonymous struct or union whose class has an in-class 4819 // initializer. 4820 if (!Field->isAnonymousStructOrUnion()) 4821 return true; 4822 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 4823 return !FieldRD->hasInClassInitializer(); 4824 } 4825 4826 /// Determine whether the given field is, or is within, a union member 4827 /// that is inactive (because there was an initializer given for a different 4828 /// member of the union, or because the union was not initialized at all). 4829 bool isWithinInactiveUnionMember(FieldDecl *Field, 4830 IndirectFieldDecl *Indirect) { 4831 if (!Indirect) 4832 return isInactiveUnionMember(Field); 4833 4834 for (auto *C : Indirect->chain()) { 4835 FieldDecl *Field = dyn_cast<FieldDecl>(C); 4836 if (Field && isInactiveUnionMember(Field)) 4837 return true; 4838 } 4839 return false; 4840 } 4841 }; 4842 } 4843 4844 /// Determine whether the given type is an incomplete or zero-lenfgth 4845 /// array type. 4846 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 4847 if (T->isIncompleteArrayType()) 4848 return true; 4849 4850 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 4851 if (!ArrayT->getSize()) 4852 return true; 4853 4854 T = ArrayT->getElementType(); 4855 } 4856 4857 return false; 4858 } 4859 4860 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 4861 FieldDecl *Field, 4862 IndirectFieldDecl *Indirect = nullptr) { 4863 if (Field->isInvalidDecl()) 4864 return false; 4865 4866 // Overwhelmingly common case: we have a direct initializer for this field. 4867 if (CXXCtorInitializer *Init = 4868 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 4869 return Info.addFieldInitializer(Init); 4870 4871 // C++11 [class.base.init]p8: 4872 // if the entity is a non-static data member that has a 4873 // brace-or-equal-initializer and either 4874 // -- the constructor's class is a union and no other variant member of that 4875 // union is designated by a mem-initializer-id or 4876 // -- the constructor's class is not a union, and, if the entity is a member 4877 // of an anonymous union, no other member of that union is designated by 4878 // a mem-initializer-id, 4879 // the entity is initialized as specified in [dcl.init]. 4880 // 4881 // We also apply the same rules to handle anonymous structs within anonymous 4882 // unions. 4883 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 4884 return false; 4885 4886 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 4887 ExprResult DIE = 4888 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); 4889 if (DIE.isInvalid()) 4890 return true; 4891 4892 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true); 4893 SemaRef.checkInitializerLifetime(Entity, DIE.get()); 4894 4895 CXXCtorInitializer *Init; 4896 if (Indirect) 4897 Init = new (SemaRef.Context) 4898 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), 4899 SourceLocation(), DIE.get(), SourceLocation()); 4900 else 4901 Init = new (SemaRef.Context) 4902 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), 4903 SourceLocation(), DIE.get(), SourceLocation()); 4904 return Info.addFieldInitializer(Init); 4905 } 4906 4907 // Don't initialize incomplete or zero-length arrays. 4908 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 4909 return false; 4910 4911 // Don't try to build an implicit initializer if there were semantic 4912 // errors in any of the initializers (and therefore we might be 4913 // missing some that the user actually wrote). 4914 if (Info.AnyErrorsInInits) 4915 return false; 4916 4917 CXXCtorInitializer *Init = nullptr; 4918 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 4919 Indirect, Init)) 4920 return true; 4921 4922 if (!Init) 4923 return false; 4924 4925 return Info.addFieldInitializer(Init); 4926 } 4927 4928 bool 4929 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 4930 CXXCtorInitializer *Initializer) { 4931 assert(Initializer->isDelegatingInitializer()); 4932 Constructor->setNumCtorInitializers(1); 4933 CXXCtorInitializer **initializer = 4934 new (Context) CXXCtorInitializer*[1]; 4935 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 4936 Constructor->setCtorInitializers(initializer); 4937 4938 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 4939 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 4940 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 4941 } 4942 4943 DelegatingCtorDecls.push_back(Constructor); 4944 4945 DiagnoseUninitializedFields(*this, Constructor); 4946 4947 return false; 4948 } 4949 4950 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 4951 ArrayRef<CXXCtorInitializer *> Initializers) { 4952 if (Constructor->isDependentContext()) { 4953 // Just store the initializers as written, they will be checked during 4954 // instantiation. 4955 if (!Initializers.empty()) { 4956 Constructor->setNumCtorInitializers(Initializers.size()); 4957 CXXCtorInitializer **baseOrMemberInitializers = 4958 new (Context) CXXCtorInitializer*[Initializers.size()]; 4959 memcpy(baseOrMemberInitializers, Initializers.data(), 4960 Initializers.size() * sizeof(CXXCtorInitializer*)); 4961 Constructor->setCtorInitializers(baseOrMemberInitializers); 4962 } 4963 4964 // Let template instantiation know whether we had errors. 4965 if (AnyErrors) 4966 Constructor->setInvalidDecl(); 4967 4968 return false; 4969 } 4970 4971 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 4972 4973 // We need to build the initializer AST according to order of construction 4974 // and not what user specified in the Initializers list. 4975 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 4976 if (!ClassDecl) 4977 return true; 4978 4979 bool HadError = false; 4980 4981 for (unsigned i = 0; i < Initializers.size(); i++) { 4982 CXXCtorInitializer *Member = Initializers[i]; 4983 4984 if (Member->isBaseInitializer()) 4985 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 4986 else { 4987 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 4988 4989 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 4990 for (auto *C : F->chain()) { 4991 FieldDecl *FD = dyn_cast<FieldDecl>(C); 4992 if (FD && FD->getParent()->isUnion()) 4993 Info.ActiveUnionMember.insert(std::make_pair( 4994 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 4995 } 4996 } else if (FieldDecl *FD = Member->getMember()) { 4997 if (FD->getParent()->isUnion()) 4998 Info.ActiveUnionMember.insert(std::make_pair( 4999 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 5000 } 5001 } 5002 } 5003 5004 // Keep track of the direct virtual bases. 5005 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 5006 for (auto &I : ClassDecl->bases()) { 5007 if (I.isVirtual()) 5008 DirectVBases.insert(&I); 5009 } 5010 5011 // Push virtual bases before others. 5012 for (auto &VBase : ClassDecl->vbases()) { 5013 if (CXXCtorInitializer *Value 5014 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 5015 // [class.base.init]p7, per DR257: 5016 // A mem-initializer where the mem-initializer-id names a virtual base 5017 // class is ignored during execution of a constructor of any class that 5018 // is not the most derived class. 5019 if (ClassDecl->isAbstract()) { 5020 // FIXME: Provide a fixit to remove the base specifier. This requires 5021 // tracking the location of the associated comma for a base specifier. 5022 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 5023 << VBase.getType() << ClassDecl; 5024 DiagnoseAbstractType(ClassDecl); 5025 } 5026 5027 Info.AllToInit.push_back(Value); 5028 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 5029 // [class.base.init]p8, per DR257: 5030 // If a given [...] base class is not named by a mem-initializer-id 5031 // [...] and the entity is not a virtual base class of an abstract 5032 // class, then [...] the entity is default-initialized. 5033 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 5034 CXXCtorInitializer *CXXBaseInit; 5035 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 5036 &VBase, IsInheritedVirtualBase, 5037 CXXBaseInit)) { 5038 HadError = true; 5039 continue; 5040 } 5041 5042 Info.AllToInit.push_back(CXXBaseInit); 5043 } 5044 } 5045 5046 // Non-virtual bases. 5047 for (auto &Base : ClassDecl->bases()) { 5048 // Virtuals are in the virtual base list and already constructed. 5049 if (Base.isVirtual()) 5050 continue; 5051 5052 if (CXXCtorInitializer *Value 5053 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 5054 Info.AllToInit.push_back(Value); 5055 } else if (!AnyErrors) { 5056 CXXCtorInitializer *CXXBaseInit; 5057 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 5058 &Base, /*IsInheritedVirtualBase=*/false, 5059 CXXBaseInit)) { 5060 HadError = true; 5061 continue; 5062 } 5063 5064 Info.AllToInit.push_back(CXXBaseInit); 5065 } 5066 } 5067 5068 // Fields. 5069 for (auto *Mem : ClassDecl->decls()) { 5070 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 5071 // C++ [class.bit]p2: 5072 // A declaration for a bit-field that omits the identifier declares an 5073 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 5074 // initialized. 5075 if (F->isUnnamedBitfield()) 5076 continue; 5077 5078 // If we're not generating the implicit copy/move constructor, then we'll 5079 // handle anonymous struct/union fields based on their individual 5080 // indirect fields. 5081 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 5082 continue; 5083 5084 if (CollectFieldInitializer(*this, Info, F)) 5085 HadError = true; 5086 continue; 5087 } 5088 5089 // Beyond this point, we only consider default initialization. 5090 if (Info.isImplicitCopyOrMove()) 5091 continue; 5092 5093 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 5094 if (F->getType()->isIncompleteArrayType()) { 5095 assert(ClassDecl->hasFlexibleArrayMember() && 5096 "Incomplete array type is not valid"); 5097 continue; 5098 } 5099 5100 // Initialize each field of an anonymous struct individually. 5101 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 5102 HadError = true; 5103 5104 continue; 5105 } 5106 } 5107 5108 unsigned NumInitializers = Info.AllToInit.size(); 5109 if (NumInitializers > 0) { 5110 Constructor->setNumCtorInitializers(NumInitializers); 5111 CXXCtorInitializer **baseOrMemberInitializers = 5112 new (Context) CXXCtorInitializer*[NumInitializers]; 5113 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 5114 NumInitializers * sizeof(CXXCtorInitializer*)); 5115 Constructor->setCtorInitializers(baseOrMemberInitializers); 5116 5117 // Constructors implicitly reference the base and member 5118 // destructors. 5119 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 5120 Constructor->getParent()); 5121 } 5122 5123 return HadError; 5124 } 5125 5126 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 5127 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 5128 const RecordDecl *RD = RT->getDecl(); 5129 if (RD->isAnonymousStructOrUnion()) { 5130 for (auto *Field : RD->fields()) 5131 PopulateKeysForFields(Field, IdealInits); 5132 return; 5133 } 5134 } 5135 IdealInits.push_back(Field->getCanonicalDecl()); 5136 } 5137 5138 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 5139 return Context.getCanonicalType(BaseType).getTypePtr(); 5140 } 5141 5142 static const void *GetKeyForMember(ASTContext &Context, 5143 CXXCtorInitializer *Member) { 5144 if (!Member->isAnyMemberInitializer()) 5145 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 5146 5147 return Member->getAnyMember()->getCanonicalDecl(); 5148 } 5149 5150 static void DiagnoseBaseOrMemInitializerOrder( 5151 Sema &SemaRef, const CXXConstructorDecl *Constructor, 5152 ArrayRef<CXXCtorInitializer *> Inits) { 5153 if (Constructor->getDeclContext()->isDependentContext()) 5154 return; 5155 5156 // Don't check initializers order unless the warning is enabled at the 5157 // location of at least one initializer. 5158 bool ShouldCheckOrder = false; 5159 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 5160 CXXCtorInitializer *Init = Inits[InitIndex]; 5161 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 5162 Init->getSourceLocation())) { 5163 ShouldCheckOrder = true; 5164 break; 5165 } 5166 } 5167 if (!ShouldCheckOrder) 5168 return; 5169 5170 // Build the list of bases and members in the order that they'll 5171 // actually be initialized. The explicit initializers should be in 5172 // this same order but may be missing things. 5173 SmallVector<const void*, 32> IdealInitKeys; 5174 5175 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 5176 5177 // 1. Virtual bases. 5178 for (const auto &VBase : ClassDecl->vbases()) 5179 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 5180 5181 // 2. Non-virtual bases. 5182 for (const auto &Base : ClassDecl->bases()) { 5183 if (Base.isVirtual()) 5184 continue; 5185 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 5186 } 5187 5188 // 3. Direct fields. 5189 for (auto *Field : ClassDecl->fields()) { 5190 if (Field->isUnnamedBitfield()) 5191 continue; 5192 5193 PopulateKeysForFields(Field, IdealInitKeys); 5194 } 5195 5196 unsigned NumIdealInits = IdealInitKeys.size(); 5197 unsigned IdealIndex = 0; 5198 5199 CXXCtorInitializer *PrevInit = nullptr; 5200 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 5201 CXXCtorInitializer *Init = Inits[InitIndex]; 5202 const void *InitKey = GetKeyForMember(SemaRef.Context, Init); 5203 5204 // Scan forward to try to find this initializer in the idealized 5205 // initializers list. 5206 for (; IdealIndex != NumIdealInits; ++IdealIndex) 5207 if (InitKey == IdealInitKeys[IdealIndex]) 5208 break; 5209 5210 // If we didn't find this initializer, it must be because we 5211 // scanned past it on a previous iteration. That can only 5212 // happen if we're out of order; emit a warning. 5213 if (IdealIndex == NumIdealInits && PrevInit) { 5214 Sema::SemaDiagnosticBuilder D = 5215 SemaRef.Diag(PrevInit->getSourceLocation(), 5216 diag::warn_initializer_out_of_order); 5217 5218 if (PrevInit->isAnyMemberInitializer()) 5219 D << 0 << PrevInit->getAnyMember()->getDeclName(); 5220 else 5221 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 5222 5223 if (Init->isAnyMemberInitializer()) 5224 D << 0 << Init->getAnyMember()->getDeclName(); 5225 else 5226 D << 1 << Init->getTypeSourceInfo()->getType(); 5227 5228 // Move back to the initializer's location in the ideal list. 5229 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 5230 if (InitKey == IdealInitKeys[IdealIndex]) 5231 break; 5232 5233 assert(IdealIndex < NumIdealInits && 5234 "initializer not found in initializer list"); 5235 } 5236 5237 PrevInit = Init; 5238 } 5239 } 5240 5241 namespace { 5242 bool CheckRedundantInit(Sema &S, 5243 CXXCtorInitializer *Init, 5244 CXXCtorInitializer *&PrevInit) { 5245 if (!PrevInit) { 5246 PrevInit = Init; 5247 return false; 5248 } 5249 5250 if (FieldDecl *Field = Init->getAnyMember()) 5251 S.Diag(Init->getSourceLocation(), 5252 diag::err_multiple_mem_initialization) 5253 << Field->getDeclName() 5254 << Init->getSourceRange(); 5255 else { 5256 const Type *BaseClass = Init->getBaseClass(); 5257 assert(BaseClass && "neither field nor base"); 5258 S.Diag(Init->getSourceLocation(), 5259 diag::err_multiple_base_initialization) 5260 << QualType(BaseClass, 0) 5261 << Init->getSourceRange(); 5262 } 5263 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 5264 << 0 << PrevInit->getSourceRange(); 5265 5266 return true; 5267 } 5268 5269 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 5270 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 5271 5272 bool CheckRedundantUnionInit(Sema &S, 5273 CXXCtorInitializer *Init, 5274 RedundantUnionMap &Unions) { 5275 FieldDecl *Field = Init->getAnyMember(); 5276 RecordDecl *Parent = Field->getParent(); 5277 NamedDecl *Child = Field; 5278 5279 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 5280 if (Parent->isUnion()) { 5281 UnionEntry &En = Unions[Parent]; 5282 if (En.first && En.first != Child) { 5283 S.Diag(Init->getSourceLocation(), 5284 diag::err_multiple_mem_union_initialization) 5285 << Field->getDeclName() 5286 << Init->getSourceRange(); 5287 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 5288 << 0 << En.second->getSourceRange(); 5289 return true; 5290 } 5291 if (!En.first) { 5292 En.first = Child; 5293 En.second = Init; 5294 } 5295 if (!Parent->isAnonymousStructOrUnion()) 5296 return false; 5297 } 5298 5299 Child = Parent; 5300 Parent = cast<RecordDecl>(Parent->getDeclContext()); 5301 } 5302 5303 return false; 5304 } 5305 } 5306 5307 /// ActOnMemInitializers - Handle the member initializers for a constructor. 5308 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 5309 SourceLocation ColonLoc, 5310 ArrayRef<CXXCtorInitializer*> MemInits, 5311 bool AnyErrors) { 5312 if (!ConstructorDecl) 5313 return; 5314 5315 AdjustDeclIfTemplate(ConstructorDecl); 5316 5317 CXXConstructorDecl *Constructor 5318 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 5319 5320 if (!Constructor) { 5321 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 5322 return; 5323 } 5324 5325 // Mapping for the duplicate initializers check. 5326 // For member initializers, this is keyed with a FieldDecl*. 5327 // For base initializers, this is keyed with a Type*. 5328 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 5329 5330 // Mapping for the inconsistent anonymous-union initializers check. 5331 RedundantUnionMap MemberUnions; 5332 5333 bool HadError = false; 5334 for (unsigned i = 0; i < MemInits.size(); i++) { 5335 CXXCtorInitializer *Init = MemInits[i]; 5336 5337 // Set the source order index. 5338 Init->setSourceOrder(i); 5339 5340 if (Init->isAnyMemberInitializer()) { 5341 const void *Key = GetKeyForMember(Context, Init); 5342 if (CheckRedundantInit(*this, Init, Members[Key]) || 5343 CheckRedundantUnionInit(*this, Init, MemberUnions)) 5344 HadError = true; 5345 } else if (Init->isBaseInitializer()) { 5346 const void *Key = GetKeyForMember(Context, Init); 5347 if (CheckRedundantInit(*this, Init, Members[Key])) 5348 HadError = true; 5349 } else { 5350 assert(Init->isDelegatingInitializer()); 5351 // This must be the only initializer 5352 if (MemInits.size() != 1) { 5353 Diag(Init->getSourceLocation(), 5354 diag::err_delegating_initializer_alone) 5355 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 5356 // We will treat this as being the only initializer. 5357 } 5358 SetDelegatingInitializer(Constructor, MemInits[i]); 5359 // Return immediately as the initializer is set. 5360 return; 5361 } 5362 } 5363 5364 if (HadError) 5365 return; 5366 5367 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 5368 5369 SetCtorInitializers(Constructor, AnyErrors, MemInits); 5370 5371 DiagnoseUninitializedFields(*this, Constructor); 5372 } 5373 5374 void 5375 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 5376 CXXRecordDecl *ClassDecl) { 5377 // Ignore dependent contexts. Also ignore unions, since their members never 5378 // have destructors implicitly called. 5379 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 5380 return; 5381 5382 // FIXME: all the access-control diagnostics are positioned on the 5383 // field/base declaration. That's probably good; that said, the 5384 // user might reasonably want to know why the destructor is being 5385 // emitted, and we currently don't say. 5386 5387 // Non-static data members. 5388 for (auto *Field : ClassDecl->fields()) { 5389 if (Field->isInvalidDecl()) 5390 continue; 5391 5392 // Don't destroy incomplete or zero-length arrays. 5393 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 5394 continue; 5395 5396 QualType FieldType = Context.getBaseElementType(Field->getType()); 5397 5398 const RecordType* RT = FieldType->getAs<RecordType>(); 5399 if (!RT) 5400 continue; 5401 5402 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5403 if (FieldClassDecl->isInvalidDecl()) 5404 continue; 5405 if (FieldClassDecl->hasIrrelevantDestructor()) 5406 continue; 5407 // The destructor for an implicit anonymous union member is never invoked. 5408 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 5409 continue; 5410 5411 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 5412 assert(Dtor && "No dtor found for FieldClassDecl!"); 5413 CheckDestructorAccess(Field->getLocation(), Dtor, 5414 PDiag(diag::err_access_dtor_field) 5415 << Field->getDeclName() 5416 << FieldType); 5417 5418 MarkFunctionReferenced(Location, Dtor); 5419 DiagnoseUseOfDecl(Dtor, Location); 5420 } 5421 5422 // We only potentially invoke the destructors of potentially constructed 5423 // subobjects. 5424 bool VisitVirtualBases = !ClassDecl->isAbstract(); 5425 5426 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 5427 5428 // Bases. 5429 for (const auto &Base : ClassDecl->bases()) { 5430 // Bases are always records in a well-formed non-dependent class. 5431 const RecordType *RT = Base.getType()->getAs<RecordType>(); 5432 5433 // Remember direct virtual bases. 5434 if (Base.isVirtual()) { 5435 if (!VisitVirtualBases) 5436 continue; 5437 DirectVirtualBases.insert(RT); 5438 } 5439 5440 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5441 // If our base class is invalid, we probably can't get its dtor anyway. 5442 if (BaseClassDecl->isInvalidDecl()) 5443 continue; 5444 if (BaseClassDecl->hasIrrelevantDestructor()) 5445 continue; 5446 5447 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5448 assert(Dtor && "No dtor found for BaseClassDecl!"); 5449 5450 // FIXME: caret should be on the start of the class name 5451 CheckDestructorAccess(Base.getBeginLoc(), Dtor, 5452 PDiag(diag::err_access_dtor_base) 5453 << Base.getType() << Base.getSourceRange(), 5454 Context.getTypeDeclType(ClassDecl)); 5455 5456 MarkFunctionReferenced(Location, Dtor); 5457 DiagnoseUseOfDecl(Dtor, Location); 5458 } 5459 5460 if (!VisitVirtualBases) 5461 return; 5462 5463 // Virtual bases. 5464 for (const auto &VBase : ClassDecl->vbases()) { 5465 // Bases are always records in a well-formed non-dependent class. 5466 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 5467 5468 // Ignore direct virtual bases. 5469 if (DirectVirtualBases.count(RT)) 5470 continue; 5471 5472 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5473 // If our base class is invalid, we probably can't get its dtor anyway. 5474 if (BaseClassDecl->isInvalidDecl()) 5475 continue; 5476 if (BaseClassDecl->hasIrrelevantDestructor()) 5477 continue; 5478 5479 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5480 assert(Dtor && "No dtor found for BaseClassDecl!"); 5481 if (CheckDestructorAccess( 5482 ClassDecl->getLocation(), Dtor, 5483 PDiag(diag::err_access_dtor_vbase) 5484 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 5485 Context.getTypeDeclType(ClassDecl)) == 5486 AR_accessible) { 5487 CheckDerivedToBaseConversion( 5488 Context.getTypeDeclType(ClassDecl), VBase.getType(), 5489 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 5490 SourceRange(), DeclarationName(), nullptr); 5491 } 5492 5493 MarkFunctionReferenced(Location, Dtor); 5494 DiagnoseUseOfDecl(Dtor, Location); 5495 } 5496 } 5497 5498 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 5499 if (!CDtorDecl) 5500 return; 5501 5502 if (CXXConstructorDecl *Constructor 5503 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 5504 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 5505 DiagnoseUninitializedFields(*this, Constructor); 5506 } 5507 } 5508 5509 bool Sema::isAbstractType(SourceLocation Loc, QualType T) { 5510 if (!getLangOpts().CPlusPlus) 5511 return false; 5512 5513 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl(); 5514 if (!RD) 5515 return false; 5516 5517 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a 5518 // class template specialization here, but doing so breaks a lot of code. 5519 5520 // We can't answer whether something is abstract until it has a 5521 // definition. If it's currently being defined, we'll walk back 5522 // over all the declarations when we have a full definition. 5523 const CXXRecordDecl *Def = RD->getDefinition(); 5524 if (!Def || Def->isBeingDefined()) 5525 return false; 5526 5527 return RD->isAbstract(); 5528 } 5529 5530 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 5531 TypeDiagnoser &Diagnoser) { 5532 if (!isAbstractType(Loc, T)) 5533 return false; 5534 5535 T = Context.getBaseElementType(T); 5536 Diagnoser.diagnose(*this, Loc, T); 5537 DiagnoseAbstractType(T->getAsCXXRecordDecl()); 5538 return true; 5539 } 5540 5541 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 5542 // Check if we've already emitted the list of pure virtual functions 5543 // for this class. 5544 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 5545 return; 5546 5547 // If the diagnostic is suppressed, don't emit the notes. We're only 5548 // going to emit them once, so try to attach them to a diagnostic we're 5549 // actually going to show. 5550 if (Diags.isLastDiagnosticIgnored()) 5551 return; 5552 5553 CXXFinalOverriderMap FinalOverriders; 5554 RD->getFinalOverriders(FinalOverriders); 5555 5556 // Keep a set of seen pure methods so we won't diagnose the same method 5557 // more than once. 5558 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 5559 5560 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 5561 MEnd = FinalOverriders.end(); 5562 M != MEnd; 5563 ++M) { 5564 for (OverridingMethods::iterator SO = M->second.begin(), 5565 SOEnd = M->second.end(); 5566 SO != SOEnd; ++SO) { 5567 // C++ [class.abstract]p4: 5568 // A class is abstract if it contains or inherits at least one 5569 // pure virtual function for which the final overrider is pure 5570 // virtual. 5571 5572 // 5573 if (SO->second.size() != 1) 5574 continue; 5575 5576 if (!SO->second.front().Method->isPure()) 5577 continue; 5578 5579 if (!SeenPureMethods.insert(SO->second.front().Method).second) 5580 continue; 5581 5582 Diag(SO->second.front().Method->getLocation(), 5583 diag::note_pure_virtual_function) 5584 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 5585 } 5586 } 5587 5588 if (!PureVirtualClassDiagSet) 5589 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 5590 PureVirtualClassDiagSet->insert(RD); 5591 } 5592 5593 namespace { 5594 struct AbstractUsageInfo { 5595 Sema &S; 5596 CXXRecordDecl *Record; 5597 CanQualType AbstractType; 5598 bool Invalid; 5599 5600 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 5601 : S(S), Record(Record), 5602 AbstractType(S.Context.getCanonicalType( 5603 S.Context.getTypeDeclType(Record))), 5604 Invalid(false) {} 5605 5606 void DiagnoseAbstractType() { 5607 if (Invalid) return; 5608 S.DiagnoseAbstractType(Record); 5609 Invalid = true; 5610 } 5611 5612 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 5613 }; 5614 5615 struct CheckAbstractUsage { 5616 AbstractUsageInfo &Info; 5617 const NamedDecl *Ctx; 5618 5619 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 5620 : Info(Info), Ctx(Ctx) {} 5621 5622 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5623 switch (TL.getTypeLocClass()) { 5624 #define ABSTRACT_TYPELOC(CLASS, PARENT) 5625 #define TYPELOC(CLASS, PARENT) \ 5626 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 5627 #include "clang/AST/TypeLocNodes.def" 5628 } 5629 } 5630 5631 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5632 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 5633 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 5634 if (!TL.getParam(I)) 5635 continue; 5636 5637 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 5638 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 5639 } 5640 } 5641 5642 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5643 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 5644 } 5645 5646 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5647 // Visit the type parameters from a permissive context. 5648 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 5649 TemplateArgumentLoc TAL = TL.getArgLoc(I); 5650 if (TAL.getArgument().getKind() == TemplateArgument::Type) 5651 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 5652 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 5653 // TODO: other template argument types? 5654 } 5655 } 5656 5657 // Visit pointee types from a permissive context. 5658 #define CheckPolymorphic(Type) \ 5659 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 5660 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 5661 } 5662 CheckPolymorphic(PointerTypeLoc) 5663 CheckPolymorphic(ReferenceTypeLoc) 5664 CheckPolymorphic(MemberPointerTypeLoc) 5665 CheckPolymorphic(BlockPointerTypeLoc) 5666 CheckPolymorphic(AtomicTypeLoc) 5667 5668 /// Handle all the types we haven't given a more specific 5669 /// implementation for above. 5670 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5671 // Every other kind of type that we haven't called out already 5672 // that has an inner type is either (1) sugar or (2) contains that 5673 // inner type in some way as a subobject. 5674 if (TypeLoc Next = TL.getNextTypeLoc()) 5675 return Visit(Next, Sel); 5676 5677 // If there's no inner type and we're in a permissive context, 5678 // don't diagnose. 5679 if (Sel == Sema::AbstractNone) return; 5680 5681 // Check whether the type matches the abstract type. 5682 QualType T = TL.getType(); 5683 if (T->isArrayType()) { 5684 Sel = Sema::AbstractArrayType; 5685 T = Info.S.Context.getBaseElementType(T); 5686 } 5687 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 5688 if (CT != Info.AbstractType) return; 5689 5690 // It matched; do some magic. 5691 if (Sel == Sema::AbstractArrayType) { 5692 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 5693 << T << TL.getSourceRange(); 5694 } else { 5695 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 5696 << Sel << T << TL.getSourceRange(); 5697 } 5698 Info.DiagnoseAbstractType(); 5699 } 5700 }; 5701 5702 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 5703 Sema::AbstractDiagSelID Sel) { 5704 CheckAbstractUsage(*this, D).Visit(TL, Sel); 5705 } 5706 5707 } 5708 5709 /// Check for invalid uses of an abstract type in a method declaration. 5710 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5711 CXXMethodDecl *MD) { 5712 // No need to do the check on definitions, which require that 5713 // the return/param types be complete. 5714 if (MD->doesThisDeclarationHaveABody()) 5715 return; 5716 5717 // For safety's sake, just ignore it if we don't have type source 5718 // information. This should never happen for non-implicit methods, 5719 // but... 5720 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 5721 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 5722 } 5723 5724 /// Check for invalid uses of an abstract type within a class definition. 5725 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5726 CXXRecordDecl *RD) { 5727 for (auto *D : RD->decls()) { 5728 if (D->isImplicit()) continue; 5729 5730 // Methods and method templates. 5731 if (isa<CXXMethodDecl>(D)) { 5732 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 5733 } else if (isa<FunctionTemplateDecl>(D)) { 5734 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 5735 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 5736 5737 // Fields and static variables. 5738 } else if (isa<FieldDecl>(D)) { 5739 FieldDecl *FD = cast<FieldDecl>(D); 5740 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 5741 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 5742 } else if (isa<VarDecl>(D)) { 5743 VarDecl *VD = cast<VarDecl>(D); 5744 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 5745 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 5746 5747 // Nested classes and class templates. 5748 } else if (isa<CXXRecordDecl>(D)) { 5749 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 5750 } else if (isa<ClassTemplateDecl>(D)) { 5751 CheckAbstractClassUsage(Info, 5752 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 5753 } 5754 } 5755 } 5756 5757 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) { 5758 Attr *ClassAttr = getDLLAttr(Class); 5759 if (!ClassAttr) 5760 return; 5761 5762 assert(ClassAttr->getKind() == attr::DLLExport); 5763 5764 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5765 5766 if (TSK == TSK_ExplicitInstantiationDeclaration) 5767 // Don't go any further if this is just an explicit instantiation 5768 // declaration. 5769 return; 5770 5771 if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) 5772 S.MarkVTableUsed(Class->getLocation(), Class, true); 5773 5774 for (Decl *Member : Class->decls()) { 5775 // Defined static variables that are members of an exported base 5776 // class must be marked export too. 5777 auto *VD = dyn_cast<VarDecl>(Member); 5778 if (VD && Member->getAttr<DLLExportAttr>() && 5779 VD->getStorageClass() == SC_Static && 5780 TSK == TSK_ImplicitInstantiation) 5781 S.MarkVariableReferenced(VD->getLocation(), VD); 5782 5783 auto *MD = dyn_cast<CXXMethodDecl>(Member); 5784 if (!MD) 5785 continue; 5786 5787 if (Member->getAttr<DLLExportAttr>()) { 5788 if (MD->isUserProvided()) { 5789 // Instantiate non-default class member functions ... 5790 5791 // .. except for certain kinds of template specializations. 5792 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 5793 continue; 5794 5795 S.MarkFunctionReferenced(Class->getLocation(), MD); 5796 5797 // The function will be passed to the consumer when its definition is 5798 // encountered. 5799 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() || 5800 MD->isCopyAssignmentOperator() || 5801 MD->isMoveAssignmentOperator()) { 5802 // Synthesize and instantiate non-trivial implicit methods, explicitly 5803 // defaulted methods, and the copy and move assignment operators. The 5804 // latter are exported even if they are trivial, because the address of 5805 // an operator can be taken and should compare equal across libraries. 5806 DiagnosticErrorTrap Trap(S.Diags); 5807 S.MarkFunctionReferenced(Class->getLocation(), MD); 5808 if (Trap.hasErrorOccurred()) { 5809 S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class) 5810 << Class << !S.getLangOpts().CPlusPlus11; 5811 break; 5812 } 5813 5814 // There is no later point when we will see the definition of this 5815 // function, so pass it to the consumer now. 5816 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 5817 } 5818 } 5819 } 5820 } 5821 5822 static void checkForMultipleExportedDefaultConstructors(Sema &S, 5823 CXXRecordDecl *Class) { 5824 // Only the MS ABI has default constructor closures, so we don't need to do 5825 // this semantic checking anywhere else. 5826 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft()) 5827 return; 5828 5829 CXXConstructorDecl *LastExportedDefaultCtor = nullptr; 5830 for (Decl *Member : Class->decls()) { 5831 // Look for exported default constructors. 5832 auto *CD = dyn_cast<CXXConstructorDecl>(Member); 5833 if (!CD || !CD->isDefaultConstructor()) 5834 continue; 5835 auto *Attr = CD->getAttr<DLLExportAttr>(); 5836 if (!Attr) 5837 continue; 5838 5839 // If the class is non-dependent, mark the default arguments as ODR-used so 5840 // that we can properly codegen the constructor closure. 5841 if (!Class->isDependentContext()) { 5842 for (ParmVarDecl *PD : CD->parameters()) { 5843 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD); 5844 S.DiscardCleanupsInEvaluationContext(); 5845 } 5846 } 5847 5848 if (LastExportedDefaultCtor) { 5849 S.Diag(LastExportedDefaultCtor->getLocation(), 5850 diag::err_attribute_dll_ambiguous_default_ctor) 5851 << Class; 5852 S.Diag(CD->getLocation(), diag::note_entity_declared_at) 5853 << CD->getDeclName(); 5854 return; 5855 } 5856 LastExportedDefaultCtor = CD; 5857 } 5858 } 5859 5860 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) { 5861 // Mark any compiler-generated routines with the implicit code_seg attribute. 5862 for (auto *Method : Class->methods()) { 5863 if (Method->isUserProvided()) 5864 continue; 5865 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true)) 5866 Method->addAttr(A); 5867 } 5868 } 5869 5870 /// Check class-level dllimport/dllexport attribute. 5871 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) { 5872 Attr *ClassAttr = getDLLAttr(Class); 5873 5874 // MSVC inherits DLL attributes to partial class template specializations. 5875 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) { 5876 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 5877 if (Attr *TemplateAttr = 5878 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 5879 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext())); 5880 A->setInherited(true); 5881 ClassAttr = A; 5882 } 5883 } 5884 } 5885 5886 if (!ClassAttr) 5887 return; 5888 5889 if (!Class->isExternallyVisible()) { 5890 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) 5891 << Class << ClassAttr; 5892 return; 5893 } 5894 5895 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 5896 !ClassAttr->isInherited()) { 5897 // Diagnose dll attributes on members of class with dll attribute. 5898 for (Decl *Member : Class->decls()) { 5899 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 5900 continue; 5901 InheritableAttr *MemberAttr = getDLLAttr(Member); 5902 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 5903 continue; 5904 5905 Diag(MemberAttr->getLocation(), 5906 diag::err_attribute_dll_member_of_dll_class) 5907 << MemberAttr << ClassAttr; 5908 Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 5909 Member->setInvalidDecl(); 5910 } 5911 } 5912 5913 if (Class->getDescribedClassTemplate()) 5914 // Don't inherit dll attribute until the template is instantiated. 5915 return; 5916 5917 // The class is either imported or exported. 5918 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 5919 5920 // Check if this was a dllimport attribute propagated from a derived class to 5921 // a base class template specialization. We don't apply these attributes to 5922 // static data members. 5923 const bool PropagatedImport = 5924 !ClassExported && 5925 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate(); 5926 5927 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5928 5929 // Ignore explicit dllexport on explicit class template instantiation 5930 // declarations, except in MinGW mode. 5931 if (ClassExported && !ClassAttr->isInherited() && 5932 TSK == TSK_ExplicitInstantiationDeclaration && 5933 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) { 5934 Class->dropAttr<DLLExportAttr>(); 5935 return; 5936 } 5937 5938 // Force declaration of implicit members so they can inherit the attribute. 5939 ForceDeclarationOfImplicitMembers(Class); 5940 5941 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 5942 // seem to be true in practice? 5943 5944 for (Decl *Member : Class->decls()) { 5945 VarDecl *VD = dyn_cast<VarDecl>(Member); 5946 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 5947 5948 // Only methods and static fields inherit the attributes. 5949 if (!VD && !MD) 5950 continue; 5951 5952 if (MD) { 5953 // Don't process deleted methods. 5954 if (MD->isDeleted()) 5955 continue; 5956 5957 if (MD->isInlined()) { 5958 // MinGW does not import or export inline methods. But do it for 5959 // template instantiations. 5960 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() && 5961 !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment() && 5962 TSK != TSK_ExplicitInstantiationDeclaration && 5963 TSK != TSK_ExplicitInstantiationDefinition) 5964 continue; 5965 5966 // MSVC versions before 2015 don't export the move assignment operators 5967 // and move constructor, so don't attempt to import/export them if 5968 // we have a definition. 5969 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD); 5970 if ((MD->isMoveAssignmentOperator() || 5971 (Ctor && Ctor->isMoveConstructor())) && 5972 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015)) 5973 continue; 5974 5975 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign 5976 // operator is exported anyway. 5977 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 5978 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial()) 5979 continue; 5980 } 5981 } 5982 5983 // Don't apply dllimport attributes to static data members of class template 5984 // instantiations when the attribute is propagated from a derived class. 5985 if (VD && PropagatedImport) 5986 continue; 5987 5988 if (!cast<NamedDecl>(Member)->isExternallyVisible()) 5989 continue; 5990 5991 if (!getDLLAttr(Member)) { 5992 InheritableAttr *NewAttr = nullptr; 5993 5994 // Do not export/import inline function when -fno-dllexport-inlines is 5995 // passed. But add attribute for later local static var check. 5996 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() && 5997 TSK != TSK_ExplicitInstantiationDeclaration && 5998 TSK != TSK_ExplicitInstantiationDefinition) { 5999 if (ClassExported) { 6000 NewAttr = ::new (getASTContext()) 6001 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr); 6002 } else { 6003 NewAttr = ::new (getASTContext()) 6004 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr); 6005 } 6006 } else { 6007 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6008 } 6009 6010 NewAttr->setInherited(true); 6011 Member->addAttr(NewAttr); 6012 6013 if (MD) { 6014 // Propagate DLLAttr to friend re-declarations of MD that have already 6015 // been constructed. 6016 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD; 6017 FD = FD->getPreviousDecl()) { 6018 if (FD->getFriendObjectKind() == Decl::FOK_None) 6019 continue; 6020 assert(!getDLLAttr(FD) && 6021 "friend re-decl should not already have a DLLAttr"); 6022 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6023 NewAttr->setInherited(true); 6024 FD->addAttr(NewAttr); 6025 } 6026 } 6027 } 6028 } 6029 6030 if (ClassExported) 6031 DelayedDllExportClasses.push_back(Class); 6032 } 6033 6034 /// Perform propagation of DLL attributes from a derived class to a 6035 /// templated base class for MS compatibility. 6036 void Sema::propagateDLLAttrToBaseClassTemplate( 6037 CXXRecordDecl *Class, Attr *ClassAttr, 6038 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 6039 if (getDLLAttr( 6040 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 6041 // If the base class template has a DLL attribute, don't try to change it. 6042 return; 6043 } 6044 6045 auto TSK = BaseTemplateSpec->getSpecializationKind(); 6046 if (!getDLLAttr(BaseTemplateSpec) && 6047 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration || 6048 TSK == TSK_ImplicitInstantiation)) { 6049 // The template hasn't been instantiated yet (or it has, but only as an 6050 // explicit instantiation declaration or implicit instantiation, which means 6051 // we haven't codegenned any members yet), so propagate the attribute. 6052 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6053 NewAttr->setInherited(true); 6054 BaseTemplateSpec->addAttr(NewAttr); 6055 6056 // If this was an import, mark that we propagated it from a derived class to 6057 // a base class template specialization. 6058 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr)) 6059 ImportAttr->setPropagatedToBaseTemplate(); 6060 6061 // If the template is already instantiated, checkDLLAttributeRedeclaration() 6062 // needs to be run again to work see the new attribute. Otherwise this will 6063 // get run whenever the template is instantiated. 6064 if (TSK != TSK_Undeclared) 6065 checkClassLevelDLLAttribute(BaseTemplateSpec); 6066 6067 return; 6068 } 6069 6070 if (getDLLAttr(BaseTemplateSpec)) { 6071 // The template has already been specialized or instantiated with an 6072 // attribute, explicitly or through propagation. We should not try to change 6073 // it. 6074 return; 6075 } 6076 6077 // The template was previously instantiated or explicitly specialized without 6078 // a dll attribute, It's too late for us to add an attribute, so warn that 6079 // this is unsupported. 6080 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 6081 << BaseTemplateSpec->isExplicitSpecialization(); 6082 Diag(ClassAttr->getLocation(), diag::note_attribute); 6083 if (BaseTemplateSpec->isExplicitSpecialization()) { 6084 Diag(BaseTemplateSpec->getLocation(), 6085 diag::note_template_class_explicit_specialization_was_here) 6086 << BaseTemplateSpec; 6087 } else { 6088 Diag(BaseTemplateSpec->getPointOfInstantiation(), 6089 diag::note_template_class_instantiation_was_here) 6090 << BaseTemplateSpec; 6091 } 6092 } 6093 6094 /// Determine the kind of defaulting that would be done for a given function. 6095 /// 6096 /// If the function is both a default constructor and a copy / move constructor 6097 /// (due to having a default argument for the first parameter), this picks 6098 /// CXXDefaultConstructor. 6099 /// 6100 /// FIXME: Check that case is properly handled by all callers. 6101 Sema::DefaultedFunctionKind 6102 Sema::getDefaultedFunctionKind(const FunctionDecl *FD) { 6103 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 6104 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { 6105 if (Ctor->isDefaultConstructor()) 6106 return Sema::CXXDefaultConstructor; 6107 6108 if (Ctor->isCopyConstructor()) 6109 return Sema::CXXCopyConstructor; 6110 6111 if (Ctor->isMoveConstructor()) 6112 return Sema::CXXMoveConstructor; 6113 } 6114 6115 if (MD->isCopyAssignmentOperator()) 6116 return Sema::CXXCopyAssignment; 6117 6118 if (MD->isMoveAssignmentOperator()) 6119 return Sema::CXXMoveAssignment; 6120 6121 if (isa<CXXDestructorDecl>(FD)) 6122 return Sema::CXXDestructor; 6123 } 6124 6125 switch (FD->getDeclName().getCXXOverloadedOperator()) { 6126 case OO_EqualEqual: 6127 return DefaultedComparisonKind::Equal; 6128 6129 case OO_ExclaimEqual: 6130 return DefaultedComparisonKind::NotEqual; 6131 6132 case OO_Spaceship: 6133 // No point allowing this if <=> doesn't exist in the current language mode. 6134 if (!getLangOpts().CPlusPlus2a) 6135 break; 6136 return DefaultedComparisonKind::ThreeWay; 6137 6138 case OO_Less: 6139 case OO_LessEqual: 6140 case OO_Greater: 6141 case OO_GreaterEqual: 6142 // No point allowing this if <=> doesn't exist in the current language mode. 6143 if (!getLangOpts().CPlusPlus2a) 6144 break; 6145 return DefaultedComparisonKind::Relational; 6146 6147 default: 6148 break; 6149 } 6150 6151 // Not defaultable. 6152 return DefaultedFunctionKind(); 6153 } 6154 6155 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD, 6156 SourceLocation DefaultLoc) { 6157 switch (S.getSpecialMember(MD)) { 6158 case Sema::CXXDefaultConstructor: 6159 S.DefineImplicitDefaultConstructor(DefaultLoc, 6160 cast<CXXConstructorDecl>(MD)); 6161 break; 6162 case Sema::CXXCopyConstructor: 6163 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 6164 break; 6165 case Sema::CXXCopyAssignment: 6166 S.DefineImplicitCopyAssignment(DefaultLoc, MD); 6167 break; 6168 case Sema::CXXDestructor: 6169 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD)); 6170 break; 6171 case Sema::CXXMoveConstructor: 6172 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 6173 break; 6174 case Sema::CXXMoveAssignment: 6175 S.DefineImplicitMoveAssignment(DefaultLoc, MD); 6176 break; 6177 case Sema::CXXInvalid: 6178 llvm_unreachable("Invalid special member."); 6179 } 6180 } 6181 6182 /// Determine whether a type is permitted to be passed or returned in 6183 /// registers, per C++ [class.temporary]p3. 6184 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D, 6185 TargetInfo::CallingConvKind CCK) { 6186 if (D->isDependentType() || D->isInvalidDecl()) 6187 return false; 6188 6189 // Clang <= 4 used the pre-C++11 rule, which ignores move operations. 6190 // The PS4 platform ABI follows the behavior of Clang 3.2. 6191 if (CCK == TargetInfo::CCK_ClangABI4OrPS4) 6192 return !D->hasNonTrivialDestructorForCall() && 6193 !D->hasNonTrivialCopyConstructorForCall(); 6194 6195 if (CCK == TargetInfo::CCK_MicrosoftWin64) { 6196 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false; 6197 bool DtorIsTrivialForCall = false; 6198 6199 // If a class has at least one non-deleted, trivial copy constructor, it 6200 // is passed according to the C ABI. Otherwise, it is passed indirectly. 6201 // 6202 // Note: This permits classes with non-trivial copy or move ctors to be 6203 // passed in registers, so long as they *also* have a trivial copy ctor, 6204 // which is non-conforming. 6205 if (D->needsImplicitCopyConstructor()) { 6206 if (!D->defaultedCopyConstructorIsDeleted()) { 6207 if (D->hasTrivialCopyConstructor()) 6208 CopyCtorIsTrivial = true; 6209 if (D->hasTrivialCopyConstructorForCall()) 6210 CopyCtorIsTrivialForCall = true; 6211 } 6212 } else { 6213 for (const CXXConstructorDecl *CD : D->ctors()) { 6214 if (CD->isCopyConstructor() && !CD->isDeleted()) { 6215 if (CD->isTrivial()) 6216 CopyCtorIsTrivial = true; 6217 if (CD->isTrivialForCall()) 6218 CopyCtorIsTrivialForCall = true; 6219 } 6220 } 6221 } 6222 6223 if (D->needsImplicitDestructor()) { 6224 if (!D->defaultedDestructorIsDeleted() && 6225 D->hasTrivialDestructorForCall()) 6226 DtorIsTrivialForCall = true; 6227 } else if (const auto *DD = D->getDestructor()) { 6228 if (!DD->isDeleted() && DD->isTrivialForCall()) 6229 DtorIsTrivialForCall = true; 6230 } 6231 6232 // If the copy ctor and dtor are both trivial-for-calls, pass direct. 6233 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall) 6234 return true; 6235 6236 // If a class has a destructor, we'd really like to pass it indirectly 6237 // because it allows us to elide copies. Unfortunately, MSVC makes that 6238 // impossible for small types, which it will pass in a single register or 6239 // stack slot. Most objects with dtors are large-ish, so handle that early. 6240 // We can't call out all large objects as being indirect because there are 6241 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate 6242 // how we pass large POD types. 6243 6244 // Note: This permits small classes with nontrivial destructors to be 6245 // passed in registers, which is non-conforming. 6246 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64(); 6247 uint64_t TypeSize = isAArch64 ? 128 : 64; 6248 6249 if (CopyCtorIsTrivial && 6250 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize) 6251 return true; 6252 return false; 6253 } 6254 6255 // Per C++ [class.temporary]p3, the relevant condition is: 6256 // each copy constructor, move constructor, and destructor of X is 6257 // either trivial or deleted, and X has at least one non-deleted copy 6258 // or move constructor 6259 bool HasNonDeletedCopyOrMove = false; 6260 6261 if (D->needsImplicitCopyConstructor() && 6262 !D->defaultedCopyConstructorIsDeleted()) { 6263 if (!D->hasTrivialCopyConstructorForCall()) 6264 return false; 6265 HasNonDeletedCopyOrMove = true; 6266 } 6267 6268 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() && 6269 !D->defaultedMoveConstructorIsDeleted()) { 6270 if (!D->hasTrivialMoveConstructorForCall()) 6271 return false; 6272 HasNonDeletedCopyOrMove = true; 6273 } 6274 6275 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() && 6276 !D->hasTrivialDestructorForCall()) 6277 return false; 6278 6279 for (const CXXMethodDecl *MD : D->methods()) { 6280 if (MD->isDeleted()) 6281 continue; 6282 6283 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 6284 if (CD && CD->isCopyOrMoveConstructor()) 6285 HasNonDeletedCopyOrMove = true; 6286 else if (!isa<CXXDestructorDecl>(MD)) 6287 continue; 6288 6289 if (!MD->isTrivialForCall()) 6290 return false; 6291 } 6292 6293 return HasNonDeletedCopyOrMove; 6294 } 6295 6296 /// Perform semantic checks on a class definition that has been 6297 /// completing, introducing implicitly-declared members, checking for 6298 /// abstract types, etc. 6299 /// 6300 /// \param S The scope in which the class was parsed. Null if we didn't just 6301 /// parse a class definition. 6302 /// \param Record The completed class. 6303 void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) { 6304 if (!Record) 6305 return; 6306 6307 if (Record->isAbstract() && !Record->isInvalidDecl()) { 6308 AbstractUsageInfo Info(*this, Record); 6309 CheckAbstractClassUsage(Info, Record); 6310 } 6311 6312 // If this is not an aggregate type and has no user-declared constructor, 6313 // complain about any non-static data members of reference or const scalar 6314 // type, since they will never get initializers. 6315 if (!Record->isInvalidDecl() && !Record->isDependentType() && 6316 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 6317 !Record->isLambda()) { 6318 bool Complained = false; 6319 for (const auto *F : Record->fields()) { 6320 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 6321 continue; 6322 6323 if (F->getType()->isReferenceType() || 6324 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 6325 if (!Complained) { 6326 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 6327 << Record->getTagKind() << Record; 6328 Complained = true; 6329 } 6330 6331 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 6332 << F->getType()->isReferenceType() 6333 << F->getDeclName(); 6334 } 6335 } 6336 } 6337 6338 if (Record->getIdentifier()) { 6339 // C++ [class.mem]p13: 6340 // If T is the name of a class, then each of the following shall have a 6341 // name different from T: 6342 // - every member of every anonymous union that is a member of class T. 6343 // 6344 // C++ [class.mem]p14: 6345 // In addition, if class T has a user-declared constructor (12.1), every 6346 // non-static data member of class T shall have a name different from T. 6347 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 6348 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 6349 ++I) { 6350 NamedDecl *D = (*I)->getUnderlyingDecl(); 6351 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) && 6352 Record->hasUserDeclaredConstructor()) || 6353 isa<IndirectFieldDecl>(D)) { 6354 Diag((*I)->getLocation(), diag::err_member_name_of_class) 6355 << D->getDeclName(); 6356 break; 6357 } 6358 } 6359 } 6360 6361 // Warn if the class has virtual methods but non-virtual public destructor. 6362 if (Record->isPolymorphic() && !Record->isDependentType()) { 6363 CXXDestructorDecl *dtor = Record->getDestructor(); 6364 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 6365 !Record->hasAttr<FinalAttr>()) 6366 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 6367 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 6368 } 6369 6370 if (Record->isAbstract()) { 6371 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 6372 Diag(Record->getLocation(), diag::warn_abstract_final_class) 6373 << FA->isSpelledAsSealed(); 6374 DiagnoseAbstractType(Record); 6375 } 6376 } 6377 6378 // Warn if the class has a final destructor but is not itself marked final. 6379 if (!Record->hasAttr<FinalAttr>()) { 6380 if (const CXXDestructorDecl *dtor = Record->getDestructor()) { 6381 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) { 6382 Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class) 6383 << FA->isSpelledAsSealed() 6384 << FixItHint::CreateInsertion( 6385 getLocForEndOfToken(Record->getLocation()), 6386 (FA->isSpelledAsSealed() ? " sealed" : " final")); 6387 Diag(Record->getLocation(), 6388 diag::note_final_dtor_non_final_class_silence) 6389 << Context.getRecordType(Record) << FA->isSpelledAsSealed(); 6390 } 6391 } 6392 } 6393 6394 // See if trivial_abi has to be dropped. 6395 if (Record->hasAttr<TrivialABIAttr>()) 6396 checkIllFormedTrivialABIStruct(*Record); 6397 6398 // Set HasTrivialSpecialMemberForCall if the record has attribute 6399 // "trivial_abi". 6400 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>(); 6401 6402 if (HasTrivialABI) 6403 Record->setHasTrivialSpecialMemberForCall(); 6404 6405 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=). 6406 // We check these last because they can depend on the properties of the 6407 // primary comparison functions (==, <=>). 6408 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons; 6409 6410 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) { 6411 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted()) 6412 return; 6413 6414 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD); 6415 if (DFK.asComparison() == DefaultedComparisonKind::NotEqual || 6416 DFK.asComparison() == DefaultedComparisonKind::Relational) 6417 DefaultedSecondaryComparisons.push_back(FD); 6418 else 6419 CheckExplicitlyDefaultedFunction(S, FD); 6420 }; 6421 6422 auto CompleteMemberFunction = [&](CXXMethodDecl *M) { 6423 // Check whether the explicitly-defaulted members are valid. 6424 CheckForDefaultedFunction(M); 6425 6426 // Skip the rest of the checks for a member of a dependent class. 6427 if (Record->isDependentType()) 6428 return; 6429 6430 // For an explicitly defaulted or deleted special member, we defer 6431 // determining triviality until the class is complete. That time is now! 6432 CXXSpecialMember CSM = getSpecialMember(M); 6433 if (!M->isImplicit() && !M->isUserProvided()) { 6434 if (CSM != CXXInvalid) { 6435 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 6436 // Inform the class that we've finished declaring this member. 6437 Record->finishedDefaultedOrDeletedMember(M); 6438 M->setTrivialForCall( 6439 HasTrivialABI || 6440 SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI)); 6441 Record->setTrivialForCallFlags(M); 6442 } 6443 } 6444 6445 // Set triviality for the purpose of calls if this is a user-provided 6446 // copy/move constructor or destructor. 6447 if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor || 6448 CSM == CXXDestructor) && M->isUserProvided()) { 6449 M->setTrivialForCall(HasTrivialABI); 6450 Record->setTrivialForCallFlags(M); 6451 } 6452 6453 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() && 6454 M->hasAttr<DLLExportAttr>()) { 6455 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 6456 M->isTrivial() && 6457 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor || 6458 CSM == CXXDestructor)) 6459 M->dropAttr<DLLExportAttr>(); 6460 6461 if (M->hasAttr<DLLExportAttr>()) { 6462 // Define after any fields with in-class initializers have been parsed. 6463 DelayedDllExportMemberFunctions.push_back(M); 6464 } 6465 } 6466 6467 // Define defaulted constexpr virtual functions that override a base class 6468 // function right away. 6469 // FIXME: We can defer doing this until the vtable is marked as used. 6470 if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods()) 6471 DefineImplicitSpecialMember(*this, M, M->getLocation()); 6472 }; 6473 6474 // Check the destructor before any other member function. We need to 6475 // determine whether it's trivial in order to determine whether the claas 6476 // type is a literal type, which is a prerequisite for determining whether 6477 // other special member functions are valid and whether they're implicitly 6478 // 'constexpr'. 6479 if (CXXDestructorDecl *Dtor = Record->getDestructor()) 6480 CompleteMemberFunction(Dtor); 6481 6482 bool HasMethodWithOverrideControl = false, 6483 HasOverridingMethodWithoutOverrideControl = false; 6484 for (auto *M : Record->methods()) { 6485 // FIXME: We could do this check for dependent types with non-dependent 6486 // bases. 6487 if (!Record->isDependentType()) { 6488 // See if a method overloads virtual methods in a base 6489 // class without overriding any. 6490 if (!M->isStatic()) 6491 DiagnoseHiddenVirtualMethods(M); 6492 if (M->hasAttr<OverrideAttr>()) 6493 HasMethodWithOverrideControl = true; 6494 else if (M->size_overridden_methods() > 0) 6495 HasOverridingMethodWithoutOverrideControl = true; 6496 } 6497 6498 if (!isa<CXXDestructorDecl>(M)) 6499 CompleteMemberFunction(M); 6500 } 6501 6502 if (HasMethodWithOverrideControl && 6503 HasOverridingMethodWithoutOverrideControl) { 6504 // At least one method has the 'override' control declared. 6505 // Diagnose all other overridden methods which do not have 'override' specified on them. 6506 for (auto *M : Record->methods()) 6507 DiagnoseAbsenceOfOverrideControl(M); 6508 } 6509 6510 // Process any defaulted friends in the member-specification. 6511 if (!Record->isDependentType()) { 6512 for (FriendDecl *D : Record->friends()) { 6513 CheckForDefaultedFunction( 6514 dyn_cast_or_null<FunctionDecl>(D->getFriendDecl())); 6515 } 6516 } 6517 6518 // Check the defaulted secondary comparisons after any other member functions. 6519 for (FunctionDecl *FD : DefaultedSecondaryComparisons) 6520 CheckExplicitlyDefaultedFunction(S, FD); 6521 6522 // ms_struct is a request to use the same ABI rules as MSVC. Check 6523 // whether this class uses any C++ features that are implemented 6524 // completely differently in MSVC, and if so, emit a diagnostic. 6525 // That diagnostic defaults to an error, but we allow projects to 6526 // map it down to a warning (or ignore it). It's a fairly common 6527 // practice among users of the ms_struct pragma to mass-annotate 6528 // headers, sweeping up a bunch of types that the project doesn't 6529 // really rely on MSVC-compatible layout for. We must therefore 6530 // support "ms_struct except for C++ stuff" as a secondary ABI. 6531 if (Record->isMsStruct(Context) && 6532 (Record->isPolymorphic() || Record->getNumBases())) { 6533 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 6534 } 6535 6536 checkClassLevelDLLAttribute(Record); 6537 checkClassLevelCodeSegAttribute(Record); 6538 6539 bool ClangABICompat4 = 6540 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4; 6541 TargetInfo::CallingConvKind CCK = 6542 Context.getTargetInfo().getCallingConvKind(ClangABICompat4); 6543 bool CanPass = canPassInRegisters(*this, Record, CCK); 6544 6545 // Do not change ArgPassingRestrictions if it has already been set to 6546 // APK_CanNeverPassInRegs. 6547 if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs) 6548 Record->setArgPassingRestrictions(CanPass 6549 ? RecordDecl::APK_CanPassInRegs 6550 : RecordDecl::APK_CannotPassInRegs); 6551 6552 // If canPassInRegisters returns true despite the record having a non-trivial 6553 // destructor, the record is destructed in the callee. This happens only when 6554 // the record or one of its subobjects has a field annotated with trivial_abi 6555 // or a field qualified with ObjC __strong/__weak. 6556 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee()) 6557 Record->setParamDestroyedInCallee(true); 6558 else if (Record->hasNonTrivialDestructor()) 6559 Record->setParamDestroyedInCallee(CanPass); 6560 6561 if (getLangOpts().ForceEmitVTables) { 6562 // If we want to emit all the vtables, we need to mark it as used. This 6563 // is especially required for cases like vtable assumption loads. 6564 MarkVTableUsed(Record->getInnerLocStart(), Record); 6565 } 6566 } 6567 6568 /// Look up the special member function that would be called by a special 6569 /// member function for a subobject of class type. 6570 /// 6571 /// \param Class The class type of the subobject. 6572 /// \param CSM The kind of special member function. 6573 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 6574 /// \param ConstRHS True if this is a copy operation with a const object 6575 /// on its RHS, that is, if the argument to the outer special member 6576 /// function is 'const' and this is not a field marked 'mutable'. 6577 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember( 6578 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 6579 unsigned FieldQuals, bool ConstRHS) { 6580 unsigned LHSQuals = 0; 6581 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 6582 LHSQuals = FieldQuals; 6583 6584 unsigned RHSQuals = FieldQuals; 6585 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 6586 RHSQuals = 0; 6587 else if (ConstRHS) 6588 RHSQuals |= Qualifiers::Const; 6589 6590 return S.LookupSpecialMember(Class, CSM, 6591 RHSQuals & Qualifiers::Const, 6592 RHSQuals & Qualifiers::Volatile, 6593 false, 6594 LHSQuals & Qualifiers::Const, 6595 LHSQuals & Qualifiers::Volatile); 6596 } 6597 6598 class Sema::InheritedConstructorInfo { 6599 Sema &S; 6600 SourceLocation UseLoc; 6601 6602 /// A mapping from the base classes through which the constructor was 6603 /// inherited to the using shadow declaration in that base class (or a null 6604 /// pointer if the constructor was declared in that base class). 6605 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *> 6606 InheritedFromBases; 6607 6608 public: 6609 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, 6610 ConstructorUsingShadowDecl *Shadow) 6611 : S(S), UseLoc(UseLoc) { 6612 bool DiagnosedMultipleConstructedBases = false; 6613 CXXRecordDecl *ConstructedBase = nullptr; 6614 UsingDecl *ConstructedBaseUsing = nullptr; 6615 6616 // Find the set of such base class subobjects and check that there's a 6617 // unique constructed subobject. 6618 for (auto *D : Shadow->redecls()) { 6619 auto *DShadow = cast<ConstructorUsingShadowDecl>(D); 6620 auto *DNominatedBase = DShadow->getNominatedBaseClass(); 6621 auto *DConstructedBase = DShadow->getConstructedBaseClass(); 6622 6623 InheritedFromBases.insert( 6624 std::make_pair(DNominatedBase->getCanonicalDecl(), 6625 DShadow->getNominatedBaseClassShadowDecl())); 6626 if (DShadow->constructsVirtualBase()) 6627 InheritedFromBases.insert( 6628 std::make_pair(DConstructedBase->getCanonicalDecl(), 6629 DShadow->getConstructedBaseClassShadowDecl())); 6630 else 6631 assert(DNominatedBase == DConstructedBase); 6632 6633 // [class.inhctor.init]p2: 6634 // If the constructor was inherited from multiple base class subobjects 6635 // of type B, the program is ill-formed. 6636 if (!ConstructedBase) { 6637 ConstructedBase = DConstructedBase; 6638 ConstructedBaseUsing = D->getUsingDecl(); 6639 } else if (ConstructedBase != DConstructedBase && 6640 !Shadow->isInvalidDecl()) { 6641 if (!DiagnosedMultipleConstructedBases) { 6642 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor) 6643 << Shadow->getTargetDecl(); 6644 S.Diag(ConstructedBaseUsing->getLocation(), 6645 diag::note_ambiguous_inherited_constructor_using) 6646 << ConstructedBase; 6647 DiagnosedMultipleConstructedBases = true; 6648 } 6649 S.Diag(D->getUsingDecl()->getLocation(), 6650 diag::note_ambiguous_inherited_constructor_using) 6651 << DConstructedBase; 6652 } 6653 } 6654 6655 if (DiagnosedMultipleConstructedBases) 6656 Shadow->setInvalidDecl(); 6657 } 6658 6659 /// Find the constructor to use for inherited construction of a base class, 6660 /// and whether that base class constructor inherits the constructor from a 6661 /// virtual base class (in which case it won't actually invoke it). 6662 std::pair<CXXConstructorDecl *, bool> 6663 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const { 6664 auto It = InheritedFromBases.find(Base->getCanonicalDecl()); 6665 if (It == InheritedFromBases.end()) 6666 return std::make_pair(nullptr, false); 6667 6668 // This is an intermediary class. 6669 if (It->second) 6670 return std::make_pair( 6671 S.findInheritingConstructor(UseLoc, Ctor, It->second), 6672 It->second->constructsVirtualBase()); 6673 6674 // This is the base class from which the constructor was inherited. 6675 return std::make_pair(Ctor, false); 6676 } 6677 }; 6678 6679 /// Is the special member function which would be selected to perform the 6680 /// specified operation on the specified class type a constexpr constructor? 6681 static bool 6682 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 6683 Sema::CXXSpecialMember CSM, unsigned Quals, 6684 bool ConstRHS, 6685 CXXConstructorDecl *InheritedCtor = nullptr, 6686 Sema::InheritedConstructorInfo *Inherited = nullptr) { 6687 // If we're inheriting a constructor, see if we need to call it for this base 6688 // class. 6689 if (InheritedCtor) { 6690 assert(CSM == Sema::CXXDefaultConstructor); 6691 auto BaseCtor = 6692 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first; 6693 if (BaseCtor) 6694 return BaseCtor->isConstexpr(); 6695 } 6696 6697 if (CSM == Sema::CXXDefaultConstructor) 6698 return ClassDecl->hasConstexprDefaultConstructor(); 6699 if (CSM == Sema::CXXDestructor) 6700 return ClassDecl->hasConstexprDestructor(); 6701 6702 Sema::SpecialMemberOverloadResult SMOR = 6703 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 6704 if (!SMOR.getMethod()) 6705 // A constructor we wouldn't select can't be "involved in initializing" 6706 // anything. 6707 return true; 6708 return SMOR.getMethod()->isConstexpr(); 6709 } 6710 6711 /// Determine whether the specified special member function would be constexpr 6712 /// if it were implicitly defined. 6713 static bool defaultedSpecialMemberIsConstexpr( 6714 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, 6715 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr, 6716 Sema::InheritedConstructorInfo *Inherited = nullptr) { 6717 if (!S.getLangOpts().CPlusPlus11) 6718 return false; 6719 6720 // C++11 [dcl.constexpr]p4: 6721 // In the definition of a constexpr constructor [...] 6722 bool Ctor = true; 6723 switch (CSM) { 6724 case Sema::CXXDefaultConstructor: 6725 if (Inherited) 6726 break; 6727 // Since default constructor lookup is essentially trivial (and cannot 6728 // involve, for instance, template instantiation), we compute whether a 6729 // defaulted default constructor is constexpr directly within CXXRecordDecl. 6730 // 6731 // This is important for performance; we need to know whether the default 6732 // constructor is constexpr to determine whether the type is a literal type. 6733 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 6734 6735 case Sema::CXXCopyConstructor: 6736 case Sema::CXXMoveConstructor: 6737 // For copy or move constructors, we need to perform overload resolution. 6738 break; 6739 6740 case Sema::CXXCopyAssignment: 6741 case Sema::CXXMoveAssignment: 6742 if (!S.getLangOpts().CPlusPlus14) 6743 return false; 6744 // In C++1y, we need to perform overload resolution. 6745 Ctor = false; 6746 break; 6747 6748 case Sema::CXXDestructor: 6749 return ClassDecl->defaultedDestructorIsConstexpr(); 6750 6751 case Sema::CXXInvalid: 6752 return false; 6753 } 6754 6755 // -- if the class is a non-empty union, or for each non-empty anonymous 6756 // union member of a non-union class, exactly one non-static data member 6757 // shall be initialized; [DR1359] 6758 // 6759 // If we squint, this is guaranteed, since exactly one non-static data member 6760 // will be initialized (if the constructor isn't deleted), we just don't know 6761 // which one. 6762 if (Ctor && ClassDecl->isUnion()) 6763 return CSM == Sema::CXXDefaultConstructor 6764 ? ClassDecl->hasInClassInitializer() || 6765 !ClassDecl->hasVariantMembers() 6766 : true; 6767 6768 // -- the class shall not have any virtual base classes; 6769 if (Ctor && ClassDecl->getNumVBases()) 6770 return false; 6771 6772 // C++1y [class.copy]p26: 6773 // -- [the class] is a literal type, and 6774 if (!Ctor && !ClassDecl->isLiteral()) 6775 return false; 6776 6777 // -- every constructor involved in initializing [...] base class 6778 // sub-objects shall be a constexpr constructor; 6779 // -- the assignment operator selected to copy/move each direct base 6780 // class is a constexpr function, and 6781 for (const auto &B : ClassDecl->bases()) { 6782 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 6783 if (!BaseType) continue; 6784 6785 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 6786 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg, 6787 InheritedCtor, Inherited)) 6788 return false; 6789 } 6790 6791 // -- every constructor involved in initializing non-static data members 6792 // [...] shall be a constexpr constructor; 6793 // -- every non-static data member and base class sub-object shall be 6794 // initialized 6795 // -- for each non-static data member of X that is of class type (or array 6796 // thereof), the assignment operator selected to copy/move that member is 6797 // a constexpr function 6798 for (const auto *F : ClassDecl->fields()) { 6799 if (F->isInvalidDecl()) 6800 continue; 6801 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer()) 6802 continue; 6803 QualType BaseType = S.Context.getBaseElementType(F->getType()); 6804 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 6805 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 6806 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 6807 BaseType.getCVRQualifiers(), 6808 ConstArg && !F->isMutable())) 6809 return false; 6810 } else if (CSM == Sema::CXXDefaultConstructor) { 6811 return false; 6812 } 6813 } 6814 6815 // All OK, it's constexpr! 6816 return true; 6817 } 6818 6819 static Sema::ImplicitExceptionSpecification 6820 ComputeDefaultedSpecialMemberExceptionSpec( 6821 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 6822 Sema::InheritedConstructorInfo *ICI); 6823 6824 static Sema::ImplicitExceptionSpecification 6825 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 6826 auto CSM = S.getSpecialMember(MD); 6827 if (CSM != Sema::CXXInvalid) 6828 return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr); 6829 6830 auto *CD = cast<CXXConstructorDecl>(MD); 6831 assert(CD->getInheritedConstructor() && 6832 "only special members have implicit exception specs"); 6833 Sema::InheritedConstructorInfo ICI( 6834 S, Loc, CD->getInheritedConstructor().getShadowDecl()); 6835 return ComputeDefaultedSpecialMemberExceptionSpec( 6836 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI); 6837 } 6838 6839 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 6840 CXXMethodDecl *MD) { 6841 FunctionProtoType::ExtProtoInfo EPI; 6842 6843 // Build an exception specification pointing back at this member. 6844 EPI.ExceptionSpec.Type = EST_Unevaluated; 6845 EPI.ExceptionSpec.SourceDecl = MD; 6846 6847 // Set the calling convention to the default for C++ instance methods. 6848 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 6849 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 6850 /*IsCXXMethod=*/true)); 6851 return EPI; 6852 } 6853 6854 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 6855 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 6856 if (FPT->getExceptionSpecType() != EST_Unevaluated) 6857 return; 6858 6859 // Evaluate the exception specification. 6860 auto IES = computeImplicitExceptionSpec(*this, Loc, MD); 6861 auto ESI = IES.getExceptionSpec(); 6862 6863 // Update the type of the special member to use it. 6864 UpdateExceptionSpec(MD, ESI); 6865 6866 // A user-provided destructor can be defined outside the class. When that 6867 // happens, be sure to update the exception specification on both 6868 // declarations. 6869 const FunctionProtoType *CanonicalFPT = 6870 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 6871 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 6872 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI); 6873 } 6874 6875 void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) { 6876 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted"); 6877 6878 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD); 6879 if (!DefKind) { 6880 assert(FD->getDeclContext()->isDependentContext()); 6881 return; 6882 } 6883 6884 if (DefKind.isSpecialMember() 6885 ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD), 6886 DefKind.asSpecialMember()) 6887 : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison())) 6888 FD->setInvalidDecl(); 6889 } 6890 6891 bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD, 6892 CXXSpecialMember CSM) { 6893 CXXRecordDecl *RD = MD->getParent(); 6894 6895 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 6896 "not an explicitly-defaulted special member"); 6897 6898 // Defer all checking for special members of a dependent type. 6899 if (RD->isDependentType()) 6900 return false; 6901 6902 // Whether this was the first-declared instance of the constructor. 6903 // This affects whether we implicitly add an exception spec and constexpr. 6904 bool First = MD == MD->getCanonicalDecl(); 6905 6906 bool HadError = false; 6907 6908 // C++11 [dcl.fct.def.default]p1: 6909 // A function that is explicitly defaulted shall 6910 // -- be a special member function [...] (checked elsewhere), 6911 // -- have the same type (except for ref-qualifiers, and except that a 6912 // copy operation can take a non-const reference) as an implicit 6913 // declaration, and 6914 // -- not have default arguments. 6915 // C++2a changes the second bullet to instead delete the function if it's 6916 // defaulted on its first declaration, unless it's "an assignment operator, 6917 // and its return type differs or its parameter type is not a reference". 6918 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus2a && First; 6919 bool ShouldDeleteForTypeMismatch = false; 6920 unsigned ExpectedParams = 1; 6921 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 6922 ExpectedParams = 0; 6923 if (MD->getNumParams() != ExpectedParams) { 6924 // This checks for default arguments: a copy or move constructor with a 6925 // default argument is classified as a default constructor, and assignment 6926 // operations and destructors can't have default arguments. 6927 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 6928 << CSM << MD->getSourceRange(); 6929 HadError = true; 6930 } else if (MD->isVariadic()) { 6931 if (DeleteOnTypeMismatch) 6932 ShouldDeleteForTypeMismatch = true; 6933 else { 6934 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 6935 << CSM << MD->getSourceRange(); 6936 HadError = true; 6937 } 6938 } 6939 6940 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 6941 6942 bool CanHaveConstParam = false; 6943 if (CSM == CXXCopyConstructor) 6944 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 6945 else if (CSM == CXXCopyAssignment) 6946 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 6947 6948 QualType ReturnType = Context.VoidTy; 6949 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 6950 // Check for return type matching. 6951 ReturnType = Type->getReturnType(); 6952 6953 QualType DeclType = Context.getTypeDeclType(RD); 6954 DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace()); 6955 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType); 6956 6957 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 6958 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 6959 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 6960 HadError = true; 6961 } 6962 6963 // A defaulted special member cannot have cv-qualifiers. 6964 if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) { 6965 if (DeleteOnTypeMismatch) 6966 ShouldDeleteForTypeMismatch = true; 6967 else { 6968 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 6969 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 6970 HadError = true; 6971 } 6972 } 6973 } 6974 6975 // Check for parameter type matching. 6976 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 6977 bool HasConstParam = false; 6978 if (ExpectedParams && ArgType->isReferenceType()) { 6979 // Argument must be reference to possibly-const T. 6980 QualType ReferentType = ArgType->getPointeeType(); 6981 HasConstParam = ReferentType.isConstQualified(); 6982 6983 if (ReferentType.isVolatileQualified()) { 6984 if (DeleteOnTypeMismatch) 6985 ShouldDeleteForTypeMismatch = true; 6986 else { 6987 Diag(MD->getLocation(), 6988 diag::err_defaulted_special_member_volatile_param) << CSM; 6989 HadError = true; 6990 } 6991 } 6992 6993 if (HasConstParam && !CanHaveConstParam) { 6994 if (DeleteOnTypeMismatch) 6995 ShouldDeleteForTypeMismatch = true; 6996 else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 6997 Diag(MD->getLocation(), 6998 diag::err_defaulted_special_member_copy_const_param) 6999 << (CSM == CXXCopyAssignment); 7000 // FIXME: Explain why this special member can't be const. 7001 HadError = true; 7002 } else { 7003 Diag(MD->getLocation(), 7004 diag::err_defaulted_special_member_move_const_param) 7005 << (CSM == CXXMoveAssignment); 7006 HadError = true; 7007 } 7008 } 7009 } else if (ExpectedParams) { 7010 // A copy assignment operator can take its argument by value, but a 7011 // defaulted one cannot. 7012 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 7013 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 7014 HadError = true; 7015 } 7016 7017 // C++11 [dcl.fct.def.default]p2: 7018 // An explicitly-defaulted function may be declared constexpr only if it 7019 // would have been implicitly declared as constexpr, 7020 // Do not apply this rule to members of class templates, since core issue 1358 7021 // makes such functions always instantiate to constexpr functions. For 7022 // functions which cannot be constexpr (for non-constructors in C++11 and for 7023 // destructors in C++14 and C++17), this is checked elsewhere. 7024 // 7025 // FIXME: This should not apply if the member is deleted. 7026 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 7027 HasConstParam); 7028 if ((getLangOpts().CPlusPlus2a || 7029 (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 7030 : isa<CXXConstructorDecl>(MD))) && 7031 MD->isConstexpr() && !Constexpr && 7032 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 7033 Diag(MD->getBeginLoc(), MD->isConsteval() 7034 ? diag::err_incorrect_defaulted_consteval 7035 : diag::err_incorrect_defaulted_constexpr) 7036 << CSM; 7037 // FIXME: Explain why the special member can't be constexpr. 7038 HadError = true; 7039 } 7040 7041 if (First) { 7042 // C++2a [dcl.fct.def.default]p3: 7043 // If a function is explicitly defaulted on its first declaration, it is 7044 // implicitly considered to be constexpr if the implicit declaration 7045 // would be. 7046 MD->setConstexprKind(Constexpr ? CSK_constexpr : CSK_unspecified); 7047 7048 if (!Type->hasExceptionSpec()) { 7049 // C++2a [except.spec]p3: 7050 // If a declaration of a function does not have a noexcept-specifier 7051 // [and] is defaulted on its first declaration, [...] the exception 7052 // specification is as specified below 7053 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 7054 EPI.ExceptionSpec.Type = EST_Unevaluated; 7055 EPI.ExceptionSpec.SourceDecl = MD; 7056 MD->setType(Context.getFunctionType(ReturnType, 7057 llvm::makeArrayRef(&ArgType, 7058 ExpectedParams), 7059 EPI)); 7060 } 7061 } 7062 7063 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) { 7064 if (First) { 7065 SetDeclDeleted(MD, MD->getLocation()); 7066 if (!inTemplateInstantiation() && !HadError) { 7067 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM; 7068 if (ShouldDeleteForTypeMismatch) { 7069 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM; 7070 } else { 7071 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 7072 } 7073 } 7074 if (ShouldDeleteForTypeMismatch && !HadError) { 7075 Diag(MD->getLocation(), 7076 diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM; 7077 } 7078 } else { 7079 // C++11 [dcl.fct.def.default]p4: 7080 // [For a] user-provided explicitly-defaulted function [...] if such a 7081 // function is implicitly defined as deleted, the program is ill-formed. 7082 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 7083 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl"); 7084 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 7085 HadError = true; 7086 } 7087 } 7088 7089 return HadError; 7090 } 7091 7092 namespace { 7093 /// Helper class for building and checking a defaulted comparison. 7094 /// 7095 /// Defaulted functions are built in two phases: 7096 /// 7097 /// * First, the set of operations that the function will perform are 7098 /// identified, and some of them are checked. If any of the checked 7099 /// operations is invalid in certain ways, the comparison function is 7100 /// defined as deleted and no body is built. 7101 /// * Then, if the function is not defined as deleted, the body is built. 7102 /// 7103 /// This is accomplished by performing two visitation steps over the eventual 7104 /// body of the function. 7105 template<typename Derived, typename ResultList, typename Result, 7106 typename Subobject> 7107 class DefaultedComparisonVisitor { 7108 public: 7109 using DefaultedComparisonKind = Sema::DefaultedComparisonKind; 7110 7111 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7112 DefaultedComparisonKind DCK) 7113 : S(S), RD(RD), FD(FD), DCK(DCK) { 7114 if (auto *Info = FD->getDefaultedFunctionInfo()) { 7115 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an 7116 // UnresolvedSet to avoid this copy. 7117 Fns.assign(Info->getUnqualifiedLookups().begin(), 7118 Info->getUnqualifiedLookups().end()); 7119 } 7120 } 7121 7122 ResultList visit() { 7123 // The type of an lvalue naming a parameter of this function. 7124 QualType ParamLvalType = 7125 FD->getParamDecl(0)->getType().getNonReferenceType(); 7126 7127 ResultList Results; 7128 7129 switch (DCK) { 7130 case DefaultedComparisonKind::None: 7131 llvm_unreachable("not a defaulted comparison"); 7132 7133 case DefaultedComparisonKind::Equal: 7134 case DefaultedComparisonKind::ThreeWay: 7135 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers()); 7136 return Results; 7137 7138 case DefaultedComparisonKind::NotEqual: 7139 case DefaultedComparisonKind::Relational: 7140 Results.add(getDerived().visitExpandedSubobject( 7141 ParamLvalType, getDerived().getCompleteObject())); 7142 return Results; 7143 } 7144 llvm_unreachable(""); 7145 } 7146 7147 protected: 7148 Derived &getDerived() { return static_cast<Derived&>(*this); } 7149 7150 /// Visit the expanded list of subobjects of the given type, as specified in 7151 /// C++2a [class.compare.default]. 7152 /// 7153 /// \return \c true if the ResultList object said we're done, \c false if not. 7154 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record, 7155 Qualifiers Quals) { 7156 // C++2a [class.compare.default]p4: 7157 // The direct base class subobjects of C 7158 for (CXXBaseSpecifier &Base : Record->bases()) 7159 if (Results.add(getDerived().visitSubobject( 7160 S.Context.getQualifiedType(Base.getType(), Quals), 7161 getDerived().getBase(&Base)))) 7162 return true; 7163 7164 // followed by the non-static data members of C 7165 for (FieldDecl *Field : Record->fields()) { 7166 // Recursively expand anonymous structs. 7167 if (Field->isAnonymousStructOrUnion()) { 7168 if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(), 7169 Quals)) 7170 return true; 7171 continue; 7172 } 7173 7174 // Figure out the type of an lvalue denoting this field. 7175 Qualifiers FieldQuals = Quals; 7176 if (Field->isMutable()) 7177 FieldQuals.removeConst(); 7178 QualType FieldType = 7179 S.Context.getQualifiedType(Field->getType(), FieldQuals); 7180 7181 if (Results.add(getDerived().visitSubobject( 7182 FieldType, getDerived().getField(Field)))) 7183 return true; 7184 } 7185 7186 // form a list of subobjects. 7187 return false; 7188 } 7189 7190 Result visitSubobject(QualType Type, Subobject Subobj) { 7191 // In that list, any subobject of array type is recursively expanded 7192 const ArrayType *AT = S.Context.getAsArrayType(Type); 7193 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT)) 7194 return getDerived().visitSubobjectArray(CAT->getElementType(), 7195 CAT->getSize(), Subobj); 7196 return getDerived().visitExpandedSubobject(Type, Subobj); 7197 } 7198 7199 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size, 7200 Subobject Subobj) { 7201 return getDerived().visitSubobject(Type, Subobj); 7202 } 7203 7204 protected: 7205 Sema &S; 7206 CXXRecordDecl *RD; 7207 FunctionDecl *FD; 7208 DefaultedComparisonKind DCK; 7209 UnresolvedSet<16> Fns; 7210 }; 7211 7212 /// Information about a defaulted comparison, as determined by 7213 /// DefaultedComparisonAnalyzer. 7214 struct DefaultedComparisonInfo { 7215 bool Deleted = false; 7216 bool Constexpr = true; 7217 7218 static DefaultedComparisonInfo deleted() { return {true, false}; } 7219 7220 bool add(const DefaultedComparisonInfo &R) { 7221 Deleted |= R.Deleted; 7222 Constexpr &= R.Constexpr; 7223 return Deleted; 7224 } 7225 }; 7226 7227 /// An element in the expanded list of subobjects of a defaulted comparison, as 7228 /// specified in C++2a [class.compare.default]p4. 7229 struct DefaultedComparisonSubobject { 7230 enum { CompleteObject, Member, Base } Kind; 7231 NamedDecl *Decl; 7232 SourceLocation Loc; 7233 }; 7234 7235 /// A visitor over the notional body of a defaulted comparison that determines 7236 /// whether that body would be deleted or constexpr. 7237 class DefaultedComparisonAnalyzer 7238 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer, 7239 DefaultedComparisonInfo, 7240 DefaultedComparisonInfo, 7241 DefaultedComparisonSubobject> { 7242 public: 7243 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr }; 7244 7245 private: 7246 DiagnosticKind Diagnose; 7247 7248 public: 7249 using Base = DefaultedComparisonVisitor; 7250 using Result = DefaultedComparisonInfo; 7251 using Subobject = DefaultedComparisonSubobject; 7252 7253 friend Base; 7254 7255 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7256 DefaultedComparisonKind DCK, 7257 DiagnosticKind Diagnose = NoDiagnostics) 7258 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {} 7259 7260 Result visit() { 7261 if ((DCK == DefaultedComparisonKind::Equal || 7262 DCK == DefaultedComparisonKind::ThreeWay) && 7263 RD->hasVariantMembers()) { 7264 // C++2a [class.compare.default]p2 [P2002R0]: 7265 // A defaulted comparison operator function for class C is defined as 7266 // deleted if [...] C has variant members. 7267 if (Diagnose == ExplainDeleted) { 7268 S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union) 7269 << FD << RD->isUnion() << RD; 7270 } 7271 return Result::deleted(); 7272 } 7273 7274 return Base::visit(); 7275 } 7276 7277 private: 7278 Subobject getCompleteObject() { 7279 return Subobject{Subobject::CompleteObject, nullptr, FD->getLocation()}; 7280 } 7281 7282 Subobject getBase(CXXBaseSpecifier *Base) { 7283 return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(), 7284 Base->getBaseTypeLoc()}; 7285 } 7286 7287 Subobject getField(FieldDecl *Field) { 7288 return Subobject{Subobject::Member, Field, Field->getLocation()}; 7289 } 7290 7291 Result visitExpandedSubobject(QualType Type, Subobject Subobj) { 7292 // C++2a [class.compare.default]p2 [P2002R0]: 7293 // A defaulted <=> or == operator function for class C is defined as 7294 // deleted if any non-static data member of C is of reference type 7295 if (Type->isReferenceType()) { 7296 if (Diagnose == ExplainDeleted) { 7297 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member) 7298 << FD << RD; 7299 } 7300 return Result::deleted(); 7301 } 7302 7303 // [...] Let xi be an lvalue denoting the ith element [...] 7304 OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue); 7305 Expr *Args[] = {&Xi, &Xi}; 7306 7307 // All operators start by trying to apply that same operator recursively. 7308 OverloadedOperatorKind OO = FD->getOverloadedOperator(); 7309 assert(OO != OO_None && "not an overloaded operator!"); 7310 return visitBinaryOperator(OO, Args, Subobj); 7311 } 7312 7313 Result 7314 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args, 7315 Subobject Subobj, 7316 OverloadCandidateSet *SpaceshipCandidates = nullptr) { 7317 // Note that there is no need to consider rewritten candidates here if 7318 // we've already found there is no viable 'operator<=>' candidate (and are 7319 // considering synthesizing a '<=>' from '==' and '<'). 7320 OverloadCandidateSet CandidateSet( 7321 FD->getLocation(), OverloadCandidateSet::CSK_Operator, 7322 OverloadCandidateSet::OperatorRewriteInfo( 7323 OO, /*AllowRewrittenCandidates=*/!SpaceshipCandidates)); 7324 7325 /// C++2a [class.compare.default]p1 [P2002R0]: 7326 /// [...] the defaulted function itself is never a candidate for overload 7327 /// resolution [...] 7328 CandidateSet.exclude(FD); 7329 7330 S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args); 7331 7332 Result R; 7333 7334 OverloadCandidateSet::iterator Best; 7335 switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) { 7336 case OR_Success: 7337 // C++2a [class.compare.secondary]p2 [P2002R0]: 7338 // The operator function [...] is defined as deleted if [...] the 7339 // candidate selected by overload resolution is not a rewritten 7340 // candidate. 7341 if ((DCK == DefaultedComparisonKind::NotEqual || 7342 DCK == DefaultedComparisonKind::Relational) && 7343 !Best->RewriteKind) { 7344 if (Diagnose == ExplainDeleted) { 7345 S.Diag(Best->Function->getLocation(), 7346 diag::note_defaulted_comparison_not_rewritten_callee) 7347 << FD; 7348 } 7349 return Result::deleted(); 7350 } 7351 7352 // C++2a [class.compare.default]p3 [P2002R0]: 7353 // A defaulted comparison function is constexpr-compatible if [...] 7354 // no overlod resolution performed [...] results in a non-constexpr 7355 // function. 7356 if (FunctionDecl *FD = Best->Function) { 7357 assert(!FD->isDeleted() && "wrong overload resolution result"); 7358 // If it's not constexpr, explain why not. 7359 if (Diagnose == ExplainConstexpr && !FD->isConstexpr()) { 7360 if (Subobj.Kind != Subobject::CompleteObject) 7361 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr) 7362 << Subobj.Kind << Subobj.Decl; 7363 S.Diag(FD->getLocation(), 7364 diag::note_defaulted_comparison_not_constexpr_here); 7365 // Bail out after explaining; we don't want any more notes. 7366 return Result::deleted(); 7367 } 7368 R.Constexpr &= FD->isConstexpr(); 7369 } 7370 7371 // Note that we might be rewriting to a different operator. That call is 7372 // not considered until we come to actually build the comparison function. 7373 break; 7374 7375 case OR_Ambiguous: 7376 if (Diagnose == ExplainDeleted) { 7377 unsigned Kind = 0; 7378 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship) 7379 Kind = OO == OO_EqualEqual ? 1 : 2; 7380 CandidateSet.NoteCandidates( 7381 PartialDiagnosticAt( 7382 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous) 7383 << FD << Kind << Subobj.Kind << Subobj.Decl), 7384 S, OCD_AmbiguousCandidates, Args); 7385 } 7386 R = Result::deleted(); 7387 break; 7388 7389 case OR_Deleted: 7390 if (Diagnose == ExplainDeleted) { 7391 if ((DCK == DefaultedComparisonKind::NotEqual || 7392 DCK == DefaultedComparisonKind::Relational) && 7393 !Best->RewriteKind) { 7394 S.Diag(Best->Function->getLocation(), 7395 diag::note_defaulted_comparison_not_rewritten_callee) 7396 << FD; 7397 } else { 7398 S.Diag(Subobj.Loc, 7399 diag::note_defaulted_comparison_calls_deleted) 7400 << FD << Subobj.Kind << Subobj.Decl; 7401 S.NoteDeletedFunction(Best->Function); 7402 } 7403 } 7404 R = Result::deleted(); 7405 break; 7406 7407 case OR_No_Viable_Function: 7408 // If there's no usable candidate, we're done unless we can rewrite a 7409 // '<=>' in terms of '==' and '<'. 7410 if (OO == OO_Spaceship && 7411 S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) { 7412 // For any kind of comparison category return type, we need a usable 7413 // '==' and a usable '<'. 7414 if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj, 7415 &CandidateSet))) 7416 R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet)); 7417 break; 7418 } 7419 7420 if (Diagnose == ExplainDeleted) { 7421 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function) 7422 << FD << Subobj.Kind << Subobj.Decl; 7423 7424 // For a three-way comparison, list both the candidates for the 7425 // original operator and the candidates for the synthesized operator. 7426 if (SpaceshipCandidates) { 7427 SpaceshipCandidates->NoteCandidates( 7428 S, Args, 7429 SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates, 7430 Args, FD->getLocation())); 7431 S.Diag(Subobj.Loc, 7432 diag::note_defaulted_comparison_no_viable_function_synthesized) 7433 << (OO == OO_EqualEqual ? 0 : 1); 7434 } 7435 7436 CandidateSet.NoteCandidates( 7437 S, Args, 7438 CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args, 7439 FD->getLocation())); 7440 } 7441 R = Result::deleted(); 7442 break; 7443 } 7444 7445 return R; 7446 } 7447 }; 7448 7449 /// A list of statements. 7450 struct StmtListResult { 7451 bool IsInvalid = false; 7452 llvm::SmallVector<Stmt*, 16> Stmts; 7453 7454 bool add(const StmtResult &S) { 7455 IsInvalid |= S.isInvalid(); 7456 if (IsInvalid) 7457 return true; 7458 Stmts.push_back(S.get()); 7459 return false; 7460 } 7461 }; 7462 7463 /// A visitor over the notional body of a defaulted comparison that synthesizes 7464 /// the actual body. 7465 class DefaultedComparisonSynthesizer 7466 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer, 7467 StmtListResult, StmtResult, 7468 std::pair<ExprResult, ExprResult>> { 7469 SourceLocation Loc; 7470 unsigned ArrayDepth = 0; 7471 7472 public: 7473 using Base = DefaultedComparisonVisitor; 7474 using ExprPair = std::pair<ExprResult, ExprResult>; 7475 7476 friend Base; 7477 7478 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD, 7479 DefaultedComparisonKind DCK, 7480 SourceLocation BodyLoc) 7481 : Base(S, RD, FD, DCK), Loc(BodyLoc) {} 7482 7483 /// Build a suitable function body for this defaulted comparison operator. 7484 StmtResult build() { 7485 Sema::CompoundScopeRAII CompoundScope(S); 7486 7487 StmtListResult Stmts = visit(); 7488 if (Stmts.IsInvalid) 7489 return StmtError(); 7490 7491 ExprResult RetVal; 7492 switch (DCK) { 7493 case DefaultedComparisonKind::None: 7494 llvm_unreachable("not a defaulted comparison"); 7495 7496 case DefaultedComparisonKind::Equal: { 7497 // C++2a [class.eq]p3: 7498 // [...] compar[e] the corresponding elements [...] until the first 7499 // index i where xi == yi yields [...] false. If no such index exists, 7500 // V is true. Otherwise, V is false. 7501 // 7502 // Join the comparisons with '&&'s and return the result. Use a right 7503 // fold (traversing the conditions right-to-left), because that 7504 // short-circuits more naturally. 7505 auto OldStmts = std::move(Stmts.Stmts); 7506 Stmts.Stmts.clear(); 7507 ExprResult CmpSoFar; 7508 // Finish a particular comparison chain. 7509 auto FinishCmp = [&] { 7510 if (Expr *Prior = CmpSoFar.get()) { 7511 // Convert the last expression to 'return ...;' 7512 if (RetVal.isUnset() && Stmts.Stmts.empty()) 7513 RetVal = CmpSoFar; 7514 // Convert any prior comparison to 'if (!(...)) return false;' 7515 else if (Stmts.add(buildIfNotCondReturnFalse(Prior))) 7516 return true; 7517 CmpSoFar = ExprResult(); 7518 } 7519 return false; 7520 }; 7521 for (Stmt *EAsStmt : llvm::reverse(OldStmts)) { 7522 Expr *E = dyn_cast<Expr>(EAsStmt); 7523 if (!E) { 7524 // Found an array comparison. 7525 if (FinishCmp() || Stmts.add(EAsStmt)) 7526 return StmtError(); 7527 continue; 7528 } 7529 7530 if (CmpSoFar.isUnset()) { 7531 CmpSoFar = E; 7532 continue; 7533 } 7534 CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get()); 7535 if (CmpSoFar.isInvalid()) 7536 return StmtError(); 7537 } 7538 if (FinishCmp()) 7539 return StmtError(); 7540 std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end()); 7541 // If no such index exists, V is true. 7542 if (RetVal.isUnset()) 7543 RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true); 7544 break; 7545 } 7546 7547 case DefaultedComparisonKind::ThreeWay: { 7548 // Per C++2a [class.spaceship]p3, as a fallback add: 7549 // return static_cast<R>(std::strong_ordering::equal); 7550 QualType StrongOrdering = S.CheckComparisonCategoryType( 7551 ComparisonCategoryType::StrongOrdering, Loc); 7552 if (StrongOrdering.isNull()) 7553 return StmtError(); 7554 VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering) 7555 .getValueInfo(ComparisonCategoryResult::Equal) 7556 ->VD; 7557 RetVal = getDecl(EqualVD); 7558 if (RetVal.isInvalid()) 7559 return StmtError(); 7560 RetVal = buildStaticCastToR(RetVal.get()); 7561 break; 7562 } 7563 7564 case DefaultedComparisonKind::NotEqual: 7565 case DefaultedComparisonKind::Relational: 7566 RetVal = cast<Expr>(Stmts.Stmts.pop_back_val()); 7567 break; 7568 } 7569 7570 // Build the final return statement. 7571 if (RetVal.isInvalid()) 7572 return StmtError(); 7573 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get()); 7574 if (ReturnStmt.isInvalid()) 7575 return StmtError(); 7576 Stmts.Stmts.push_back(ReturnStmt.get()); 7577 7578 return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false); 7579 } 7580 7581 private: 7582 ExprResult getDecl(ValueDecl *VD) { 7583 return S.BuildDeclarationNameExpr( 7584 CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD); 7585 } 7586 7587 ExprResult getParam(unsigned I) { 7588 ParmVarDecl *PD = FD->getParamDecl(I); 7589 return getDecl(PD); 7590 } 7591 7592 ExprPair getCompleteObject() { 7593 unsigned Param = 0; 7594 ExprResult LHS; 7595 if (isa<CXXMethodDecl>(FD)) { 7596 // LHS is '*this'. 7597 LHS = S.ActOnCXXThis(Loc); 7598 if (!LHS.isInvalid()) 7599 LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get()); 7600 } else { 7601 LHS = getParam(Param++); 7602 } 7603 ExprResult RHS = getParam(Param++); 7604 assert(Param == FD->getNumParams()); 7605 return {LHS, RHS}; 7606 } 7607 7608 ExprPair getBase(CXXBaseSpecifier *Base) { 7609 ExprPair Obj = getCompleteObject(); 7610 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 7611 return {ExprError(), ExprError()}; 7612 CXXCastPath Path = {Base}; 7613 return {S.ImpCastExprToType(Obj.first.get(), Base->getType(), 7614 CK_DerivedToBase, VK_LValue, &Path), 7615 S.ImpCastExprToType(Obj.second.get(), Base->getType(), 7616 CK_DerivedToBase, VK_LValue, &Path)}; 7617 } 7618 7619 ExprPair getField(FieldDecl *Field) { 7620 ExprPair Obj = getCompleteObject(); 7621 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 7622 return {ExprError(), ExprError()}; 7623 7624 DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess()); 7625 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc); 7626 return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc, 7627 CXXScopeSpec(), Field, Found, NameInfo), 7628 S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc, 7629 CXXScopeSpec(), Field, Found, NameInfo)}; 7630 } 7631 7632 // FIXME: When expanding a subobject, register a note in the code synthesis 7633 // stack to say which subobject we're comparing. 7634 7635 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) { 7636 if (Cond.isInvalid()) 7637 return StmtError(); 7638 7639 ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get()); 7640 if (NotCond.isInvalid()) 7641 return StmtError(); 7642 7643 ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false); 7644 assert(!False.isInvalid() && "should never fail"); 7645 StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get()); 7646 if (ReturnFalse.isInvalid()) 7647 return StmtError(); 7648 7649 return S.ActOnIfStmt(Loc, false, nullptr, 7650 S.ActOnCondition(nullptr, Loc, NotCond.get(), 7651 Sema::ConditionKind::Boolean), 7652 ReturnFalse.get(), SourceLocation(), nullptr); 7653 } 7654 7655 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size, 7656 ExprPair Subobj) { 7657 QualType SizeType = S.Context.getSizeType(); 7658 Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType)); 7659 7660 // Build 'size_t i$n = 0'. 7661 IdentifierInfo *IterationVarName = nullptr; 7662 { 7663 SmallString<8> Str; 7664 llvm::raw_svector_ostream OS(Str); 7665 OS << "i" << ArrayDepth; 7666 IterationVarName = &S.Context.Idents.get(OS.str()); 7667 } 7668 VarDecl *IterationVar = VarDecl::Create( 7669 S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType, 7670 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None); 7671 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 7672 IterationVar->setInit( 7673 IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 7674 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc); 7675 7676 auto IterRef = [&] { 7677 ExprResult Ref = S.BuildDeclarationNameExpr( 7678 CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc), 7679 IterationVar); 7680 assert(!Ref.isInvalid() && "can't reference our own variable?"); 7681 return Ref.get(); 7682 }; 7683 7684 // Build 'i$n != Size'. 7685 ExprResult Cond = S.CreateBuiltinBinOp( 7686 Loc, BO_NE, IterRef(), 7687 IntegerLiteral::Create(S.Context, Size, SizeType, Loc)); 7688 assert(!Cond.isInvalid() && "should never fail"); 7689 7690 // Build '++i$n'. 7691 ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef()); 7692 assert(!Inc.isInvalid() && "should never fail"); 7693 7694 // Build 'a[i$n]' and 'b[i$n]'. 7695 auto Index = [&](ExprResult E) { 7696 if (E.isInvalid()) 7697 return ExprError(); 7698 return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc); 7699 }; 7700 Subobj.first = Index(Subobj.first); 7701 Subobj.second = Index(Subobj.second); 7702 7703 // Compare the array elements. 7704 ++ArrayDepth; 7705 StmtResult Substmt = visitSubobject(Type, Subobj); 7706 --ArrayDepth; 7707 7708 if (Substmt.isInvalid()) 7709 return StmtError(); 7710 7711 // For the inner level of an 'operator==', build 'if (!cmp) return false;'. 7712 // For outer levels or for an 'operator<=>' we already have a suitable 7713 // statement that returns as necessary. 7714 if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) { 7715 assert(DCK == DefaultedComparisonKind::Equal && 7716 "should have non-expression statement"); 7717 Substmt = buildIfNotCondReturnFalse(ElemCmp); 7718 if (Substmt.isInvalid()) 7719 return StmtError(); 7720 } 7721 7722 // Build 'for (...) ...' 7723 return S.ActOnForStmt(Loc, Loc, Init, 7724 S.ActOnCondition(nullptr, Loc, Cond.get(), 7725 Sema::ConditionKind::Boolean), 7726 S.MakeFullDiscardedValueExpr(Inc.get()), Loc, 7727 Substmt.get()); 7728 } 7729 7730 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) { 7731 if (Obj.first.isInvalid() || Obj.second.isInvalid()) 7732 return StmtError(); 7733 7734 OverloadedOperatorKind OO = FD->getOverloadedOperator(); 7735 ExprResult Op = S.CreateOverloadedBinOp( 7736 Loc, BinaryOperator::getOverloadedOpcode(OO), Fns, 7737 Obj.first.get(), Obj.second.get(), /*PerformADL=*/true, 7738 /*AllowRewrittenCandidates=*/true, FD); 7739 if (Op.isInvalid()) 7740 return StmtError(); 7741 7742 switch (DCK) { 7743 case DefaultedComparisonKind::None: 7744 llvm_unreachable("not a defaulted comparison"); 7745 7746 case DefaultedComparisonKind::Equal: 7747 // Per C++2a [class.eq]p2, each comparison is individually contextually 7748 // converted to bool. 7749 Op = S.PerformContextuallyConvertToBool(Op.get()); 7750 if (Op.isInvalid()) 7751 return StmtError(); 7752 return Op.get(); 7753 7754 case DefaultedComparisonKind::ThreeWay: { 7755 // Per C++2a [class.spaceship]p3, form: 7756 // if (R cmp = static_cast<R>(op); cmp != 0) 7757 // return cmp; 7758 QualType R = FD->getReturnType(); 7759 Op = buildStaticCastToR(Op.get()); 7760 if (Op.isInvalid()) 7761 return StmtError(); 7762 7763 // R cmp = ...; 7764 IdentifierInfo *Name = &S.Context.Idents.get("cmp"); 7765 VarDecl *VD = 7766 VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R, 7767 S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None); 7768 S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false); 7769 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc); 7770 7771 // cmp != 0 7772 ExprResult VDRef = getDecl(VD); 7773 if (VDRef.isInvalid()) 7774 return StmtError(); 7775 llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0); 7776 Expr *Zero = 7777 IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc); 7778 ExprResult Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), 7779 Zero, true, true, FD); 7780 if (Comp.isInvalid()) 7781 return StmtError(); 7782 Sema::ConditionResult Cond = S.ActOnCondition( 7783 nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean); 7784 if (Cond.isInvalid()) 7785 return StmtError(); 7786 7787 // return cmp; 7788 VDRef = getDecl(VD); 7789 if (VDRef.isInvalid()) 7790 return StmtError(); 7791 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get()); 7792 if (ReturnStmt.isInvalid()) 7793 return StmtError(); 7794 7795 // if (...) 7796 return S.ActOnIfStmt(Loc, /*IsConstexpr=*/false, InitStmt, Cond, 7797 ReturnStmt.get(), /*ElseLoc=*/SourceLocation(), 7798 /*Else=*/nullptr); 7799 } 7800 7801 case DefaultedComparisonKind::NotEqual: 7802 case DefaultedComparisonKind::Relational: 7803 // C++2a [class.compare.secondary]p2: 7804 // Otherwise, the operator function yields x @ y. 7805 return Op.get(); 7806 } 7807 llvm_unreachable(""); 7808 } 7809 7810 /// Build "static_cast<R>(E)". 7811 ExprResult buildStaticCastToR(Expr *E) { 7812 QualType R = FD->getReturnType(); 7813 assert(!R->isUndeducedType() && "type should have been deduced already"); 7814 7815 // Don't bother forming a no-op cast in the common case. 7816 if (E->isRValue() && S.Context.hasSameType(E->getType(), R)) 7817 return E; 7818 return S.BuildCXXNamedCast(Loc, tok::kw_static_cast, 7819 S.Context.getTrivialTypeSourceInfo(R, Loc), E, 7820 SourceRange(Loc, Loc), SourceRange(Loc, Loc)); 7821 } 7822 }; 7823 } 7824 7825 /// Perform the unqualified lookups that might be needed to form a defaulted 7826 /// comparison function for the given operator. 7827 static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S, 7828 UnresolvedSetImpl &Operators, 7829 OverloadedOperatorKind Op) { 7830 auto Lookup = [&](OverloadedOperatorKind OO) { 7831 Self.LookupOverloadedOperatorName(OO, S, QualType(), QualType(), Operators); 7832 }; 7833 7834 // Every defaulted operator looks up itself. 7835 Lookup(Op); 7836 // ... and the rewritten form of itself, if any. 7837 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op)) 7838 Lookup(ExtraOp); 7839 7840 // For 'operator<=>', we also form a 'cmp != 0' expression, and might 7841 // synthesize a three-way comparison from '<' and '=='. 7842 if (Op == OO_Spaceship) { 7843 Lookup(OO_ExclaimEqual); 7844 Lookup(OO_Less); 7845 Lookup(OO_EqualEqual); 7846 } 7847 } 7848 7849 bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD, 7850 DefaultedComparisonKind DCK) { 7851 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison"); 7852 7853 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext()); 7854 assert(RD && "defaulted comparison is not defaulted in a class"); 7855 7856 // Perform any unqualified lookups we're going to need to default this 7857 // function. 7858 if (S) { 7859 UnresolvedSet<32> Operators; 7860 lookupOperatorsForDefaultedComparison(*this, S, Operators, 7861 FD->getOverloadedOperator()); 7862 FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create( 7863 Context, Operators.pairs())); 7864 } 7865 7866 // C++2a [class.compare.default]p1: 7867 // A defaulted comparison operator function for some class C shall be a 7868 // non-template function declared in the member-specification of C that is 7869 // -- a non-static const member of C having one parameter of type 7870 // const C&, or 7871 // -- a friend of C having two parameters of type const C&. 7872 QualType ExpectedParmType = 7873 Context.getLValueReferenceType(Context.getRecordType(RD).withConst()); 7874 for (const ParmVarDecl *Param : FD->parameters()) { 7875 if (!Param->getType()->isDependentType() && 7876 !Context.hasSameType(Param->getType(), ExpectedParmType)) { 7877 Diag(FD->getLocation(), diag::err_defaulted_comparison_param) 7878 << (int)DCK << Param->getType() << ExpectedParmType 7879 << Param->getSourceRange(); 7880 return true; 7881 } 7882 } 7883 7884 // ... non-static const member ... 7885 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 7886 assert(!MD->isStatic() && "comparison function cannot be a static member"); 7887 if (!MD->isConst()) { 7888 SourceLocation InsertLoc; 7889 if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc()) 7890 InsertLoc = getLocForEndOfToken(Loc.getRParenLoc()); 7891 Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const) 7892 << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const"); 7893 7894 // Add the 'const' to the type to recover. 7895 const auto *FPT = MD->getType()->castAs<FunctionProtoType>(); 7896 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 7897 EPI.TypeQuals.addConst(); 7898 MD->setType(Context.getFunctionType(FPT->getReturnType(), 7899 FPT->getParamTypes(), EPI)); 7900 } 7901 } else { 7902 // A non-member function declared in a class must be a friend. 7903 assert(FD->getFriendObjectKind() && "expected a friend declaration"); 7904 } 7905 7906 // C++2a [class.eq]p1, [class.rel]p1: 7907 // A [defaulted comparison other than <=>] shall have a declared return 7908 // type bool. 7909 if (DCK != DefaultedComparisonKind::ThreeWay && 7910 !FD->getDeclaredReturnType()->isDependentType() && 7911 !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) { 7912 Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool) 7913 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy 7914 << FD->getReturnTypeSourceRange(); 7915 return true; 7916 } 7917 7918 // For a defaulted function in a dependent class, defer all remaining checks 7919 // until instantiation. 7920 if (RD->isDependentType()) 7921 return false; 7922 7923 // Determine whether the function should be defined as deleted. 7924 DefaultedComparisonInfo Info = 7925 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit(); 7926 7927 bool First = FD == FD->getCanonicalDecl(); 7928 7929 // If we want to delete the function, then do so; there's nothing else to 7930 // check in that case. 7931 if (Info.Deleted) { 7932 if (!First) { 7933 // C++11 [dcl.fct.def.default]p4: 7934 // [For a] user-provided explicitly-defaulted function [...] if such a 7935 // function is implicitly defined as deleted, the program is ill-formed. 7936 // 7937 // This is really just a consequence of the general rule that you can 7938 // only delete a function on its first declaration. 7939 Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes) 7940 << (int)DCK; 7941 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 7942 DefaultedComparisonAnalyzer::ExplainDeleted) 7943 .visit(); 7944 return true; 7945 } 7946 7947 SetDeclDeleted(FD, FD->getLocation()); 7948 if (!inTemplateInstantiation()) { 7949 Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted) 7950 << (int)DCK; 7951 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 7952 DefaultedComparisonAnalyzer::ExplainDeleted) 7953 .visit(); 7954 } 7955 return false; 7956 } 7957 7958 // FIXME: Deduce the return type now. 7959 7960 // C++2a [dcl.fct.def.default]p3 [P2002R0]: 7961 // An explicitly-defaulted function that is not defined as deleted may be 7962 // declared constexpr or consteval only if it is constexpr-compatible. 7963 // C++2a [class.compare.default]p3 [P2002R0]: 7964 // A defaulted comparison function is constexpr-compatible if it satisfies 7965 // the requirements for a constexpr function [...] 7966 // The only relevant requirements are that the parameter and return types are 7967 // literal types. The remaining conditions are checked by the analyzer. 7968 if (FD->isConstexpr()) { 7969 if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) && 7970 CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) && 7971 !Info.Constexpr) { 7972 Diag(FD->getBeginLoc(), 7973 diag::err_incorrect_defaulted_comparison_constexpr) 7974 << (int)DCK << FD->isConsteval(); 7975 DefaultedComparisonAnalyzer(*this, RD, FD, DCK, 7976 DefaultedComparisonAnalyzer::ExplainConstexpr) 7977 .visit(); 7978 } 7979 } 7980 7981 // C++2a [dcl.fct.def.default]p3 [P2002R0]: 7982 // If a constexpr-compatible function is explicitly defaulted on its first 7983 // declaration, it is implicitly considered to be constexpr. 7984 // FIXME: Only applying this to the first declaration seems problematic, as 7985 // simple reorderings can affect the meaning of the program. 7986 if (First) { 7987 if (!FD->isConstexpr() && Info.Constexpr) 7988 FD->setConstexprKind(CSK_constexpr); 7989 7990 // FIXME: Set up an implicit exception specification, or if given an 7991 // explicit one, check that it matches. 7992 } 7993 7994 return false; 7995 } 7996 7997 void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD, 7998 DefaultedComparisonKind DCK) { 7999 assert(FD->isDefaulted() && !FD->isDeleted() && 8000 !FD->doesThisDeclarationHaveABody()); 8001 if (FD->willHaveBody() || FD->isInvalidDecl()) 8002 return; 8003 8004 SynthesizedFunctionScope Scope(*this, FD); 8005 8006 // The exception specification is needed because we are defining the 8007 // function. 8008 // FIXME: Handle this better. Computing the exception specification will 8009 // eventually need the function body. 8010 ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>()); 8011 8012 // Add a context note for diagnostics produced after this point. 8013 Scope.addContextNote(UseLoc); 8014 8015 // Build and set up the function body. 8016 { 8017 CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent()); 8018 SourceLocation BodyLoc = 8019 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation(); 8020 StmtResult Body = 8021 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build(); 8022 if (Body.isInvalid()) { 8023 FD->setInvalidDecl(); 8024 return; 8025 } 8026 FD->setBody(Body.get()); 8027 FD->markUsed(Context); 8028 } 8029 8030 if (ASTMutationListener *L = getASTMutationListener()) 8031 L->CompletedImplicitDefinition(FD); 8032 } 8033 8034 void Sema::CheckDelayedMemberExceptionSpecs() { 8035 decltype(DelayedOverridingExceptionSpecChecks) Overriding; 8036 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent; 8037 8038 std::swap(Overriding, DelayedOverridingExceptionSpecChecks); 8039 std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks); 8040 8041 // Perform any deferred checking of exception specifications for virtual 8042 // destructors. 8043 for (auto &Check : Overriding) 8044 CheckOverridingFunctionExceptionSpec(Check.first, Check.second); 8045 8046 // Perform any deferred checking of exception specifications for befriended 8047 // special members. 8048 for (auto &Check : Equivalent) 8049 CheckEquivalentExceptionSpec(Check.second, Check.first); 8050 } 8051 8052 namespace { 8053 /// CRTP base class for visiting operations performed by a special member 8054 /// function (or inherited constructor). 8055 template<typename Derived> 8056 struct SpecialMemberVisitor { 8057 Sema &S; 8058 CXXMethodDecl *MD; 8059 Sema::CXXSpecialMember CSM; 8060 Sema::InheritedConstructorInfo *ICI; 8061 8062 // Properties of the special member, computed for convenience. 8063 bool IsConstructor = false, IsAssignment = false, ConstArg = false; 8064 8065 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 8066 Sema::InheritedConstructorInfo *ICI) 8067 : S(S), MD(MD), CSM(CSM), ICI(ICI) { 8068 switch (CSM) { 8069 case Sema::CXXDefaultConstructor: 8070 case Sema::CXXCopyConstructor: 8071 case Sema::CXXMoveConstructor: 8072 IsConstructor = true; 8073 break; 8074 case Sema::CXXCopyAssignment: 8075 case Sema::CXXMoveAssignment: 8076 IsAssignment = true; 8077 break; 8078 case Sema::CXXDestructor: 8079 break; 8080 case Sema::CXXInvalid: 8081 llvm_unreachable("invalid special member kind"); 8082 } 8083 8084 if (MD->getNumParams()) { 8085 if (const ReferenceType *RT = 8086 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 8087 ConstArg = RT->getPointeeType().isConstQualified(); 8088 } 8089 } 8090 8091 Derived &getDerived() { return static_cast<Derived&>(*this); } 8092 8093 /// Is this a "move" special member? 8094 bool isMove() const { 8095 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment; 8096 } 8097 8098 /// Look up the corresponding special member in the given class. 8099 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class, 8100 unsigned Quals, bool IsMutable) { 8101 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 8102 ConstArg && !IsMutable); 8103 } 8104 8105 /// Look up the constructor for the specified base class to see if it's 8106 /// overridden due to this being an inherited constructor. 8107 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) { 8108 if (!ICI) 8109 return {}; 8110 assert(CSM == Sema::CXXDefaultConstructor); 8111 auto *BaseCtor = 8112 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor(); 8113 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first) 8114 return MD; 8115 return {}; 8116 } 8117 8118 /// A base or member subobject. 8119 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 8120 8121 /// Get the location to use for a subobject in diagnostics. 8122 static SourceLocation getSubobjectLoc(Subobject Subobj) { 8123 // FIXME: For an indirect virtual base, the direct base leading to 8124 // the indirect virtual base would be a more useful choice. 8125 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>()) 8126 return B->getBaseTypeLoc(); 8127 else 8128 return Subobj.get<FieldDecl*>()->getLocation(); 8129 } 8130 8131 enum BasesToVisit { 8132 /// Visit all non-virtual (direct) bases. 8133 VisitNonVirtualBases, 8134 /// Visit all direct bases, virtual or not. 8135 VisitDirectBases, 8136 /// Visit all non-virtual bases, and all virtual bases if the class 8137 /// is not abstract. 8138 VisitPotentiallyConstructedBases, 8139 /// Visit all direct or virtual bases. 8140 VisitAllBases 8141 }; 8142 8143 // Visit the bases and members of the class. 8144 bool visit(BasesToVisit Bases) { 8145 CXXRecordDecl *RD = MD->getParent(); 8146 8147 if (Bases == VisitPotentiallyConstructedBases) 8148 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases; 8149 8150 for (auto &B : RD->bases()) 8151 if ((Bases == VisitDirectBases || !B.isVirtual()) && 8152 getDerived().visitBase(&B)) 8153 return true; 8154 8155 if (Bases == VisitAllBases) 8156 for (auto &B : RD->vbases()) 8157 if (getDerived().visitBase(&B)) 8158 return true; 8159 8160 for (auto *F : RD->fields()) 8161 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() && 8162 getDerived().visitField(F)) 8163 return true; 8164 8165 return false; 8166 } 8167 }; 8168 } 8169 8170 namespace { 8171 struct SpecialMemberDeletionInfo 8172 : SpecialMemberVisitor<SpecialMemberDeletionInfo> { 8173 bool Diagnose; 8174 8175 SourceLocation Loc; 8176 8177 bool AllFieldsAreConst; 8178 8179 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 8180 Sema::CXXSpecialMember CSM, 8181 Sema::InheritedConstructorInfo *ICI, bool Diagnose) 8182 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose), 8183 Loc(MD->getLocation()), AllFieldsAreConst(true) {} 8184 8185 bool inUnion() const { return MD->getParent()->isUnion(); } 8186 8187 Sema::CXXSpecialMember getEffectiveCSM() { 8188 return ICI ? Sema::CXXInvalid : CSM; 8189 } 8190 8191 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType); 8192 8193 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); } 8194 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); } 8195 8196 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 8197 bool shouldDeleteForField(FieldDecl *FD); 8198 bool shouldDeleteForAllConstMembers(); 8199 8200 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 8201 unsigned Quals); 8202 bool shouldDeleteForSubobjectCall(Subobject Subobj, 8203 Sema::SpecialMemberOverloadResult SMOR, 8204 bool IsDtorCallInCtor); 8205 8206 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 8207 }; 8208 } 8209 8210 /// Is the given special member inaccessible when used on the given 8211 /// sub-object. 8212 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 8213 CXXMethodDecl *target) { 8214 /// If we're operating on a base class, the object type is the 8215 /// type of this special member. 8216 QualType objectTy; 8217 AccessSpecifier access = target->getAccess(); 8218 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 8219 objectTy = S.Context.getTypeDeclType(MD->getParent()); 8220 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 8221 8222 // If we're operating on a field, the object type is the type of the field. 8223 } else { 8224 objectTy = S.Context.getTypeDeclType(target->getParent()); 8225 } 8226 8227 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 8228 } 8229 8230 /// Check whether we should delete a special member due to the implicit 8231 /// definition containing a call to a special member of a subobject. 8232 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 8233 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR, 8234 bool IsDtorCallInCtor) { 8235 CXXMethodDecl *Decl = SMOR.getMethod(); 8236 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 8237 8238 int DiagKind = -1; 8239 8240 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 8241 DiagKind = !Decl ? 0 : 1; 8242 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 8243 DiagKind = 2; 8244 else if (!isAccessible(Subobj, Decl)) 8245 DiagKind = 3; 8246 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 8247 !Decl->isTrivial()) { 8248 // A member of a union must have a trivial corresponding special member. 8249 // As a weird special case, a destructor call from a union's constructor 8250 // must be accessible and non-deleted, but need not be trivial. Such a 8251 // destructor is never actually called, but is semantically checked as 8252 // if it were. 8253 DiagKind = 4; 8254 } 8255 8256 if (DiagKind == -1) 8257 return false; 8258 8259 if (Diagnose) { 8260 if (Field) { 8261 S.Diag(Field->getLocation(), 8262 diag::note_deleted_special_member_class_subobject) 8263 << getEffectiveCSM() << MD->getParent() << /*IsField*/true 8264 << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false; 8265 } else { 8266 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 8267 S.Diag(Base->getBeginLoc(), 8268 diag::note_deleted_special_member_class_subobject) 8269 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 8270 << Base->getType() << DiagKind << IsDtorCallInCtor 8271 << /*IsObjCPtr*/false; 8272 } 8273 8274 if (DiagKind == 1) 8275 S.NoteDeletedFunction(Decl); 8276 // FIXME: Explain inaccessibility if DiagKind == 3. 8277 } 8278 8279 return true; 8280 } 8281 8282 /// Check whether we should delete a special member function due to having a 8283 /// direct or virtual base class or non-static data member of class type M. 8284 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 8285 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 8286 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 8287 bool IsMutable = Field && Field->isMutable(); 8288 8289 // C++11 [class.ctor]p5: 8290 // -- any direct or virtual base class, or non-static data member with no 8291 // brace-or-equal-initializer, has class type M (or array thereof) and 8292 // either M has no default constructor or overload resolution as applied 8293 // to M's default constructor results in an ambiguity or in a function 8294 // that is deleted or inaccessible 8295 // C++11 [class.copy]p11, C++11 [class.copy]p23: 8296 // -- a direct or virtual base class B that cannot be copied/moved because 8297 // overload resolution, as applied to B's corresponding special member, 8298 // results in an ambiguity or a function that is deleted or inaccessible 8299 // from the defaulted special member 8300 // C++11 [class.dtor]p5: 8301 // -- any direct or virtual base class [...] has a type with a destructor 8302 // that is deleted or inaccessible 8303 if (!(CSM == Sema::CXXDefaultConstructor && 8304 Field && Field->hasInClassInitializer()) && 8305 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 8306 false)) 8307 return true; 8308 8309 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 8310 // -- any direct or virtual base class or non-static data member has a 8311 // type with a destructor that is deleted or inaccessible 8312 if (IsConstructor) { 8313 Sema::SpecialMemberOverloadResult SMOR = 8314 S.LookupSpecialMember(Class, Sema::CXXDestructor, 8315 false, false, false, false, false); 8316 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 8317 return true; 8318 } 8319 8320 return false; 8321 } 8322 8323 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember( 8324 FieldDecl *FD, QualType FieldType) { 8325 // The defaulted special functions are defined as deleted if this is a variant 8326 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak 8327 // type under ARC. 8328 if (!FieldType.hasNonTrivialObjCLifetime()) 8329 return false; 8330 8331 // Don't make the defaulted default constructor defined as deleted if the 8332 // member has an in-class initializer. 8333 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) 8334 return false; 8335 8336 if (Diagnose) { 8337 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent()); 8338 S.Diag(FD->getLocation(), 8339 diag::note_deleted_special_member_class_subobject) 8340 << getEffectiveCSM() << ParentClass << /*IsField*/true 8341 << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true; 8342 } 8343 8344 return true; 8345 } 8346 8347 /// Check whether we should delete a special member function due to the class 8348 /// having a particular direct or virtual base class. 8349 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 8350 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 8351 // If program is correct, BaseClass cannot be null, but if it is, the error 8352 // must be reported elsewhere. 8353 if (!BaseClass) 8354 return false; 8355 // If we have an inheriting constructor, check whether we're calling an 8356 // inherited constructor instead of a default constructor. 8357 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 8358 if (auto *BaseCtor = SMOR.getMethod()) { 8359 // Note that we do not check access along this path; other than that, 8360 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false); 8361 // FIXME: Check that the base has a usable destructor! Sink this into 8362 // shouldDeleteForClassSubobject. 8363 if (BaseCtor->isDeleted() && Diagnose) { 8364 S.Diag(Base->getBeginLoc(), 8365 diag::note_deleted_special_member_class_subobject) 8366 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 8367 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false 8368 << /*IsObjCPtr*/false; 8369 S.NoteDeletedFunction(BaseCtor); 8370 } 8371 return BaseCtor->isDeleted(); 8372 } 8373 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 8374 } 8375 8376 /// Check whether we should delete a special member function due to the class 8377 /// having a particular non-static data member. 8378 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 8379 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 8380 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 8381 8382 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType)) 8383 return true; 8384 8385 if (CSM == Sema::CXXDefaultConstructor) { 8386 // For a default constructor, all references must be initialized in-class 8387 // and, if a union, it must have a non-const member. 8388 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 8389 if (Diagnose) 8390 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 8391 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0; 8392 return true; 8393 } 8394 // C++11 [class.ctor]p5: any non-variant non-static data member of 8395 // const-qualified type (or array thereof) with no 8396 // brace-or-equal-initializer does not have a user-provided default 8397 // constructor. 8398 if (!inUnion() && FieldType.isConstQualified() && 8399 !FD->hasInClassInitializer() && 8400 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 8401 if (Diagnose) 8402 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 8403 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1; 8404 return true; 8405 } 8406 8407 if (inUnion() && !FieldType.isConstQualified()) 8408 AllFieldsAreConst = false; 8409 } else if (CSM == Sema::CXXCopyConstructor) { 8410 // For a copy constructor, data members must not be of rvalue reference 8411 // type. 8412 if (FieldType->isRValueReferenceType()) { 8413 if (Diagnose) 8414 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 8415 << MD->getParent() << FD << FieldType; 8416 return true; 8417 } 8418 } else if (IsAssignment) { 8419 // For an assignment operator, data members must not be of reference type. 8420 if (FieldType->isReferenceType()) { 8421 if (Diagnose) 8422 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 8423 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0; 8424 return true; 8425 } 8426 if (!FieldRecord && FieldType.isConstQualified()) { 8427 // C++11 [class.copy]p23: 8428 // -- a non-static data member of const non-class type (or array thereof) 8429 if (Diagnose) 8430 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 8431 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1; 8432 return true; 8433 } 8434 } 8435 8436 if (FieldRecord) { 8437 // Some additional restrictions exist on the variant members. 8438 if (!inUnion() && FieldRecord->isUnion() && 8439 FieldRecord->isAnonymousStructOrUnion()) { 8440 bool AllVariantFieldsAreConst = true; 8441 8442 // FIXME: Handle anonymous unions declared within anonymous unions. 8443 for (auto *UI : FieldRecord->fields()) { 8444 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 8445 8446 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType)) 8447 return true; 8448 8449 if (!UnionFieldType.isConstQualified()) 8450 AllVariantFieldsAreConst = false; 8451 8452 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 8453 if (UnionFieldRecord && 8454 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 8455 UnionFieldType.getCVRQualifiers())) 8456 return true; 8457 } 8458 8459 // At least one member in each anonymous union must be non-const 8460 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 8461 !FieldRecord->field_empty()) { 8462 if (Diagnose) 8463 S.Diag(FieldRecord->getLocation(), 8464 diag::note_deleted_default_ctor_all_const) 8465 << !!ICI << MD->getParent() << /*anonymous union*/1; 8466 return true; 8467 } 8468 8469 // Don't check the implicit member of the anonymous union type. 8470 // This is technically non-conformant, but sanity demands it. 8471 return false; 8472 } 8473 8474 if (shouldDeleteForClassSubobject(FieldRecord, FD, 8475 FieldType.getCVRQualifiers())) 8476 return true; 8477 } 8478 8479 return false; 8480 } 8481 8482 /// C++11 [class.ctor] p5: 8483 /// A defaulted default constructor for a class X is defined as deleted if 8484 /// X is a union and all of its variant members are of const-qualified type. 8485 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 8486 // This is a silly definition, because it gives an empty union a deleted 8487 // default constructor. Don't do that. 8488 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) { 8489 bool AnyFields = false; 8490 for (auto *F : MD->getParent()->fields()) 8491 if ((AnyFields = !F->isUnnamedBitfield())) 8492 break; 8493 if (!AnyFields) 8494 return false; 8495 if (Diagnose) 8496 S.Diag(MD->getParent()->getLocation(), 8497 diag::note_deleted_default_ctor_all_const) 8498 << !!ICI << MD->getParent() << /*not anonymous union*/0; 8499 return true; 8500 } 8501 return false; 8502 } 8503 8504 /// Determine whether a defaulted special member function should be defined as 8505 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 8506 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 8507 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 8508 InheritedConstructorInfo *ICI, 8509 bool Diagnose) { 8510 if (MD->isInvalidDecl()) 8511 return false; 8512 CXXRecordDecl *RD = MD->getParent(); 8513 assert(!RD->isDependentType() && "do deletion after instantiation"); 8514 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 8515 return false; 8516 8517 // C++11 [expr.lambda.prim]p19: 8518 // The closure type associated with a lambda-expression has a 8519 // deleted (8.4.3) default constructor and a deleted copy 8520 // assignment operator. 8521 // C++2a adds back these operators if the lambda has no lambda-capture. 8522 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() && 8523 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 8524 if (Diagnose) 8525 Diag(RD->getLocation(), diag::note_lambda_decl); 8526 return true; 8527 } 8528 8529 // For an anonymous struct or union, the copy and assignment special members 8530 // will never be used, so skip the check. For an anonymous union declared at 8531 // namespace scope, the constructor and destructor are used. 8532 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 8533 RD->isAnonymousStructOrUnion()) 8534 return false; 8535 8536 // C++11 [class.copy]p7, p18: 8537 // If the class definition declares a move constructor or move assignment 8538 // operator, an implicitly declared copy constructor or copy assignment 8539 // operator is defined as deleted. 8540 if (MD->isImplicit() && 8541 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 8542 CXXMethodDecl *UserDeclaredMove = nullptr; 8543 8544 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the 8545 // deletion of the corresponding copy operation, not both copy operations. 8546 // MSVC 2015 has adopted the standards conforming behavior. 8547 bool DeletesOnlyMatchingCopy = 8548 getLangOpts().MSVCCompat && 8549 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015); 8550 8551 if (RD->hasUserDeclaredMoveConstructor() && 8552 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) { 8553 if (!Diagnose) return true; 8554 8555 // Find any user-declared move constructor. 8556 for (auto *I : RD->ctors()) { 8557 if (I->isMoveConstructor()) { 8558 UserDeclaredMove = I; 8559 break; 8560 } 8561 } 8562 assert(UserDeclaredMove); 8563 } else if (RD->hasUserDeclaredMoveAssignment() && 8564 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) { 8565 if (!Diagnose) return true; 8566 8567 // Find any user-declared move assignment operator. 8568 for (auto *I : RD->methods()) { 8569 if (I->isMoveAssignmentOperator()) { 8570 UserDeclaredMove = I; 8571 break; 8572 } 8573 } 8574 assert(UserDeclaredMove); 8575 } 8576 8577 if (UserDeclaredMove) { 8578 Diag(UserDeclaredMove->getLocation(), 8579 diag::note_deleted_copy_user_declared_move) 8580 << (CSM == CXXCopyAssignment) << RD 8581 << UserDeclaredMove->isMoveAssignmentOperator(); 8582 return true; 8583 } 8584 } 8585 8586 // Do access control from the special member function 8587 ContextRAII MethodContext(*this, MD); 8588 8589 // C++11 [class.dtor]p5: 8590 // -- for a virtual destructor, lookup of the non-array deallocation function 8591 // results in an ambiguity or in a function that is deleted or inaccessible 8592 if (CSM == CXXDestructor && MD->isVirtual()) { 8593 FunctionDecl *OperatorDelete = nullptr; 8594 DeclarationName Name = 8595 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 8596 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 8597 OperatorDelete, /*Diagnose*/false)) { 8598 if (Diagnose) 8599 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 8600 return true; 8601 } 8602 } 8603 8604 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose); 8605 8606 // Per DR1611, do not consider virtual bases of constructors of abstract 8607 // classes, since we are not going to construct them. 8608 // Per DR1658, do not consider virtual bases of destructors of abstract 8609 // classes either. 8610 // Per DR2180, for assignment operators we only assign (and thus only 8611 // consider) direct bases. 8612 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases 8613 : SMI.VisitPotentiallyConstructedBases)) 8614 return true; 8615 8616 if (SMI.shouldDeleteForAllConstMembers()) 8617 return true; 8618 8619 if (getLangOpts().CUDA) { 8620 // We should delete the special member in CUDA mode if target inference 8621 // failed. 8622 // For inherited constructors (non-null ICI), CSM may be passed so that MD 8623 // is treated as certain special member, which may not reflect what special 8624 // member MD really is. However inferCUDATargetForImplicitSpecialMember 8625 // expects CSM to match MD, therefore recalculate CSM. 8626 assert(ICI || CSM == getSpecialMember(MD)); 8627 auto RealCSM = CSM; 8628 if (ICI) 8629 RealCSM = getSpecialMember(MD); 8630 8631 return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD, 8632 SMI.ConstArg, Diagnose); 8633 } 8634 8635 return false; 8636 } 8637 8638 void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) { 8639 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD); 8640 assert(DFK && "not a defaultable function"); 8641 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted"); 8642 8643 if (DFK.isSpecialMember()) { 8644 ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), 8645 nullptr, /*Diagnose=*/true); 8646 } else { 8647 DefaultedComparisonAnalyzer( 8648 *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD, 8649 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted) 8650 .visit(); 8651 } 8652 } 8653 8654 /// Perform lookup for a special member of the specified kind, and determine 8655 /// whether it is trivial. If the triviality can be determined without the 8656 /// lookup, skip it. This is intended for use when determining whether a 8657 /// special member of a containing object is trivial, and thus does not ever 8658 /// perform overload resolution for default constructors. 8659 /// 8660 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 8661 /// member that was most likely to be intended to be trivial, if any. 8662 /// 8663 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to 8664 /// determine whether the special member is trivial. 8665 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 8666 Sema::CXXSpecialMember CSM, unsigned Quals, 8667 bool ConstRHS, 8668 Sema::TrivialABIHandling TAH, 8669 CXXMethodDecl **Selected) { 8670 if (Selected) 8671 *Selected = nullptr; 8672 8673 switch (CSM) { 8674 case Sema::CXXInvalid: 8675 llvm_unreachable("not a special member"); 8676 8677 case Sema::CXXDefaultConstructor: 8678 // C++11 [class.ctor]p5: 8679 // A default constructor is trivial if: 8680 // - all the [direct subobjects] have trivial default constructors 8681 // 8682 // Note, no overload resolution is performed in this case. 8683 if (RD->hasTrivialDefaultConstructor()) 8684 return true; 8685 8686 if (Selected) { 8687 // If there's a default constructor which could have been trivial, dig it 8688 // out. Otherwise, if there's any user-provided default constructor, point 8689 // to that as an example of why there's not a trivial one. 8690 CXXConstructorDecl *DefCtor = nullptr; 8691 if (RD->needsImplicitDefaultConstructor()) 8692 S.DeclareImplicitDefaultConstructor(RD); 8693 for (auto *CI : RD->ctors()) { 8694 if (!CI->isDefaultConstructor()) 8695 continue; 8696 DefCtor = CI; 8697 if (!DefCtor->isUserProvided()) 8698 break; 8699 } 8700 8701 *Selected = DefCtor; 8702 } 8703 8704 return false; 8705 8706 case Sema::CXXDestructor: 8707 // C++11 [class.dtor]p5: 8708 // A destructor is trivial if: 8709 // - all the direct [subobjects] have trivial destructors 8710 if (RD->hasTrivialDestructor() || 8711 (TAH == Sema::TAH_ConsiderTrivialABI && 8712 RD->hasTrivialDestructorForCall())) 8713 return true; 8714 8715 if (Selected) { 8716 if (RD->needsImplicitDestructor()) 8717 S.DeclareImplicitDestructor(RD); 8718 *Selected = RD->getDestructor(); 8719 } 8720 8721 return false; 8722 8723 case Sema::CXXCopyConstructor: 8724 // C++11 [class.copy]p12: 8725 // A copy constructor is trivial if: 8726 // - the constructor selected to copy each direct [subobject] is trivial 8727 if (RD->hasTrivialCopyConstructor() || 8728 (TAH == Sema::TAH_ConsiderTrivialABI && 8729 RD->hasTrivialCopyConstructorForCall())) { 8730 if (Quals == Qualifiers::Const) 8731 // We must either select the trivial copy constructor or reach an 8732 // ambiguity; no need to actually perform overload resolution. 8733 return true; 8734 } else if (!Selected) { 8735 return false; 8736 } 8737 // In C++98, we are not supposed to perform overload resolution here, but we 8738 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 8739 // cases like B as having a non-trivial copy constructor: 8740 // struct A { template<typename T> A(T&); }; 8741 // struct B { mutable A a; }; 8742 goto NeedOverloadResolution; 8743 8744 case Sema::CXXCopyAssignment: 8745 // C++11 [class.copy]p25: 8746 // A copy assignment operator is trivial if: 8747 // - the assignment operator selected to copy each direct [subobject] is 8748 // trivial 8749 if (RD->hasTrivialCopyAssignment()) { 8750 if (Quals == Qualifiers::Const) 8751 return true; 8752 } else if (!Selected) { 8753 return false; 8754 } 8755 // In C++98, we are not supposed to perform overload resolution here, but we 8756 // treat that as a language defect. 8757 goto NeedOverloadResolution; 8758 8759 case Sema::CXXMoveConstructor: 8760 case Sema::CXXMoveAssignment: 8761 NeedOverloadResolution: 8762 Sema::SpecialMemberOverloadResult SMOR = 8763 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 8764 8765 // The standard doesn't describe how to behave if the lookup is ambiguous. 8766 // We treat it as not making the member non-trivial, just like the standard 8767 // mandates for the default constructor. This should rarely matter, because 8768 // the member will also be deleted. 8769 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 8770 return true; 8771 8772 if (!SMOR.getMethod()) { 8773 assert(SMOR.getKind() == 8774 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 8775 return false; 8776 } 8777 8778 // We deliberately don't check if we found a deleted special member. We're 8779 // not supposed to! 8780 if (Selected) 8781 *Selected = SMOR.getMethod(); 8782 8783 if (TAH == Sema::TAH_ConsiderTrivialABI && 8784 (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor)) 8785 return SMOR.getMethod()->isTrivialForCall(); 8786 return SMOR.getMethod()->isTrivial(); 8787 } 8788 8789 llvm_unreachable("unknown special method kind"); 8790 } 8791 8792 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 8793 for (auto *CI : RD->ctors()) 8794 if (!CI->isImplicit()) 8795 return CI; 8796 8797 // Look for constructor templates. 8798 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 8799 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 8800 if (CXXConstructorDecl *CD = 8801 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 8802 return CD; 8803 } 8804 8805 return nullptr; 8806 } 8807 8808 /// The kind of subobject we are checking for triviality. The values of this 8809 /// enumeration are used in diagnostics. 8810 enum TrivialSubobjectKind { 8811 /// The subobject is a base class. 8812 TSK_BaseClass, 8813 /// The subobject is a non-static data member. 8814 TSK_Field, 8815 /// The object is actually the complete object. 8816 TSK_CompleteObject 8817 }; 8818 8819 /// Check whether the special member selected for a given type would be trivial. 8820 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 8821 QualType SubType, bool ConstRHS, 8822 Sema::CXXSpecialMember CSM, 8823 TrivialSubobjectKind Kind, 8824 Sema::TrivialABIHandling TAH, bool Diagnose) { 8825 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 8826 if (!SubRD) 8827 return true; 8828 8829 CXXMethodDecl *Selected; 8830 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 8831 ConstRHS, TAH, Diagnose ? &Selected : nullptr)) 8832 return true; 8833 8834 if (Diagnose) { 8835 if (ConstRHS) 8836 SubType.addConst(); 8837 8838 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 8839 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 8840 << Kind << SubType.getUnqualifiedType(); 8841 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 8842 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 8843 } else if (!Selected) 8844 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 8845 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 8846 else if (Selected->isUserProvided()) { 8847 if (Kind == TSK_CompleteObject) 8848 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 8849 << Kind << SubType.getUnqualifiedType() << CSM; 8850 else { 8851 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 8852 << Kind << SubType.getUnqualifiedType() << CSM; 8853 S.Diag(Selected->getLocation(), diag::note_declared_at); 8854 } 8855 } else { 8856 if (Kind != TSK_CompleteObject) 8857 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 8858 << Kind << SubType.getUnqualifiedType() << CSM; 8859 8860 // Explain why the defaulted or deleted special member isn't trivial. 8861 S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI, 8862 Diagnose); 8863 } 8864 } 8865 8866 return false; 8867 } 8868 8869 /// Check whether the members of a class type allow a special member to be 8870 /// trivial. 8871 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 8872 Sema::CXXSpecialMember CSM, 8873 bool ConstArg, 8874 Sema::TrivialABIHandling TAH, 8875 bool Diagnose) { 8876 for (const auto *FI : RD->fields()) { 8877 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 8878 continue; 8879 8880 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 8881 8882 // Pretend anonymous struct or union members are members of this class. 8883 if (FI->isAnonymousStructOrUnion()) { 8884 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 8885 CSM, ConstArg, TAH, Diagnose)) 8886 return false; 8887 continue; 8888 } 8889 8890 // C++11 [class.ctor]p5: 8891 // A default constructor is trivial if [...] 8892 // -- no non-static data member of its class has a 8893 // brace-or-equal-initializer 8894 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 8895 if (Diagnose) 8896 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI; 8897 return false; 8898 } 8899 8900 // Objective C ARC 4.3.5: 8901 // [...] nontrivally ownership-qualified types are [...] not trivially 8902 // default constructible, copy constructible, move constructible, copy 8903 // assignable, move assignable, or destructible [...] 8904 if (FieldType.hasNonTrivialObjCLifetime()) { 8905 if (Diagnose) 8906 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 8907 << RD << FieldType.getObjCLifetime(); 8908 return false; 8909 } 8910 8911 bool ConstRHS = ConstArg && !FI->isMutable(); 8912 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 8913 CSM, TSK_Field, TAH, Diagnose)) 8914 return false; 8915 } 8916 8917 return true; 8918 } 8919 8920 /// Diagnose why the specified class does not have a trivial special member of 8921 /// the given kind. 8922 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 8923 QualType Ty = Context.getRecordType(RD); 8924 8925 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 8926 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 8927 TSK_CompleteObject, TAH_IgnoreTrivialABI, 8928 /*Diagnose*/true); 8929 } 8930 8931 /// Determine whether a defaulted or deleted special member function is trivial, 8932 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 8933 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 8934 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 8935 TrivialABIHandling TAH, bool Diagnose) { 8936 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 8937 8938 CXXRecordDecl *RD = MD->getParent(); 8939 8940 bool ConstArg = false; 8941 8942 // C++11 [class.copy]p12, p25: [DR1593] 8943 // A [special member] is trivial if [...] its parameter-type-list is 8944 // equivalent to the parameter-type-list of an implicit declaration [...] 8945 switch (CSM) { 8946 case CXXDefaultConstructor: 8947 case CXXDestructor: 8948 // Trivial default constructors and destructors cannot have parameters. 8949 break; 8950 8951 case CXXCopyConstructor: 8952 case CXXCopyAssignment: { 8953 // Trivial copy operations always have const, non-volatile parameter types. 8954 ConstArg = true; 8955 const ParmVarDecl *Param0 = MD->getParamDecl(0); 8956 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 8957 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 8958 if (Diagnose) 8959 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 8960 << Param0->getSourceRange() << Param0->getType() 8961 << Context.getLValueReferenceType( 8962 Context.getRecordType(RD).withConst()); 8963 return false; 8964 } 8965 break; 8966 } 8967 8968 case CXXMoveConstructor: 8969 case CXXMoveAssignment: { 8970 // Trivial move operations always have non-cv-qualified parameters. 8971 const ParmVarDecl *Param0 = MD->getParamDecl(0); 8972 const RValueReferenceType *RT = 8973 Param0->getType()->getAs<RValueReferenceType>(); 8974 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 8975 if (Diagnose) 8976 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 8977 << Param0->getSourceRange() << Param0->getType() 8978 << Context.getRValueReferenceType(Context.getRecordType(RD)); 8979 return false; 8980 } 8981 break; 8982 } 8983 8984 case CXXInvalid: 8985 llvm_unreachable("not a special member"); 8986 } 8987 8988 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 8989 if (Diagnose) 8990 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 8991 diag::note_nontrivial_default_arg) 8992 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 8993 return false; 8994 } 8995 if (MD->isVariadic()) { 8996 if (Diagnose) 8997 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 8998 return false; 8999 } 9000 9001 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 9002 // A copy/move [constructor or assignment operator] is trivial if 9003 // -- the [member] selected to copy/move each direct base class subobject 9004 // is trivial 9005 // 9006 // C++11 [class.copy]p12, C++11 [class.copy]p25: 9007 // A [default constructor or destructor] is trivial if 9008 // -- all the direct base classes have trivial [default constructors or 9009 // destructors] 9010 for (const auto &BI : RD->bases()) 9011 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(), 9012 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose)) 9013 return false; 9014 9015 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 9016 // A copy/move [constructor or assignment operator] for a class X is 9017 // trivial if 9018 // -- for each non-static data member of X that is of class type (or array 9019 // thereof), the constructor selected to copy/move that member is 9020 // trivial 9021 // 9022 // C++11 [class.copy]p12, C++11 [class.copy]p25: 9023 // A [default constructor or destructor] is trivial if 9024 // -- for all of the non-static data members of its class that are of class 9025 // type (or array thereof), each such class has a trivial [default 9026 // constructor or destructor] 9027 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose)) 9028 return false; 9029 9030 // C++11 [class.dtor]p5: 9031 // A destructor is trivial if [...] 9032 // -- the destructor is not virtual 9033 if (CSM == CXXDestructor && MD->isVirtual()) { 9034 if (Diagnose) 9035 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 9036 return false; 9037 } 9038 9039 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 9040 // A [special member] for class X is trivial if [...] 9041 // -- class X has no virtual functions and no virtual base classes 9042 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 9043 if (!Diagnose) 9044 return false; 9045 9046 if (RD->getNumVBases()) { 9047 // Check for virtual bases. We already know that the corresponding 9048 // member in all bases is trivial, so vbases must all be direct. 9049 CXXBaseSpecifier &BS = *RD->vbases_begin(); 9050 assert(BS.isVirtual()); 9051 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1; 9052 return false; 9053 } 9054 9055 // Must have a virtual method. 9056 for (const auto *MI : RD->methods()) { 9057 if (MI->isVirtual()) { 9058 SourceLocation MLoc = MI->getBeginLoc(); 9059 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 9060 return false; 9061 } 9062 } 9063 9064 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 9065 } 9066 9067 // Looks like it's trivial! 9068 return true; 9069 } 9070 9071 namespace { 9072 struct FindHiddenVirtualMethod { 9073 Sema *S; 9074 CXXMethodDecl *Method; 9075 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 9076 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 9077 9078 private: 9079 /// Check whether any most overridden method from MD in Methods 9080 static bool CheckMostOverridenMethods( 9081 const CXXMethodDecl *MD, 9082 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) { 9083 if (MD->size_overridden_methods() == 0) 9084 return Methods.count(MD->getCanonicalDecl()); 9085 for (const CXXMethodDecl *O : MD->overridden_methods()) 9086 if (CheckMostOverridenMethods(O, Methods)) 9087 return true; 9088 return false; 9089 } 9090 9091 public: 9092 /// Member lookup function that determines whether a given C++ 9093 /// method overloads virtual methods in a base class without overriding any, 9094 /// to be used with CXXRecordDecl::lookupInBases(). 9095 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 9096 RecordDecl *BaseRecord = 9097 Specifier->getType()->castAs<RecordType>()->getDecl(); 9098 9099 DeclarationName Name = Method->getDeclName(); 9100 assert(Name.getNameKind() == DeclarationName::Identifier); 9101 9102 bool foundSameNameMethod = false; 9103 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 9104 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 9105 Path.Decls = Path.Decls.slice(1)) { 9106 NamedDecl *D = Path.Decls.front(); 9107 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 9108 MD = MD->getCanonicalDecl(); 9109 foundSameNameMethod = true; 9110 // Interested only in hidden virtual methods. 9111 if (!MD->isVirtual()) 9112 continue; 9113 // If the method we are checking overrides a method from its base 9114 // don't warn about the other overloaded methods. Clang deviates from 9115 // GCC by only diagnosing overloads of inherited virtual functions that 9116 // do not override any other virtual functions in the base. GCC's 9117 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 9118 // function from a base class. These cases may be better served by a 9119 // warning (not specific to virtual functions) on call sites when the 9120 // call would select a different function from the base class, were it 9121 // visible. 9122 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 9123 if (!S->IsOverload(Method, MD, false)) 9124 return true; 9125 // Collect the overload only if its hidden. 9126 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods)) 9127 overloadedMethods.push_back(MD); 9128 } 9129 } 9130 9131 if (foundSameNameMethod) 9132 OverloadedMethods.append(overloadedMethods.begin(), 9133 overloadedMethods.end()); 9134 return foundSameNameMethod; 9135 } 9136 }; 9137 } // end anonymous namespace 9138 9139 /// Add the most overriden methods from MD to Methods 9140 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 9141 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 9142 if (MD->size_overridden_methods() == 0) 9143 Methods.insert(MD->getCanonicalDecl()); 9144 else 9145 for (const CXXMethodDecl *O : MD->overridden_methods()) 9146 AddMostOverridenMethods(O, Methods); 9147 } 9148 9149 /// Check if a method overloads virtual methods in a base class without 9150 /// overriding any. 9151 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 9152 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 9153 if (!MD->getDeclName().isIdentifier()) 9154 return; 9155 9156 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 9157 /*bool RecordPaths=*/false, 9158 /*bool DetectVirtual=*/false); 9159 FindHiddenVirtualMethod FHVM; 9160 FHVM.Method = MD; 9161 FHVM.S = this; 9162 9163 // Keep the base methods that were overridden or introduced in the subclass 9164 // by 'using' in a set. A base method not in this set is hidden. 9165 CXXRecordDecl *DC = MD->getParent(); 9166 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 9167 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 9168 NamedDecl *ND = *I; 9169 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 9170 ND = shad->getTargetDecl(); 9171 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 9172 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods); 9173 } 9174 9175 if (DC->lookupInBases(FHVM, Paths)) 9176 OverloadedMethods = FHVM.OverloadedMethods; 9177 } 9178 9179 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 9180 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 9181 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 9182 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 9183 PartialDiagnostic PD = PDiag( 9184 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 9185 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 9186 Diag(overloadedMD->getLocation(), PD); 9187 } 9188 } 9189 9190 /// Diagnose methods which overload virtual methods in a base class 9191 /// without overriding any. 9192 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 9193 if (MD->isInvalidDecl()) 9194 return; 9195 9196 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 9197 return; 9198 9199 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 9200 FindHiddenVirtualMethods(MD, OverloadedMethods); 9201 if (!OverloadedMethods.empty()) { 9202 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 9203 << MD << (OverloadedMethods.size() > 1); 9204 9205 NoteHiddenVirtualMethods(MD, OverloadedMethods); 9206 } 9207 } 9208 9209 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) { 9210 auto PrintDiagAndRemoveAttr = [&]() { 9211 // No diagnostics if this is a template instantiation. 9212 if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) 9213 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), 9214 diag::ext_cannot_use_trivial_abi) << &RD; 9215 RD.dropAttr<TrivialABIAttr>(); 9216 }; 9217 9218 // Ill-formed if the struct has virtual functions. 9219 if (RD.isPolymorphic()) { 9220 PrintDiagAndRemoveAttr(); 9221 return; 9222 } 9223 9224 for (const auto &B : RD.bases()) { 9225 // Ill-formed if the base class is non-trivial for the purpose of calls or a 9226 // virtual base. 9227 if ((!B.getType()->isDependentType() && 9228 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) || 9229 B.isVirtual()) { 9230 PrintDiagAndRemoveAttr(); 9231 return; 9232 } 9233 } 9234 9235 for (const auto *FD : RD.fields()) { 9236 // Ill-formed if the field is an ObjectiveC pointer or of a type that is 9237 // non-trivial for the purpose of calls. 9238 QualType FT = FD->getType(); 9239 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) { 9240 PrintDiagAndRemoveAttr(); 9241 return; 9242 } 9243 9244 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>()) 9245 if (!RT->isDependentType() && 9246 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) { 9247 PrintDiagAndRemoveAttr(); 9248 return; 9249 } 9250 } 9251 } 9252 9253 void Sema::ActOnFinishCXXMemberSpecification( 9254 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, 9255 SourceLocation RBrac, const ParsedAttributesView &AttrList) { 9256 if (!TagDecl) 9257 return; 9258 9259 AdjustDeclIfTemplate(TagDecl); 9260 9261 for (const ParsedAttr &AL : AttrList) { 9262 if (AL.getKind() != ParsedAttr::AT_Visibility) 9263 continue; 9264 AL.setInvalid(); 9265 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL; 9266 } 9267 9268 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 9269 // strict aliasing violation! 9270 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 9271 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 9272 9273 CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl)); 9274 } 9275 9276 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 9277 /// special functions, such as the default constructor, copy 9278 /// constructor, or destructor, to the given C++ class (C++ 9279 /// [special]p1). This routine can only be executed just before the 9280 /// definition of the class is complete. 9281 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 9282 if (ClassDecl->needsImplicitDefaultConstructor()) { 9283 ++getASTContext().NumImplicitDefaultConstructors; 9284 9285 if (ClassDecl->hasInheritedConstructor()) 9286 DeclareImplicitDefaultConstructor(ClassDecl); 9287 } 9288 9289 if (ClassDecl->needsImplicitCopyConstructor()) { 9290 ++getASTContext().NumImplicitCopyConstructors; 9291 9292 // If the properties or semantics of the copy constructor couldn't be 9293 // determined while the class was being declared, force a declaration 9294 // of it now. 9295 if (ClassDecl->needsOverloadResolutionForCopyConstructor() || 9296 ClassDecl->hasInheritedConstructor()) 9297 DeclareImplicitCopyConstructor(ClassDecl); 9298 // For the MS ABI we need to know whether the copy ctor is deleted. A 9299 // prerequisite for deleting the implicit copy ctor is that the class has a 9300 // move ctor or move assignment that is either user-declared or whose 9301 // semantics are inherited from a subobject. FIXME: We should provide a more 9302 // direct way for CodeGen to ask whether the constructor was deleted. 9303 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 9304 (ClassDecl->hasUserDeclaredMoveConstructor() || 9305 ClassDecl->needsOverloadResolutionForMoveConstructor() || 9306 ClassDecl->hasUserDeclaredMoveAssignment() || 9307 ClassDecl->needsOverloadResolutionForMoveAssignment())) 9308 DeclareImplicitCopyConstructor(ClassDecl); 9309 } 9310 9311 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 9312 ++getASTContext().NumImplicitMoveConstructors; 9313 9314 if (ClassDecl->needsOverloadResolutionForMoveConstructor() || 9315 ClassDecl->hasInheritedConstructor()) 9316 DeclareImplicitMoveConstructor(ClassDecl); 9317 } 9318 9319 if (ClassDecl->needsImplicitCopyAssignment()) { 9320 ++getASTContext().NumImplicitCopyAssignmentOperators; 9321 9322 // If we have a dynamic class, then the copy assignment operator may be 9323 // virtual, so we have to declare it immediately. This ensures that, e.g., 9324 // it shows up in the right place in the vtable and that we diagnose 9325 // problems with the implicit exception specification. 9326 if (ClassDecl->isDynamicClass() || 9327 ClassDecl->needsOverloadResolutionForCopyAssignment() || 9328 ClassDecl->hasInheritedAssignment()) 9329 DeclareImplicitCopyAssignment(ClassDecl); 9330 } 9331 9332 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 9333 ++getASTContext().NumImplicitMoveAssignmentOperators; 9334 9335 // Likewise for the move assignment operator. 9336 if (ClassDecl->isDynamicClass() || 9337 ClassDecl->needsOverloadResolutionForMoveAssignment() || 9338 ClassDecl->hasInheritedAssignment()) 9339 DeclareImplicitMoveAssignment(ClassDecl); 9340 } 9341 9342 if (ClassDecl->needsImplicitDestructor()) { 9343 ++getASTContext().NumImplicitDestructors; 9344 9345 // If we have a dynamic class, then the destructor may be virtual, so we 9346 // have to declare the destructor immediately. This ensures that, e.g., it 9347 // shows up in the right place in the vtable and that we diagnose problems 9348 // with the implicit exception specification. 9349 if (ClassDecl->isDynamicClass() || 9350 ClassDecl->needsOverloadResolutionForDestructor()) 9351 DeclareImplicitDestructor(ClassDecl); 9352 } 9353 } 9354 9355 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 9356 if (!D) 9357 return 0; 9358 9359 // The order of template parameters is not important here. All names 9360 // get added to the same scope. 9361 SmallVector<TemplateParameterList *, 4> ParameterLists; 9362 9363 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 9364 D = TD->getTemplatedDecl(); 9365 9366 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 9367 ParameterLists.push_back(PSD->getTemplateParameters()); 9368 9369 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 9370 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 9371 ParameterLists.push_back(DD->getTemplateParameterList(i)); 9372 9373 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 9374 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 9375 ParameterLists.push_back(FTD->getTemplateParameters()); 9376 } 9377 } 9378 9379 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 9380 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 9381 ParameterLists.push_back(TD->getTemplateParameterList(i)); 9382 9383 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 9384 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 9385 ParameterLists.push_back(CTD->getTemplateParameters()); 9386 } 9387 } 9388 9389 unsigned Count = 0; 9390 for (TemplateParameterList *Params : ParameterLists) { 9391 if (Params->size() > 0) 9392 // Ignore explicit specializations; they don't contribute to the template 9393 // depth. 9394 ++Count; 9395 for (NamedDecl *Param : *Params) { 9396 if (Param->getDeclName()) { 9397 S->AddDecl(Param); 9398 IdResolver.AddDecl(Param); 9399 } 9400 } 9401 } 9402 9403 return Count; 9404 } 9405 9406 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 9407 if (!RecordD) return; 9408 AdjustDeclIfTemplate(RecordD); 9409 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 9410 PushDeclContext(S, Record); 9411 } 9412 9413 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 9414 if (!RecordD) return; 9415 PopDeclContext(); 9416 } 9417 9418 /// This is used to implement the constant expression evaluation part of the 9419 /// attribute enable_if extension. There is nothing in standard C++ which would 9420 /// require reentering parameters. 9421 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 9422 if (!Param) 9423 return; 9424 9425 S->AddDecl(Param); 9426 if (Param->getDeclName()) 9427 IdResolver.AddDecl(Param); 9428 } 9429 9430 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 9431 /// parsing a top-level (non-nested) C++ class, and we are now 9432 /// parsing those parts of the given Method declaration that could 9433 /// not be parsed earlier (C++ [class.mem]p2), such as default 9434 /// arguments. This action should enter the scope of the given 9435 /// Method declaration as if we had just parsed the qualified method 9436 /// name. However, it should not bring the parameters into scope; 9437 /// that will be performed by ActOnDelayedCXXMethodParameter. 9438 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 9439 } 9440 9441 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 9442 /// C++ method declaration. We're (re-)introducing the given 9443 /// function parameter into scope for use in parsing later parts of 9444 /// the method declaration. For example, we could see an 9445 /// ActOnParamDefaultArgument event for this parameter. 9446 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 9447 if (!ParamD) 9448 return; 9449 9450 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 9451 9452 // If this parameter has an unparsed default argument, clear it out 9453 // to make way for the parsed default argument. 9454 if (Param->hasUnparsedDefaultArg()) 9455 Param->setDefaultArg(nullptr); 9456 9457 S->AddDecl(Param); 9458 if (Param->getDeclName()) 9459 IdResolver.AddDecl(Param); 9460 } 9461 9462 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 9463 /// processing the delayed method declaration for Method. The method 9464 /// declaration is now considered finished. There may be a separate 9465 /// ActOnStartOfFunctionDef action later (not necessarily 9466 /// immediately!) for this method, if it was also defined inside the 9467 /// class body. 9468 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 9469 if (!MethodD) 9470 return; 9471 9472 AdjustDeclIfTemplate(MethodD); 9473 9474 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 9475 9476 // Now that we have our default arguments, check the constructor 9477 // again. It could produce additional diagnostics or affect whether 9478 // the class has implicitly-declared destructors, among other 9479 // things. 9480 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 9481 CheckConstructor(Constructor); 9482 9483 // Check the default arguments, which we may have added. 9484 if (!Method->isInvalidDecl()) 9485 CheckCXXDefaultArguments(Method); 9486 } 9487 9488 // Emit the given diagnostic for each non-address-space qualifier. 9489 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator. 9490 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) { 9491 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 9492 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) { 9493 bool DiagOccured = false; 9494 FTI.MethodQualifiers->forEachQualifier( 9495 [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName, 9496 SourceLocation SL) { 9497 // This diagnostic should be emitted on any qualifier except an addr 9498 // space qualifier. However, forEachQualifier currently doesn't visit 9499 // addr space qualifiers, so there's no way to write this condition 9500 // right now; we just diagnose on everything. 9501 S.Diag(SL, DiagID) << QualName << SourceRange(SL); 9502 DiagOccured = true; 9503 }); 9504 if (DiagOccured) 9505 D.setInvalidType(); 9506 } 9507 } 9508 9509 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 9510 /// the well-formedness of the constructor declarator @p D with type @p 9511 /// R. If there are any errors in the declarator, this routine will 9512 /// emit diagnostics and set the invalid bit to true. In any case, the type 9513 /// will be updated to reflect a well-formed type for the constructor and 9514 /// returned. 9515 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 9516 StorageClass &SC) { 9517 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 9518 9519 // C++ [class.ctor]p3: 9520 // A constructor shall not be virtual (10.3) or static (9.4). A 9521 // constructor can be invoked for a const, volatile or const 9522 // volatile object. A constructor shall not be declared const, 9523 // volatile, or const volatile (9.3.2). 9524 if (isVirtual) { 9525 if (!D.isInvalidType()) 9526 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 9527 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 9528 << SourceRange(D.getIdentifierLoc()); 9529 D.setInvalidType(); 9530 } 9531 if (SC == SC_Static) { 9532 if (!D.isInvalidType()) 9533 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 9534 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 9535 << SourceRange(D.getIdentifierLoc()); 9536 D.setInvalidType(); 9537 SC = SC_None; 9538 } 9539 9540 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 9541 diagnoseIgnoredQualifiers( 9542 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 9543 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 9544 D.getDeclSpec().getRestrictSpecLoc(), 9545 D.getDeclSpec().getAtomicSpecLoc()); 9546 D.setInvalidType(); 9547 } 9548 9549 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor); 9550 9551 // C++0x [class.ctor]p4: 9552 // A constructor shall not be declared with a ref-qualifier. 9553 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 9554 if (FTI.hasRefQualifier()) { 9555 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 9556 << FTI.RefQualifierIsLValueRef 9557 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 9558 D.setInvalidType(); 9559 } 9560 9561 // Rebuild the function type "R" without any type qualifiers (in 9562 // case any of the errors above fired) and with "void" as the 9563 // return type, since constructors don't have return types. 9564 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 9565 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 9566 return R; 9567 9568 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 9569 EPI.TypeQuals = Qualifiers(); 9570 EPI.RefQualifier = RQ_None; 9571 9572 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 9573 } 9574 9575 /// CheckConstructor - Checks a fully-formed constructor for 9576 /// well-formedness, issuing any diagnostics required. Returns true if 9577 /// the constructor declarator is invalid. 9578 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 9579 CXXRecordDecl *ClassDecl 9580 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 9581 if (!ClassDecl) 9582 return Constructor->setInvalidDecl(); 9583 9584 // C++ [class.copy]p3: 9585 // A declaration of a constructor for a class X is ill-formed if 9586 // its first parameter is of type (optionally cv-qualified) X and 9587 // either there are no other parameters or else all other 9588 // parameters have default arguments. 9589 if (!Constructor->isInvalidDecl() && 9590 ((Constructor->getNumParams() == 1) || 9591 (Constructor->getNumParams() > 1 && 9592 Constructor->getParamDecl(1)->hasDefaultArg())) && 9593 Constructor->getTemplateSpecializationKind() 9594 != TSK_ImplicitInstantiation) { 9595 QualType ParamType = Constructor->getParamDecl(0)->getType(); 9596 QualType ClassTy = Context.getTagDeclType(ClassDecl); 9597 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 9598 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 9599 const char *ConstRef 9600 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 9601 : " const &"; 9602 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 9603 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 9604 9605 // FIXME: Rather that making the constructor invalid, we should endeavor 9606 // to fix the type. 9607 Constructor->setInvalidDecl(); 9608 } 9609 } 9610 } 9611 9612 /// CheckDestructor - Checks a fully-formed destructor definition for 9613 /// well-formedness, issuing any diagnostics required. Returns true 9614 /// on error. 9615 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 9616 CXXRecordDecl *RD = Destructor->getParent(); 9617 9618 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 9619 SourceLocation Loc; 9620 9621 if (!Destructor->isImplicit()) 9622 Loc = Destructor->getLocation(); 9623 else 9624 Loc = RD->getLocation(); 9625 9626 // If we have a virtual destructor, look up the deallocation function 9627 if (FunctionDecl *OperatorDelete = 9628 FindDeallocationFunctionForDestructor(Loc, RD)) { 9629 Expr *ThisArg = nullptr; 9630 9631 // If the notional 'delete this' expression requires a non-trivial 9632 // conversion from 'this' to the type of a destroying operator delete's 9633 // first parameter, perform that conversion now. 9634 if (OperatorDelete->isDestroyingOperatorDelete()) { 9635 QualType ParamType = OperatorDelete->getParamDecl(0)->getType(); 9636 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) { 9637 // C++ [class.dtor]p13: 9638 // ... as if for the expression 'delete this' appearing in a 9639 // non-virtual destructor of the destructor's class. 9640 ContextRAII SwitchContext(*this, Destructor); 9641 ExprResult This = 9642 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation()); 9643 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?"); 9644 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing); 9645 if (This.isInvalid()) { 9646 // FIXME: Register this as a context note so that it comes out 9647 // in the right order. 9648 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here); 9649 return true; 9650 } 9651 ThisArg = This.get(); 9652 } 9653 } 9654 9655 DiagnoseUseOfDecl(OperatorDelete, Loc); 9656 MarkFunctionReferenced(Loc, OperatorDelete); 9657 Destructor->setOperatorDelete(OperatorDelete, ThisArg); 9658 } 9659 } 9660 9661 return false; 9662 } 9663 9664 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 9665 /// the well-formednes of the destructor declarator @p D with type @p 9666 /// R. If there are any errors in the declarator, this routine will 9667 /// emit diagnostics and set the declarator to invalid. Even if this happens, 9668 /// will be updated to reflect a well-formed type for the destructor and 9669 /// returned. 9670 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 9671 StorageClass& SC) { 9672 // C++ [class.dtor]p1: 9673 // [...] A typedef-name that names a class is a class-name 9674 // (7.1.3); however, a typedef-name that names a class shall not 9675 // be used as the identifier in the declarator for a destructor 9676 // declaration. 9677 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 9678 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 9679 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 9680 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 9681 else if (const TemplateSpecializationType *TST = 9682 DeclaratorType->getAs<TemplateSpecializationType>()) 9683 if (TST->isTypeAlias()) 9684 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 9685 << DeclaratorType << 1; 9686 9687 // C++ [class.dtor]p2: 9688 // A destructor is used to destroy objects of its class type. A 9689 // destructor takes no parameters, and no return type can be 9690 // specified for it (not even void). The address of a destructor 9691 // shall not be taken. A destructor shall not be static. A 9692 // destructor can be invoked for a const, volatile or const 9693 // volatile object. A destructor shall not be declared const, 9694 // volatile or const volatile (9.3.2). 9695 if (SC == SC_Static) { 9696 if (!D.isInvalidType()) 9697 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 9698 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 9699 << SourceRange(D.getIdentifierLoc()) 9700 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 9701 9702 SC = SC_None; 9703 } 9704 if (!D.isInvalidType()) { 9705 // Destructors don't have return types, but the parser will 9706 // happily parse something like: 9707 // 9708 // class X { 9709 // float ~X(); 9710 // }; 9711 // 9712 // The return type will be eliminated later. 9713 if (D.getDeclSpec().hasTypeSpecifier()) 9714 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 9715 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 9716 << SourceRange(D.getIdentifierLoc()); 9717 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 9718 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 9719 SourceLocation(), 9720 D.getDeclSpec().getConstSpecLoc(), 9721 D.getDeclSpec().getVolatileSpecLoc(), 9722 D.getDeclSpec().getRestrictSpecLoc(), 9723 D.getDeclSpec().getAtomicSpecLoc()); 9724 D.setInvalidType(); 9725 } 9726 } 9727 9728 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor); 9729 9730 // C++0x [class.dtor]p2: 9731 // A destructor shall not be declared with a ref-qualifier. 9732 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 9733 if (FTI.hasRefQualifier()) { 9734 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 9735 << FTI.RefQualifierIsLValueRef 9736 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 9737 D.setInvalidType(); 9738 } 9739 9740 // Make sure we don't have any parameters. 9741 if (FTIHasNonVoidParameters(FTI)) { 9742 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 9743 9744 // Delete the parameters. 9745 FTI.freeParams(); 9746 D.setInvalidType(); 9747 } 9748 9749 // Make sure the destructor isn't variadic. 9750 if (FTI.isVariadic) { 9751 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 9752 D.setInvalidType(); 9753 } 9754 9755 // Rebuild the function type "R" without any type qualifiers or 9756 // parameters (in case any of the errors above fired) and with 9757 // "void" as the return type, since destructors don't have return 9758 // types. 9759 if (!D.isInvalidType()) 9760 return R; 9761 9762 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 9763 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 9764 EPI.Variadic = false; 9765 EPI.TypeQuals = Qualifiers(); 9766 EPI.RefQualifier = RQ_None; 9767 return Context.getFunctionType(Context.VoidTy, None, EPI); 9768 } 9769 9770 static void extendLeft(SourceRange &R, SourceRange Before) { 9771 if (Before.isInvalid()) 9772 return; 9773 R.setBegin(Before.getBegin()); 9774 if (R.getEnd().isInvalid()) 9775 R.setEnd(Before.getEnd()); 9776 } 9777 9778 static void extendRight(SourceRange &R, SourceRange After) { 9779 if (After.isInvalid()) 9780 return; 9781 if (R.getBegin().isInvalid()) 9782 R.setBegin(After.getBegin()); 9783 R.setEnd(After.getEnd()); 9784 } 9785 9786 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 9787 /// well-formednes of the conversion function declarator @p D with 9788 /// type @p R. If there are any errors in the declarator, this routine 9789 /// will emit diagnostics and return true. Otherwise, it will return 9790 /// false. Either way, the type @p R will be updated to reflect a 9791 /// well-formed type for the conversion operator. 9792 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 9793 StorageClass& SC) { 9794 // C++ [class.conv.fct]p1: 9795 // Neither parameter types nor return type can be specified. The 9796 // type of a conversion function (8.3.5) is "function taking no 9797 // parameter returning conversion-type-id." 9798 if (SC == SC_Static) { 9799 if (!D.isInvalidType()) 9800 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 9801 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 9802 << D.getName().getSourceRange(); 9803 D.setInvalidType(); 9804 SC = SC_None; 9805 } 9806 9807 TypeSourceInfo *ConvTSI = nullptr; 9808 QualType ConvType = 9809 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); 9810 9811 const DeclSpec &DS = D.getDeclSpec(); 9812 if (DS.hasTypeSpecifier() && !D.isInvalidType()) { 9813 // Conversion functions don't have return types, but the parser will 9814 // happily parse something like: 9815 // 9816 // class X { 9817 // float operator bool(); 9818 // }; 9819 // 9820 // The return type will be changed later anyway. 9821 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 9822 << SourceRange(DS.getTypeSpecTypeLoc()) 9823 << SourceRange(D.getIdentifierLoc()); 9824 D.setInvalidType(); 9825 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) { 9826 // It's also plausible that the user writes type qualifiers in the wrong 9827 // place, such as: 9828 // struct S { const operator int(); }; 9829 // FIXME: we could provide a fixit to move the qualifiers onto the 9830 // conversion type. 9831 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 9832 << SourceRange(D.getIdentifierLoc()) << 0; 9833 D.setInvalidType(); 9834 } 9835 9836 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 9837 9838 // Make sure we don't have any parameters. 9839 if (Proto->getNumParams() > 0) { 9840 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 9841 9842 // Delete the parameters. 9843 D.getFunctionTypeInfo().freeParams(); 9844 D.setInvalidType(); 9845 } else if (Proto->isVariadic()) { 9846 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 9847 D.setInvalidType(); 9848 } 9849 9850 // Diagnose "&operator bool()" and other such nonsense. This 9851 // is actually a gcc extension which we don't support. 9852 if (Proto->getReturnType() != ConvType) { 9853 bool NeedsTypedef = false; 9854 SourceRange Before, After; 9855 9856 // Walk the chunks and extract information on them for our diagnostic. 9857 bool PastFunctionChunk = false; 9858 for (auto &Chunk : D.type_objects()) { 9859 switch (Chunk.Kind) { 9860 case DeclaratorChunk::Function: 9861 if (!PastFunctionChunk) { 9862 if (Chunk.Fun.HasTrailingReturnType) { 9863 TypeSourceInfo *TRT = nullptr; 9864 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); 9865 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); 9866 } 9867 PastFunctionChunk = true; 9868 break; 9869 } 9870 LLVM_FALLTHROUGH; 9871 case DeclaratorChunk::Array: 9872 NeedsTypedef = true; 9873 extendRight(After, Chunk.getSourceRange()); 9874 break; 9875 9876 case DeclaratorChunk::Pointer: 9877 case DeclaratorChunk::BlockPointer: 9878 case DeclaratorChunk::Reference: 9879 case DeclaratorChunk::MemberPointer: 9880 case DeclaratorChunk::Pipe: 9881 extendLeft(Before, Chunk.getSourceRange()); 9882 break; 9883 9884 case DeclaratorChunk::Paren: 9885 extendLeft(Before, Chunk.Loc); 9886 extendRight(After, Chunk.EndLoc); 9887 break; 9888 } 9889 } 9890 9891 SourceLocation Loc = Before.isValid() ? Before.getBegin() : 9892 After.isValid() ? After.getBegin() : 9893 D.getIdentifierLoc(); 9894 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); 9895 DB << Before << After; 9896 9897 if (!NeedsTypedef) { 9898 DB << /*don't need a typedef*/0; 9899 9900 // If we can provide a correct fix-it hint, do so. 9901 if (After.isInvalid() && ConvTSI) { 9902 SourceLocation InsertLoc = 9903 getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc()); 9904 DB << FixItHint::CreateInsertion(InsertLoc, " ") 9905 << FixItHint::CreateInsertionFromRange( 9906 InsertLoc, CharSourceRange::getTokenRange(Before)) 9907 << FixItHint::CreateRemoval(Before); 9908 } 9909 } else if (!Proto->getReturnType()->isDependentType()) { 9910 DB << /*typedef*/1 << Proto->getReturnType(); 9911 } else if (getLangOpts().CPlusPlus11) { 9912 DB << /*alias template*/2 << Proto->getReturnType(); 9913 } else { 9914 DB << /*might not be fixable*/3; 9915 } 9916 9917 // Recover by incorporating the other type chunks into the result type. 9918 // Note, this does *not* change the name of the function. This is compatible 9919 // with the GCC extension: 9920 // struct S { &operator int(); } s; 9921 // int &r = s.operator int(); // ok in GCC 9922 // S::operator int&() {} // error in GCC, function name is 'operator int'. 9923 ConvType = Proto->getReturnType(); 9924 } 9925 9926 // C++ [class.conv.fct]p4: 9927 // The conversion-type-id shall not represent a function type nor 9928 // an array type. 9929 if (ConvType->isArrayType()) { 9930 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 9931 ConvType = Context.getPointerType(ConvType); 9932 D.setInvalidType(); 9933 } else if (ConvType->isFunctionType()) { 9934 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 9935 ConvType = Context.getPointerType(ConvType); 9936 D.setInvalidType(); 9937 } 9938 9939 // Rebuild the function type "R" without any parameters (in case any 9940 // of the errors above fired) and with the conversion type as the 9941 // return type. 9942 if (D.isInvalidType()) 9943 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 9944 9945 // C++0x explicit conversion operators. 9946 if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus2a) 9947 Diag(DS.getExplicitSpecLoc(), 9948 getLangOpts().CPlusPlus11 9949 ? diag::warn_cxx98_compat_explicit_conversion_functions 9950 : diag::ext_explicit_conversion_functions) 9951 << SourceRange(DS.getExplicitSpecRange()); 9952 } 9953 9954 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 9955 /// the declaration of the given C++ conversion function. This routine 9956 /// is responsible for recording the conversion function in the C++ 9957 /// class, if possible. 9958 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 9959 assert(Conversion && "Expected to receive a conversion function declaration"); 9960 9961 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 9962 9963 // Make sure we aren't redeclaring the conversion function. 9964 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 9965 9966 // C++ [class.conv.fct]p1: 9967 // [...] A conversion function is never used to convert a 9968 // (possibly cv-qualified) object to the (possibly cv-qualified) 9969 // same object type (or a reference to it), to a (possibly 9970 // cv-qualified) base class of that type (or a reference to it), 9971 // or to (possibly cv-qualified) void. 9972 // FIXME: Suppress this warning if the conversion function ends up being a 9973 // virtual function that overrides a virtual function in a base class. 9974 QualType ClassType 9975 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 9976 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 9977 ConvType = ConvTypeRef->getPointeeType(); 9978 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 9979 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 9980 /* Suppress diagnostics for instantiations. */; 9981 else if (ConvType->isRecordType()) { 9982 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 9983 if (ConvType == ClassType) 9984 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 9985 << ClassType; 9986 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType)) 9987 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 9988 << ClassType << ConvType; 9989 } else if (ConvType->isVoidType()) { 9990 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 9991 << ClassType << ConvType; 9992 } 9993 9994 if (FunctionTemplateDecl *ConversionTemplate 9995 = Conversion->getDescribedFunctionTemplate()) 9996 return ConversionTemplate; 9997 9998 return Conversion; 9999 } 10000 10001 namespace { 10002 /// Utility class to accumulate and print a diagnostic listing the invalid 10003 /// specifier(s) on a declaration. 10004 struct BadSpecifierDiagnoser { 10005 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID) 10006 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {} 10007 ~BadSpecifierDiagnoser() { 10008 Diagnostic << Specifiers; 10009 } 10010 10011 template<typename T> void check(SourceLocation SpecLoc, T Spec) { 10012 return check(SpecLoc, DeclSpec::getSpecifierName(Spec)); 10013 } 10014 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) { 10015 return check(SpecLoc, 10016 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy())); 10017 } 10018 void check(SourceLocation SpecLoc, const char *Spec) { 10019 if (SpecLoc.isInvalid()) return; 10020 Diagnostic << SourceRange(SpecLoc, SpecLoc); 10021 if (!Specifiers.empty()) Specifiers += " "; 10022 Specifiers += Spec; 10023 } 10024 10025 Sema &S; 10026 Sema::SemaDiagnosticBuilder Diagnostic; 10027 std::string Specifiers; 10028 }; 10029 } 10030 10031 /// Check the validity of a declarator that we parsed for a deduction-guide. 10032 /// These aren't actually declarators in the grammar, so we need to check that 10033 /// the user didn't specify any pieces that are not part of the deduction-guide 10034 /// grammar. 10035 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R, 10036 StorageClass &SC) { 10037 TemplateName GuidedTemplate = D.getName().TemplateName.get().get(); 10038 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl(); 10039 assert(GuidedTemplateDecl && "missing template decl for deduction guide"); 10040 10041 // C++ [temp.deduct.guide]p3: 10042 // A deduction-gide shall be declared in the same scope as the 10043 // corresponding class template. 10044 if (!CurContext->getRedeclContext()->Equals( 10045 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) { 10046 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope) 10047 << GuidedTemplateDecl; 10048 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here); 10049 } 10050 10051 auto &DS = D.getMutableDeclSpec(); 10052 // We leave 'friend' and 'virtual' to be rejected in the normal way. 10053 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() || 10054 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() || 10055 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) { 10056 BadSpecifierDiagnoser Diagnoser( 10057 *this, D.getIdentifierLoc(), 10058 diag::err_deduction_guide_invalid_specifier); 10059 10060 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec()); 10061 DS.ClearStorageClassSpecs(); 10062 SC = SC_None; 10063 10064 // 'explicit' is permitted. 10065 Diagnoser.check(DS.getInlineSpecLoc(), "inline"); 10066 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn"); 10067 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr"); 10068 DS.ClearConstexprSpec(); 10069 10070 Diagnoser.check(DS.getConstSpecLoc(), "const"); 10071 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict"); 10072 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile"); 10073 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic"); 10074 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned"); 10075 DS.ClearTypeQualifiers(); 10076 10077 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex()); 10078 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign()); 10079 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth()); 10080 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType()); 10081 DS.ClearTypeSpecType(); 10082 } 10083 10084 if (D.isInvalidType()) 10085 return; 10086 10087 // Check the declarator is simple enough. 10088 bool FoundFunction = false; 10089 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) { 10090 if (Chunk.Kind == DeclaratorChunk::Paren) 10091 continue; 10092 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) { 10093 Diag(D.getDeclSpec().getBeginLoc(), 10094 diag::err_deduction_guide_with_complex_decl) 10095 << D.getSourceRange(); 10096 break; 10097 } 10098 if (!Chunk.Fun.hasTrailingReturnType()) { 10099 Diag(D.getName().getBeginLoc(), 10100 diag::err_deduction_guide_no_trailing_return_type); 10101 break; 10102 } 10103 10104 // Check that the return type is written as a specialization of 10105 // the template specified as the deduction-guide's name. 10106 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType(); 10107 TypeSourceInfo *TSI = nullptr; 10108 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI); 10109 assert(TSI && "deduction guide has valid type but invalid return type?"); 10110 bool AcceptableReturnType = false; 10111 bool MightInstantiateToSpecialization = false; 10112 if (auto RetTST = 10113 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) { 10114 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName(); 10115 bool TemplateMatches = 10116 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate); 10117 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches) 10118 AcceptableReturnType = true; 10119 else { 10120 // This could still instantiate to the right type, unless we know it 10121 // names the wrong class template. 10122 auto *TD = SpecifiedName.getAsTemplateDecl(); 10123 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) && 10124 !TemplateMatches); 10125 } 10126 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) { 10127 MightInstantiateToSpecialization = true; 10128 } 10129 10130 if (!AcceptableReturnType) { 10131 Diag(TSI->getTypeLoc().getBeginLoc(), 10132 diag::err_deduction_guide_bad_trailing_return_type) 10133 << GuidedTemplate << TSI->getType() 10134 << MightInstantiateToSpecialization 10135 << TSI->getTypeLoc().getSourceRange(); 10136 } 10137 10138 // Keep going to check that we don't have any inner declarator pieces (we 10139 // could still have a function returning a pointer to a function). 10140 FoundFunction = true; 10141 } 10142 10143 if (D.isFunctionDefinition()) 10144 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function); 10145 } 10146 10147 //===----------------------------------------------------------------------===// 10148 // Namespace Handling 10149 //===----------------------------------------------------------------------===// 10150 10151 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is 10152 /// reopened. 10153 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 10154 SourceLocation Loc, 10155 IdentifierInfo *II, bool *IsInline, 10156 NamespaceDecl *PrevNS) { 10157 assert(*IsInline != PrevNS->isInline()); 10158 10159 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 10160 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 10161 // inline namespaces, with the intention of bringing names into namespace std. 10162 // 10163 // We support this just well enough to get that case working; this is not 10164 // sufficient to support reopening namespaces as inline in general. 10165 if (*IsInline && II && II->getName().startswith("__atomic") && 10166 S.getSourceManager().isInSystemHeader(Loc)) { 10167 // Mark all prior declarations of the namespace as inline. 10168 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 10169 NS = NS->getPreviousDecl()) 10170 NS->setInline(*IsInline); 10171 // Patch up the lookup table for the containing namespace. This isn't really 10172 // correct, but it's good enough for this particular case. 10173 for (auto *I : PrevNS->decls()) 10174 if (auto *ND = dyn_cast<NamedDecl>(I)) 10175 PrevNS->getParent()->makeDeclVisibleInContext(ND); 10176 return; 10177 } 10178 10179 if (PrevNS->isInline()) 10180 // The user probably just forgot the 'inline', so suggest that it 10181 // be added back. 10182 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 10183 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 10184 else 10185 S.Diag(Loc, diag::err_inline_namespace_mismatch); 10186 10187 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 10188 *IsInline = PrevNS->isInline(); 10189 } 10190 10191 /// ActOnStartNamespaceDef - This is called at the start of a namespace 10192 /// definition. 10193 Decl *Sema::ActOnStartNamespaceDef( 10194 Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc, 10195 SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace, 10196 const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) { 10197 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 10198 // For anonymous namespace, take the location of the left brace. 10199 SourceLocation Loc = II ? IdentLoc : LBrace; 10200 bool IsInline = InlineLoc.isValid(); 10201 bool IsInvalid = false; 10202 bool IsStd = false; 10203 bool AddToKnown = false; 10204 Scope *DeclRegionScope = NamespcScope->getParent(); 10205 10206 NamespaceDecl *PrevNS = nullptr; 10207 if (II) { 10208 // C++ [namespace.def]p2: 10209 // The identifier in an original-namespace-definition shall not 10210 // have been previously defined in the declarative region in 10211 // which the original-namespace-definition appears. The 10212 // identifier in an original-namespace-definition is the name of 10213 // the namespace. Subsequently in that declarative region, it is 10214 // treated as an original-namespace-name. 10215 // 10216 // Since namespace names are unique in their scope, and we don't 10217 // look through using directives, just look for any ordinary names 10218 // as if by qualified name lookup. 10219 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, 10220 ForExternalRedeclaration); 10221 LookupQualifiedName(R, CurContext->getRedeclContext()); 10222 NamedDecl *PrevDecl = 10223 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr; 10224 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 10225 10226 if (PrevNS) { 10227 // This is an extended namespace definition. 10228 if (IsInline != PrevNS->isInline()) 10229 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 10230 &IsInline, PrevNS); 10231 } else if (PrevDecl) { 10232 // This is an invalid name redefinition. 10233 Diag(Loc, diag::err_redefinition_different_kind) 10234 << II; 10235 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 10236 IsInvalid = true; 10237 // Continue on to push Namespc as current DeclContext and return it. 10238 } else if (II->isStr("std") && 10239 CurContext->getRedeclContext()->isTranslationUnit()) { 10240 // This is the first "real" definition of the namespace "std", so update 10241 // our cache of the "std" namespace to point at this definition. 10242 PrevNS = getStdNamespace(); 10243 IsStd = true; 10244 AddToKnown = !IsInline; 10245 } else { 10246 // We've seen this namespace for the first time. 10247 AddToKnown = !IsInline; 10248 } 10249 } else { 10250 // Anonymous namespaces. 10251 10252 // Determine whether the parent already has an anonymous namespace. 10253 DeclContext *Parent = CurContext->getRedeclContext(); 10254 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 10255 PrevNS = TU->getAnonymousNamespace(); 10256 } else { 10257 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 10258 PrevNS = ND->getAnonymousNamespace(); 10259 } 10260 10261 if (PrevNS && IsInline != PrevNS->isInline()) 10262 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 10263 &IsInline, PrevNS); 10264 } 10265 10266 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 10267 StartLoc, Loc, II, PrevNS); 10268 if (IsInvalid) 10269 Namespc->setInvalidDecl(); 10270 10271 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 10272 AddPragmaAttributes(DeclRegionScope, Namespc); 10273 10274 // FIXME: Should we be merging attributes? 10275 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 10276 PushNamespaceVisibilityAttr(Attr, Loc); 10277 10278 if (IsStd) 10279 StdNamespace = Namespc; 10280 if (AddToKnown) 10281 KnownNamespaces[Namespc] = false; 10282 10283 if (II) { 10284 PushOnScopeChains(Namespc, DeclRegionScope); 10285 } else { 10286 // Link the anonymous namespace into its parent. 10287 DeclContext *Parent = CurContext->getRedeclContext(); 10288 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 10289 TU->setAnonymousNamespace(Namespc); 10290 } else { 10291 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 10292 } 10293 10294 CurContext->addDecl(Namespc); 10295 10296 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 10297 // behaves as if it were replaced by 10298 // namespace unique { /* empty body */ } 10299 // using namespace unique; 10300 // namespace unique { namespace-body } 10301 // where all occurrences of 'unique' in a translation unit are 10302 // replaced by the same identifier and this identifier differs 10303 // from all other identifiers in the entire program. 10304 10305 // We just create the namespace with an empty name and then add an 10306 // implicit using declaration, just like the standard suggests. 10307 // 10308 // CodeGen enforces the "universally unique" aspect by giving all 10309 // declarations semantically contained within an anonymous 10310 // namespace internal linkage. 10311 10312 if (!PrevNS) { 10313 UD = UsingDirectiveDecl::Create(Context, Parent, 10314 /* 'using' */ LBrace, 10315 /* 'namespace' */ SourceLocation(), 10316 /* qualifier */ NestedNameSpecifierLoc(), 10317 /* identifier */ SourceLocation(), 10318 Namespc, 10319 /* Ancestor */ Parent); 10320 UD->setImplicit(); 10321 Parent->addDecl(UD); 10322 } 10323 } 10324 10325 ActOnDocumentableDecl(Namespc); 10326 10327 // Although we could have an invalid decl (i.e. the namespace name is a 10328 // redefinition), push it as current DeclContext and try to continue parsing. 10329 // FIXME: We should be able to push Namespc here, so that the each DeclContext 10330 // for the namespace has the declarations that showed up in that particular 10331 // namespace definition. 10332 PushDeclContext(NamespcScope, Namespc); 10333 return Namespc; 10334 } 10335 10336 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 10337 /// is a namespace alias, returns the namespace it points to. 10338 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 10339 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 10340 return AD->getNamespace(); 10341 return dyn_cast_or_null<NamespaceDecl>(D); 10342 } 10343 10344 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 10345 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 10346 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 10347 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 10348 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 10349 Namespc->setRBraceLoc(RBrace); 10350 PopDeclContext(); 10351 if (Namespc->hasAttr<VisibilityAttr>()) 10352 PopPragmaVisibility(true, RBrace); 10353 // If this namespace contains an export-declaration, export it now. 10354 if (DeferredExportedNamespaces.erase(Namespc)) 10355 Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported); 10356 } 10357 10358 CXXRecordDecl *Sema::getStdBadAlloc() const { 10359 return cast_or_null<CXXRecordDecl>( 10360 StdBadAlloc.get(Context.getExternalSource())); 10361 } 10362 10363 EnumDecl *Sema::getStdAlignValT() const { 10364 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource())); 10365 } 10366 10367 NamespaceDecl *Sema::getStdNamespace() const { 10368 return cast_or_null<NamespaceDecl>( 10369 StdNamespace.get(Context.getExternalSource())); 10370 } 10371 10372 NamespaceDecl *Sema::lookupStdExperimentalNamespace() { 10373 if (!StdExperimentalNamespaceCache) { 10374 if (auto Std = getStdNamespace()) { 10375 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"), 10376 SourceLocation(), LookupNamespaceName); 10377 if (!LookupQualifiedName(Result, Std) || 10378 !(StdExperimentalNamespaceCache = 10379 Result.getAsSingle<NamespaceDecl>())) 10380 Result.suppressDiagnostics(); 10381 } 10382 } 10383 return StdExperimentalNamespaceCache; 10384 } 10385 10386 namespace { 10387 10388 enum UnsupportedSTLSelect { 10389 USS_InvalidMember, 10390 USS_MissingMember, 10391 USS_NonTrivial, 10392 USS_Other 10393 }; 10394 10395 struct InvalidSTLDiagnoser { 10396 Sema &S; 10397 SourceLocation Loc; 10398 QualType TyForDiags; 10399 10400 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "", 10401 const VarDecl *VD = nullptr) { 10402 { 10403 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported) 10404 << TyForDiags << ((int)Sel); 10405 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) { 10406 assert(!Name.empty()); 10407 D << Name; 10408 } 10409 } 10410 if (Sel == USS_InvalidMember) { 10411 S.Diag(VD->getLocation(), diag::note_var_declared_here) 10412 << VD << VD->getSourceRange(); 10413 } 10414 return QualType(); 10415 } 10416 }; 10417 } // namespace 10418 10419 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind, 10420 SourceLocation Loc) { 10421 assert(getLangOpts().CPlusPlus && 10422 "Looking for comparison category type outside of C++."); 10423 10424 // Use an elaborated type for diagnostics which has a name containing the 10425 // prepended 'std' namespace but not any inline namespace names. 10426 auto TyForDiags = [&](ComparisonCategoryInfo *Info) { 10427 auto *NNS = 10428 NestedNameSpecifier::Create(Context, nullptr, getStdNamespace()); 10429 return Context.getElaboratedType(ETK_None, NNS, Info->getType()); 10430 }; 10431 10432 // Check if we've already successfully checked the comparison category type 10433 // before. If so, skip checking it again. 10434 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind); 10435 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) { 10436 // The only thing we need to check is that the type has a reachable 10437 // definition in the current context. 10438 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type)) 10439 return QualType(); 10440 10441 return Info->getType(); 10442 } 10443 10444 // If lookup failed 10445 if (!Info) { 10446 std::string NameForDiags = "std::"; 10447 NameForDiags += ComparisonCategories::getCategoryString(Kind); 10448 Diag(Loc, diag::err_implied_comparison_category_type_not_found) 10449 << NameForDiags; 10450 return QualType(); 10451 } 10452 10453 assert(Info->Kind == Kind); 10454 assert(Info->Record); 10455 10456 // Update the Record decl in case we encountered a forward declaration on our 10457 // first pass. FIXME: This is a bit of a hack. 10458 if (Info->Record->hasDefinition()) 10459 Info->Record = Info->Record->getDefinition(); 10460 10461 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type)) 10462 return QualType(); 10463 10464 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)}; 10465 10466 if (!Info->Record->isTriviallyCopyable()) 10467 return UnsupportedSTLError(USS_NonTrivial); 10468 10469 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) { 10470 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl(); 10471 // Tolerate empty base classes. 10472 if (Base->isEmpty()) 10473 continue; 10474 // Reject STL implementations which have at least one non-empty base. 10475 return UnsupportedSTLError(); 10476 } 10477 10478 // Check that the STL has implemented the types using a single integer field. 10479 // This expectation allows better codegen for builtin operators. We require: 10480 // (1) The class has exactly one field. 10481 // (2) The field is an integral or enumeration type. 10482 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end(); 10483 if (std::distance(FIt, FEnd) != 1 || 10484 !FIt->getType()->isIntegralOrEnumerationType()) { 10485 return UnsupportedSTLError(); 10486 } 10487 10488 // Build each of the require values and store them in Info. 10489 for (ComparisonCategoryResult CCR : 10490 ComparisonCategories::getPossibleResultsForType(Kind)) { 10491 StringRef MemName = ComparisonCategories::getResultString(CCR); 10492 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR); 10493 10494 if (!ValInfo) 10495 return UnsupportedSTLError(USS_MissingMember, MemName); 10496 10497 VarDecl *VD = ValInfo->VD; 10498 assert(VD && "should not be null!"); 10499 10500 // Attempt to diagnose reasons why the STL definition of this type 10501 // might be foobar, including it failing to be a constant expression. 10502 // TODO Handle more ways the lookup or result can be invalid. 10503 if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() || 10504 !VD->checkInitIsICE()) 10505 return UnsupportedSTLError(USS_InvalidMember, MemName, VD); 10506 10507 // Attempt to evaluate the var decl as a constant expression and extract 10508 // the value of its first field as a ICE. If this fails, the STL 10509 // implementation is not supported. 10510 if (!ValInfo->hasValidIntValue()) 10511 return UnsupportedSTLError(); 10512 10513 MarkVariableReferenced(Loc, VD); 10514 } 10515 10516 // We've successfully built the required types and expressions. Update 10517 // the cache and return the newly cached value. 10518 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true; 10519 return Info->getType(); 10520 } 10521 10522 /// Retrieve the special "std" namespace, which may require us to 10523 /// implicitly define the namespace. 10524 NamespaceDecl *Sema::getOrCreateStdNamespace() { 10525 if (!StdNamespace) { 10526 // The "std" namespace has not yet been defined, so build one implicitly. 10527 StdNamespace = NamespaceDecl::Create(Context, 10528 Context.getTranslationUnitDecl(), 10529 /*Inline=*/false, 10530 SourceLocation(), SourceLocation(), 10531 &PP.getIdentifierTable().get("std"), 10532 /*PrevDecl=*/nullptr); 10533 getStdNamespace()->setImplicit(true); 10534 } 10535 10536 return getStdNamespace(); 10537 } 10538 10539 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 10540 assert(getLangOpts().CPlusPlus && 10541 "Looking for std::initializer_list outside of C++."); 10542 10543 // We're looking for implicit instantiations of 10544 // template <typename E> class std::initializer_list. 10545 10546 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 10547 return false; 10548 10549 ClassTemplateDecl *Template = nullptr; 10550 const TemplateArgument *Arguments = nullptr; 10551 10552 if (const RecordType *RT = Ty->getAs<RecordType>()) { 10553 10554 ClassTemplateSpecializationDecl *Specialization = 10555 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 10556 if (!Specialization) 10557 return false; 10558 10559 Template = Specialization->getSpecializedTemplate(); 10560 Arguments = Specialization->getTemplateArgs().data(); 10561 } else if (const TemplateSpecializationType *TST = 10562 Ty->getAs<TemplateSpecializationType>()) { 10563 Template = dyn_cast_or_null<ClassTemplateDecl>( 10564 TST->getTemplateName().getAsTemplateDecl()); 10565 Arguments = TST->getArgs(); 10566 } 10567 if (!Template) 10568 return false; 10569 10570 if (!StdInitializerList) { 10571 // Haven't recognized std::initializer_list yet, maybe this is it. 10572 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 10573 if (TemplateClass->getIdentifier() != 10574 &PP.getIdentifierTable().get("initializer_list") || 10575 !getStdNamespace()->InEnclosingNamespaceSetOf( 10576 TemplateClass->getDeclContext())) 10577 return false; 10578 // This is a template called std::initializer_list, but is it the right 10579 // template? 10580 TemplateParameterList *Params = Template->getTemplateParameters(); 10581 if (Params->getMinRequiredArguments() != 1) 10582 return false; 10583 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 10584 return false; 10585 10586 // It's the right template. 10587 StdInitializerList = Template; 10588 } 10589 10590 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) 10591 return false; 10592 10593 // This is an instance of std::initializer_list. Find the argument type. 10594 if (Element) 10595 *Element = Arguments[0].getAsType(); 10596 return true; 10597 } 10598 10599 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 10600 NamespaceDecl *Std = S.getStdNamespace(); 10601 if (!Std) { 10602 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 10603 return nullptr; 10604 } 10605 10606 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 10607 Loc, Sema::LookupOrdinaryName); 10608 if (!S.LookupQualifiedName(Result, Std)) { 10609 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 10610 return nullptr; 10611 } 10612 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 10613 if (!Template) { 10614 Result.suppressDiagnostics(); 10615 // We found something weird. Complain about the first thing we found. 10616 NamedDecl *Found = *Result.begin(); 10617 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 10618 return nullptr; 10619 } 10620 10621 // We found some template called std::initializer_list. Now verify that it's 10622 // correct. 10623 TemplateParameterList *Params = Template->getTemplateParameters(); 10624 if (Params->getMinRequiredArguments() != 1 || 10625 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 10626 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 10627 return nullptr; 10628 } 10629 10630 return Template; 10631 } 10632 10633 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 10634 if (!StdInitializerList) { 10635 StdInitializerList = LookupStdInitializerList(*this, Loc); 10636 if (!StdInitializerList) 10637 return QualType(); 10638 } 10639 10640 TemplateArgumentListInfo Args(Loc, Loc); 10641 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 10642 Context.getTrivialTypeSourceInfo(Element, 10643 Loc))); 10644 return Context.getCanonicalType( 10645 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 10646 } 10647 10648 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) { 10649 // C++ [dcl.init.list]p2: 10650 // A constructor is an initializer-list constructor if its first parameter 10651 // is of type std::initializer_list<E> or reference to possibly cv-qualified 10652 // std::initializer_list<E> for some type E, and either there are no other 10653 // parameters or else all other parameters have default arguments. 10654 if (Ctor->getNumParams() < 1 || 10655 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 10656 return false; 10657 10658 QualType ArgType = Ctor->getParamDecl(0)->getType(); 10659 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 10660 ArgType = RT->getPointeeType().getUnqualifiedType(); 10661 10662 return isStdInitializerList(ArgType, nullptr); 10663 } 10664 10665 /// Determine whether a using statement is in a context where it will be 10666 /// apply in all contexts. 10667 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 10668 switch (CurContext->getDeclKind()) { 10669 case Decl::TranslationUnit: 10670 return true; 10671 case Decl::LinkageSpec: 10672 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 10673 default: 10674 return false; 10675 } 10676 } 10677 10678 namespace { 10679 10680 // Callback to only accept typo corrections that are namespaces. 10681 class NamespaceValidatorCCC final : public CorrectionCandidateCallback { 10682 public: 10683 bool ValidateCandidate(const TypoCorrection &candidate) override { 10684 if (NamedDecl *ND = candidate.getCorrectionDecl()) 10685 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 10686 return false; 10687 } 10688 10689 std::unique_ptr<CorrectionCandidateCallback> clone() override { 10690 return std::make_unique<NamespaceValidatorCCC>(*this); 10691 } 10692 }; 10693 10694 } 10695 10696 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 10697 CXXScopeSpec &SS, 10698 SourceLocation IdentLoc, 10699 IdentifierInfo *Ident) { 10700 R.clear(); 10701 NamespaceValidatorCCC CCC{}; 10702 if (TypoCorrection Corrected = 10703 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC, 10704 Sema::CTK_ErrorRecovery)) { 10705 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 10706 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 10707 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 10708 Ident->getName().equals(CorrectedStr); 10709 S.diagnoseTypo(Corrected, 10710 S.PDiag(diag::err_using_directive_member_suggest) 10711 << Ident << DC << DroppedSpecifier << SS.getRange(), 10712 S.PDiag(diag::note_namespace_defined_here)); 10713 } else { 10714 S.diagnoseTypo(Corrected, 10715 S.PDiag(diag::err_using_directive_suggest) << Ident, 10716 S.PDiag(diag::note_namespace_defined_here)); 10717 } 10718 R.addDecl(Corrected.getFoundDecl()); 10719 return true; 10720 } 10721 return false; 10722 } 10723 10724 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc, 10725 SourceLocation NamespcLoc, CXXScopeSpec &SS, 10726 SourceLocation IdentLoc, 10727 IdentifierInfo *NamespcName, 10728 const ParsedAttributesView &AttrList) { 10729 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 10730 assert(NamespcName && "Invalid NamespcName."); 10731 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 10732 10733 // This can only happen along a recovery path. 10734 while (S->isTemplateParamScope()) 10735 S = S->getParent(); 10736 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 10737 10738 UsingDirectiveDecl *UDir = nullptr; 10739 NestedNameSpecifier *Qualifier = nullptr; 10740 if (SS.isSet()) 10741 Qualifier = SS.getScopeRep(); 10742 10743 // Lookup namespace name. 10744 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 10745 LookupParsedName(R, S, &SS); 10746 if (R.isAmbiguous()) 10747 return nullptr; 10748 10749 if (R.empty()) { 10750 R.clear(); 10751 // Allow "using namespace std;" or "using namespace ::std;" even if 10752 // "std" hasn't been defined yet, for GCC compatibility. 10753 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 10754 NamespcName->isStr("std")) { 10755 Diag(IdentLoc, diag::ext_using_undefined_std); 10756 R.addDecl(getOrCreateStdNamespace()); 10757 R.resolveKind(); 10758 } 10759 // Otherwise, attempt typo correction. 10760 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 10761 } 10762 10763 if (!R.empty()) { 10764 NamedDecl *Named = R.getRepresentativeDecl(); 10765 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>(); 10766 assert(NS && "expected namespace decl"); 10767 10768 // The use of a nested name specifier may trigger deprecation warnings. 10769 DiagnoseUseOfDecl(Named, IdentLoc); 10770 10771 // C++ [namespace.udir]p1: 10772 // A using-directive specifies that the names in the nominated 10773 // namespace can be used in the scope in which the 10774 // using-directive appears after the using-directive. During 10775 // unqualified name lookup (3.4.1), the names appear as if they 10776 // were declared in the nearest enclosing namespace which 10777 // contains both the using-directive and the nominated 10778 // namespace. [Note: in this context, "contains" means "contains 10779 // directly or indirectly". ] 10780 10781 // Find enclosing context containing both using-directive and 10782 // nominated namespace. 10783 DeclContext *CommonAncestor = NS; 10784 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 10785 CommonAncestor = CommonAncestor->getParent(); 10786 10787 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 10788 SS.getWithLocInContext(Context), 10789 IdentLoc, Named, CommonAncestor); 10790 10791 if (IsUsingDirectiveInToplevelContext(CurContext) && 10792 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 10793 Diag(IdentLoc, diag::warn_using_directive_in_header); 10794 } 10795 10796 PushUsingDirective(S, UDir); 10797 } else { 10798 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 10799 } 10800 10801 if (UDir) 10802 ProcessDeclAttributeList(S, UDir, AttrList); 10803 10804 return UDir; 10805 } 10806 10807 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 10808 // If the scope has an associated entity and the using directive is at 10809 // namespace or translation unit scope, add the UsingDirectiveDecl into 10810 // its lookup structure so qualified name lookup can find it. 10811 DeclContext *Ctx = S->getEntity(); 10812 if (Ctx && !Ctx->isFunctionOrMethod()) 10813 Ctx->addDecl(UDir); 10814 else 10815 // Otherwise, it is at block scope. The using-directives will affect lookup 10816 // only to the end of the scope. 10817 S->PushUsingDirective(UDir); 10818 } 10819 10820 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS, 10821 SourceLocation UsingLoc, 10822 SourceLocation TypenameLoc, CXXScopeSpec &SS, 10823 UnqualifiedId &Name, 10824 SourceLocation EllipsisLoc, 10825 const ParsedAttributesView &AttrList) { 10826 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 10827 10828 if (SS.isEmpty()) { 10829 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname); 10830 return nullptr; 10831 } 10832 10833 switch (Name.getKind()) { 10834 case UnqualifiedIdKind::IK_ImplicitSelfParam: 10835 case UnqualifiedIdKind::IK_Identifier: 10836 case UnqualifiedIdKind::IK_OperatorFunctionId: 10837 case UnqualifiedIdKind::IK_LiteralOperatorId: 10838 case UnqualifiedIdKind::IK_ConversionFunctionId: 10839 break; 10840 10841 case UnqualifiedIdKind::IK_ConstructorName: 10842 case UnqualifiedIdKind::IK_ConstructorTemplateId: 10843 // C++11 inheriting constructors. 10844 Diag(Name.getBeginLoc(), 10845 getLangOpts().CPlusPlus11 10846 ? diag::warn_cxx98_compat_using_decl_constructor 10847 : diag::err_using_decl_constructor) 10848 << SS.getRange(); 10849 10850 if (getLangOpts().CPlusPlus11) break; 10851 10852 return nullptr; 10853 10854 case UnqualifiedIdKind::IK_DestructorName: 10855 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange(); 10856 return nullptr; 10857 10858 case UnqualifiedIdKind::IK_TemplateId: 10859 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id) 10860 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 10861 return nullptr; 10862 10863 case UnqualifiedIdKind::IK_DeductionGuideName: 10864 llvm_unreachable("cannot parse qualified deduction guide name"); 10865 } 10866 10867 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 10868 DeclarationName TargetName = TargetNameInfo.getName(); 10869 if (!TargetName) 10870 return nullptr; 10871 10872 // Warn about access declarations. 10873 if (UsingLoc.isInvalid()) { 10874 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11 10875 ? diag::err_access_decl 10876 : diag::warn_access_decl_deprecated) 10877 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 10878 } 10879 10880 if (EllipsisLoc.isInvalid()) { 10881 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 10882 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 10883 return nullptr; 10884 } else { 10885 if (!SS.getScopeRep()->containsUnexpandedParameterPack() && 10886 !TargetNameInfo.containsUnexpandedParameterPack()) { 10887 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 10888 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc()); 10889 EllipsisLoc = SourceLocation(); 10890 } 10891 } 10892 10893 NamedDecl *UD = 10894 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc, 10895 SS, TargetNameInfo, EllipsisLoc, AttrList, 10896 /*IsInstantiation*/false); 10897 if (UD) 10898 PushOnScopeChains(UD, S, /*AddToContext*/ false); 10899 10900 return UD; 10901 } 10902 10903 /// Determine whether a using declaration considers the given 10904 /// declarations as "equivalent", e.g., if they are redeclarations of 10905 /// the same entity or are both typedefs of the same type. 10906 static bool 10907 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 10908 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 10909 return true; 10910 10911 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 10912 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 10913 return Context.hasSameType(TD1->getUnderlyingType(), 10914 TD2->getUnderlyingType()); 10915 10916 return false; 10917 } 10918 10919 10920 /// Determines whether to create a using shadow decl for a particular 10921 /// decl, given the set of decls existing prior to this using lookup. 10922 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 10923 const LookupResult &Previous, 10924 UsingShadowDecl *&PrevShadow) { 10925 // Diagnose finding a decl which is not from a base class of the 10926 // current class. We do this now because there are cases where this 10927 // function will silently decide not to build a shadow decl, which 10928 // will pre-empt further diagnostics. 10929 // 10930 // We don't need to do this in C++11 because we do the check once on 10931 // the qualifier. 10932 // 10933 // FIXME: diagnose the following if we care enough: 10934 // struct A { int foo; }; 10935 // struct B : A { using A::foo; }; 10936 // template <class T> struct C : A {}; 10937 // template <class T> struct D : C<T> { using B::foo; } // <--- 10938 // This is invalid (during instantiation) in C++03 because B::foo 10939 // resolves to the using decl in B, which is not a base class of D<T>. 10940 // We can't diagnose it immediately because C<T> is an unknown 10941 // specialization. The UsingShadowDecl in D<T> then points directly 10942 // to A::foo, which will look well-formed when we instantiate. 10943 // The right solution is to not collapse the shadow-decl chain. 10944 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 10945 DeclContext *OrigDC = Orig->getDeclContext(); 10946 10947 // Handle enums and anonymous structs. 10948 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 10949 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 10950 while (OrigRec->isAnonymousStructOrUnion()) 10951 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 10952 10953 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 10954 if (OrigDC == CurContext) { 10955 Diag(Using->getLocation(), 10956 diag::err_using_decl_nested_name_specifier_is_current_class) 10957 << Using->getQualifierLoc().getSourceRange(); 10958 Diag(Orig->getLocation(), diag::note_using_decl_target); 10959 Using->setInvalidDecl(); 10960 return true; 10961 } 10962 10963 Diag(Using->getQualifierLoc().getBeginLoc(), 10964 diag::err_using_decl_nested_name_specifier_is_not_base_class) 10965 << Using->getQualifier() 10966 << cast<CXXRecordDecl>(CurContext) 10967 << Using->getQualifierLoc().getSourceRange(); 10968 Diag(Orig->getLocation(), diag::note_using_decl_target); 10969 Using->setInvalidDecl(); 10970 return true; 10971 } 10972 } 10973 10974 if (Previous.empty()) return false; 10975 10976 NamedDecl *Target = Orig; 10977 if (isa<UsingShadowDecl>(Target)) 10978 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 10979 10980 // If the target happens to be one of the previous declarations, we 10981 // don't have a conflict. 10982 // 10983 // FIXME: but we might be increasing its access, in which case we 10984 // should redeclare it. 10985 NamedDecl *NonTag = nullptr, *Tag = nullptr; 10986 bool FoundEquivalentDecl = false; 10987 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 10988 I != E; ++I) { 10989 NamedDecl *D = (*I)->getUnderlyingDecl(); 10990 // We can have UsingDecls in our Previous results because we use the same 10991 // LookupResult for checking whether the UsingDecl itself is a valid 10992 // redeclaration. 10993 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D)) 10994 continue; 10995 10996 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 10997 // C++ [class.mem]p19: 10998 // If T is the name of a class, then [every named member other than 10999 // a non-static data member] shall have a name different from T 11000 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) && 11001 !isa<IndirectFieldDecl>(Target) && 11002 !isa<UnresolvedUsingValueDecl>(Target) && 11003 DiagnoseClassNameShadow( 11004 CurContext, 11005 DeclarationNameInfo(Using->getDeclName(), Using->getLocation()))) 11006 return true; 11007 } 11008 11009 if (IsEquivalentForUsingDecl(Context, D, Target)) { 11010 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 11011 PrevShadow = Shadow; 11012 FoundEquivalentDecl = true; 11013 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) { 11014 // We don't conflict with an existing using shadow decl of an equivalent 11015 // declaration, but we're not a redeclaration of it. 11016 FoundEquivalentDecl = true; 11017 } 11018 11019 if (isVisible(D)) 11020 (isa<TagDecl>(D) ? Tag : NonTag) = D; 11021 } 11022 11023 if (FoundEquivalentDecl) 11024 return false; 11025 11026 if (FunctionDecl *FD = Target->getAsFunction()) { 11027 NamedDecl *OldDecl = nullptr; 11028 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 11029 /*IsForUsingDecl*/ true)) { 11030 case Ovl_Overload: 11031 return false; 11032 11033 case Ovl_NonFunction: 11034 Diag(Using->getLocation(), diag::err_using_decl_conflict); 11035 break; 11036 11037 // We found a decl with the exact signature. 11038 case Ovl_Match: 11039 // If we're in a record, we want to hide the target, so we 11040 // return true (without a diagnostic) to tell the caller not to 11041 // build a shadow decl. 11042 if (CurContext->isRecord()) 11043 return true; 11044 11045 // If we're not in a record, this is an error. 11046 Diag(Using->getLocation(), diag::err_using_decl_conflict); 11047 break; 11048 } 11049 11050 Diag(Target->getLocation(), diag::note_using_decl_target); 11051 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 11052 Using->setInvalidDecl(); 11053 return true; 11054 } 11055 11056 // Target is not a function. 11057 11058 if (isa<TagDecl>(Target)) { 11059 // No conflict between a tag and a non-tag. 11060 if (!Tag) return false; 11061 11062 Diag(Using->getLocation(), diag::err_using_decl_conflict); 11063 Diag(Target->getLocation(), diag::note_using_decl_target); 11064 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 11065 Using->setInvalidDecl(); 11066 return true; 11067 } 11068 11069 // No conflict between a tag and a non-tag. 11070 if (!NonTag) return false; 11071 11072 Diag(Using->getLocation(), diag::err_using_decl_conflict); 11073 Diag(Target->getLocation(), diag::note_using_decl_target); 11074 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 11075 Using->setInvalidDecl(); 11076 return true; 11077 } 11078 11079 /// Determine whether a direct base class is a virtual base class. 11080 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) { 11081 if (!Derived->getNumVBases()) 11082 return false; 11083 for (auto &B : Derived->bases()) 11084 if (B.getType()->getAsCXXRecordDecl() == Base) 11085 return B.isVirtual(); 11086 llvm_unreachable("not a direct base class"); 11087 } 11088 11089 /// Builds a shadow declaration corresponding to a 'using' declaration. 11090 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 11091 UsingDecl *UD, 11092 NamedDecl *Orig, 11093 UsingShadowDecl *PrevDecl) { 11094 // If we resolved to another shadow declaration, just coalesce them. 11095 NamedDecl *Target = Orig; 11096 if (isa<UsingShadowDecl>(Target)) { 11097 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 11098 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 11099 } 11100 11101 NamedDecl *NonTemplateTarget = Target; 11102 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target)) 11103 NonTemplateTarget = TargetTD->getTemplatedDecl(); 11104 11105 UsingShadowDecl *Shadow; 11106 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) { 11107 bool IsVirtualBase = 11108 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext), 11109 UD->getQualifier()->getAsRecordDecl()); 11110 Shadow = ConstructorUsingShadowDecl::Create( 11111 Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase); 11112 } else { 11113 Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD, 11114 Target); 11115 } 11116 UD->addShadowDecl(Shadow); 11117 11118 Shadow->setAccess(UD->getAccess()); 11119 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 11120 Shadow->setInvalidDecl(); 11121 11122 Shadow->setPreviousDecl(PrevDecl); 11123 11124 if (S) 11125 PushOnScopeChains(Shadow, S); 11126 else 11127 CurContext->addDecl(Shadow); 11128 11129 11130 return Shadow; 11131 } 11132 11133 /// Hides a using shadow declaration. This is required by the current 11134 /// using-decl implementation when a resolvable using declaration in a 11135 /// class is followed by a declaration which would hide or override 11136 /// one or more of the using decl's targets; for example: 11137 /// 11138 /// struct Base { void foo(int); }; 11139 /// struct Derived : Base { 11140 /// using Base::foo; 11141 /// void foo(int); 11142 /// }; 11143 /// 11144 /// The governing language is C++03 [namespace.udecl]p12: 11145 /// 11146 /// When a using-declaration brings names from a base class into a 11147 /// derived class scope, member functions in the derived class 11148 /// override and/or hide member functions with the same name and 11149 /// parameter types in a base class (rather than conflicting). 11150 /// 11151 /// There are two ways to implement this: 11152 /// (1) optimistically create shadow decls when they're not hidden 11153 /// by existing declarations, or 11154 /// (2) don't create any shadow decls (or at least don't make them 11155 /// visible) until we've fully parsed/instantiated the class. 11156 /// The problem with (1) is that we might have to retroactively remove 11157 /// a shadow decl, which requires several O(n) operations because the 11158 /// decl structures are (very reasonably) not designed for removal. 11159 /// (2) avoids this but is very fiddly and phase-dependent. 11160 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 11161 if (Shadow->getDeclName().getNameKind() == 11162 DeclarationName::CXXConversionFunctionName) 11163 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 11164 11165 // Remove it from the DeclContext... 11166 Shadow->getDeclContext()->removeDecl(Shadow); 11167 11168 // ...and the scope, if applicable... 11169 if (S) { 11170 S->RemoveDecl(Shadow); 11171 IdResolver.RemoveDecl(Shadow); 11172 } 11173 11174 // ...and the using decl. 11175 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 11176 11177 // TODO: complain somehow if Shadow was used. It shouldn't 11178 // be possible for this to happen, because...? 11179 } 11180 11181 /// Find the base specifier for a base class with the given type. 11182 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 11183 QualType DesiredBase, 11184 bool &AnyDependentBases) { 11185 // Check whether the named type is a direct base class. 11186 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified() 11187 .getUnqualifiedType(); 11188 for (auto &Base : Derived->bases()) { 11189 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 11190 if (CanonicalDesiredBase == BaseType) 11191 return &Base; 11192 if (BaseType->isDependentType()) 11193 AnyDependentBases = true; 11194 } 11195 return nullptr; 11196 } 11197 11198 namespace { 11199 class UsingValidatorCCC final : public CorrectionCandidateCallback { 11200 public: 11201 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 11202 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 11203 : HasTypenameKeyword(HasTypenameKeyword), 11204 IsInstantiation(IsInstantiation), OldNNS(NNS), 11205 RequireMemberOf(RequireMemberOf) {} 11206 11207 bool ValidateCandidate(const TypoCorrection &Candidate) override { 11208 NamedDecl *ND = Candidate.getCorrectionDecl(); 11209 11210 // Keywords are not valid here. 11211 if (!ND || isa<NamespaceDecl>(ND)) 11212 return false; 11213 11214 // Completely unqualified names are invalid for a 'using' declaration. 11215 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 11216 return false; 11217 11218 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would 11219 // reject. 11220 11221 if (RequireMemberOf) { 11222 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 11223 if (FoundRecord && FoundRecord->isInjectedClassName()) { 11224 // No-one ever wants a using-declaration to name an injected-class-name 11225 // of a base class, unless they're declaring an inheriting constructor. 11226 ASTContext &Ctx = ND->getASTContext(); 11227 if (!Ctx.getLangOpts().CPlusPlus11) 11228 return false; 11229 QualType FoundType = Ctx.getRecordType(FoundRecord); 11230 11231 // Check that the injected-class-name is named as a member of its own 11232 // type; we don't want to suggest 'using Derived::Base;', since that 11233 // means something else. 11234 NestedNameSpecifier *Specifier = 11235 Candidate.WillReplaceSpecifier() 11236 ? Candidate.getCorrectionSpecifier() 11237 : OldNNS; 11238 if (!Specifier->getAsType() || 11239 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 11240 return false; 11241 11242 // Check that this inheriting constructor declaration actually names a 11243 // direct base class of the current class. 11244 bool AnyDependentBases = false; 11245 if (!findDirectBaseWithType(RequireMemberOf, 11246 Ctx.getRecordType(FoundRecord), 11247 AnyDependentBases) && 11248 !AnyDependentBases) 11249 return false; 11250 } else { 11251 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 11252 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 11253 return false; 11254 11255 // FIXME: Check that the base class member is accessible? 11256 } 11257 } else { 11258 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 11259 if (FoundRecord && FoundRecord->isInjectedClassName()) 11260 return false; 11261 } 11262 11263 if (isa<TypeDecl>(ND)) 11264 return HasTypenameKeyword || !IsInstantiation; 11265 11266 return !HasTypenameKeyword; 11267 } 11268 11269 std::unique_ptr<CorrectionCandidateCallback> clone() override { 11270 return std::make_unique<UsingValidatorCCC>(*this); 11271 } 11272 11273 private: 11274 bool HasTypenameKeyword; 11275 bool IsInstantiation; 11276 NestedNameSpecifier *OldNNS; 11277 CXXRecordDecl *RequireMemberOf; 11278 }; 11279 } // end anonymous namespace 11280 11281 /// Builds a using declaration. 11282 /// 11283 /// \param IsInstantiation - Whether this call arises from an 11284 /// instantiation of an unresolved using declaration. We treat 11285 /// the lookup differently for these declarations. 11286 NamedDecl *Sema::BuildUsingDeclaration( 11287 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, 11288 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, 11289 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, 11290 const ParsedAttributesView &AttrList, bool IsInstantiation) { 11291 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 11292 SourceLocation IdentLoc = NameInfo.getLoc(); 11293 assert(IdentLoc.isValid() && "Invalid TargetName location."); 11294 11295 // FIXME: We ignore attributes for now. 11296 11297 // For an inheriting constructor declaration, the name of the using 11298 // declaration is the name of a constructor in this class, not in the 11299 // base class. 11300 DeclarationNameInfo UsingName = NameInfo; 11301 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName) 11302 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext)) 11303 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 11304 Context.getCanonicalType(Context.getRecordType(RD)))); 11305 11306 // Do the redeclaration lookup in the current scope. 11307 LookupResult Previous(*this, UsingName, LookupUsingDeclName, 11308 ForVisibleRedeclaration); 11309 Previous.setHideTags(false); 11310 if (S) { 11311 LookupName(Previous, S); 11312 11313 // It is really dumb that we have to do this. 11314 LookupResult::Filter F = Previous.makeFilter(); 11315 while (F.hasNext()) { 11316 NamedDecl *D = F.next(); 11317 if (!isDeclInScope(D, CurContext, S)) 11318 F.erase(); 11319 // If we found a local extern declaration that's not ordinarily visible, 11320 // and this declaration is being added to a non-block scope, ignore it. 11321 // We're only checking for scope conflicts here, not also for violations 11322 // of the linkage rules. 11323 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 11324 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 11325 F.erase(); 11326 } 11327 F.done(); 11328 } else { 11329 assert(IsInstantiation && "no scope in non-instantiation"); 11330 if (CurContext->isRecord()) 11331 LookupQualifiedName(Previous, CurContext); 11332 else { 11333 // No redeclaration check is needed here; in non-member contexts we 11334 // diagnosed all possible conflicts with other using-declarations when 11335 // building the template: 11336 // 11337 // For a dependent non-type using declaration, the only valid case is 11338 // if we instantiate to a single enumerator. We check for conflicts 11339 // between shadow declarations we introduce, and we check in the template 11340 // definition for conflicts between a non-type using declaration and any 11341 // other declaration, which together covers all cases. 11342 // 11343 // A dependent typename using declaration will never successfully 11344 // instantiate, since it will always name a class member, so we reject 11345 // that in the template definition. 11346 } 11347 } 11348 11349 // Check for invalid redeclarations. 11350 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 11351 SS, IdentLoc, Previous)) 11352 return nullptr; 11353 11354 // Check for bad qualifiers. 11355 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo, 11356 IdentLoc)) 11357 return nullptr; 11358 11359 DeclContext *LookupContext = computeDeclContext(SS); 11360 NamedDecl *D; 11361 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 11362 if (!LookupContext || EllipsisLoc.isValid()) { 11363 if (HasTypenameKeyword) { 11364 // FIXME: not all declaration name kinds are legal here 11365 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 11366 UsingLoc, TypenameLoc, 11367 QualifierLoc, 11368 IdentLoc, NameInfo.getName(), 11369 EllipsisLoc); 11370 } else { 11371 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 11372 QualifierLoc, NameInfo, EllipsisLoc); 11373 } 11374 D->setAccess(AS); 11375 CurContext->addDecl(D); 11376 return D; 11377 } 11378 11379 auto Build = [&](bool Invalid) { 11380 UsingDecl *UD = 11381 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 11382 UsingName, HasTypenameKeyword); 11383 UD->setAccess(AS); 11384 CurContext->addDecl(UD); 11385 UD->setInvalidDecl(Invalid); 11386 return UD; 11387 }; 11388 auto BuildInvalid = [&]{ return Build(true); }; 11389 auto BuildValid = [&]{ return Build(false); }; 11390 11391 if (RequireCompleteDeclContext(SS, LookupContext)) 11392 return BuildInvalid(); 11393 11394 // Look up the target name. 11395 LookupResult R(*this, NameInfo, LookupOrdinaryName); 11396 11397 // Unlike most lookups, we don't always want to hide tag 11398 // declarations: tag names are visible through the using declaration 11399 // even if hidden by ordinary names, *except* in a dependent context 11400 // where it's important for the sanity of two-phase lookup. 11401 if (!IsInstantiation) 11402 R.setHideTags(false); 11403 11404 // For the purposes of this lookup, we have a base object type 11405 // equal to that of the current context. 11406 if (CurContext->isRecord()) { 11407 R.setBaseObjectType( 11408 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 11409 } 11410 11411 LookupQualifiedName(R, LookupContext); 11412 11413 // Try to correct typos if possible. If constructor name lookup finds no 11414 // results, that means the named class has no explicit constructors, and we 11415 // suppressed declaring implicit ones (probably because it's dependent or 11416 // invalid). 11417 if (R.empty() && 11418 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { 11419 // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes 11420 // it will believe that glibc provides a ::gets in cases where it does not, 11421 // and will try to pull it into namespace std with a using-declaration. 11422 // Just ignore the using-declaration in that case. 11423 auto *II = NameInfo.getName().getAsIdentifierInfo(); 11424 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") && 11425 CurContext->isStdNamespace() && 11426 isa<TranslationUnitDecl>(LookupContext) && 11427 getSourceManager().isInSystemHeader(UsingLoc)) 11428 return nullptr; 11429 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 11430 dyn_cast<CXXRecordDecl>(CurContext)); 11431 if (TypoCorrection Corrected = 11432 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 11433 CTK_ErrorRecovery)) { 11434 // We reject candidates where DroppedSpecifier == true, hence the 11435 // literal '0' below. 11436 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 11437 << NameInfo.getName() << LookupContext << 0 11438 << SS.getRange()); 11439 11440 // If we picked a correction with no attached Decl we can't do anything 11441 // useful with it, bail out. 11442 NamedDecl *ND = Corrected.getCorrectionDecl(); 11443 if (!ND) 11444 return BuildInvalid(); 11445 11446 // If we corrected to an inheriting constructor, handle it as one. 11447 auto *RD = dyn_cast<CXXRecordDecl>(ND); 11448 if (RD && RD->isInjectedClassName()) { 11449 // The parent of the injected class name is the class itself. 11450 RD = cast<CXXRecordDecl>(RD->getParent()); 11451 11452 // Fix up the information we'll use to build the using declaration. 11453 if (Corrected.WillReplaceSpecifier()) { 11454 NestedNameSpecifierLocBuilder Builder; 11455 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 11456 QualifierLoc.getSourceRange()); 11457 QualifierLoc = Builder.getWithLocInContext(Context); 11458 } 11459 11460 // In this case, the name we introduce is the name of a derived class 11461 // constructor. 11462 auto *CurClass = cast<CXXRecordDecl>(CurContext); 11463 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 11464 Context.getCanonicalType(Context.getRecordType(CurClass)))); 11465 UsingName.setNamedTypeInfo(nullptr); 11466 for (auto *Ctor : LookupConstructors(RD)) 11467 R.addDecl(Ctor); 11468 R.resolveKind(); 11469 } else { 11470 // FIXME: Pick up all the declarations if we found an overloaded 11471 // function. 11472 UsingName.setName(ND->getDeclName()); 11473 R.addDecl(ND); 11474 } 11475 } else { 11476 Diag(IdentLoc, diag::err_no_member) 11477 << NameInfo.getName() << LookupContext << SS.getRange(); 11478 return BuildInvalid(); 11479 } 11480 } 11481 11482 if (R.isAmbiguous()) 11483 return BuildInvalid(); 11484 11485 if (HasTypenameKeyword) { 11486 // If we asked for a typename and got a non-type decl, error out. 11487 if (!R.getAsSingle<TypeDecl>()) { 11488 Diag(IdentLoc, diag::err_using_typename_non_type); 11489 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 11490 Diag((*I)->getUnderlyingDecl()->getLocation(), 11491 diag::note_using_decl_target); 11492 return BuildInvalid(); 11493 } 11494 } else { 11495 // If we asked for a non-typename and we got a type, error out, 11496 // but only if this is an instantiation of an unresolved using 11497 // decl. Otherwise just silently find the type name. 11498 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 11499 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 11500 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 11501 return BuildInvalid(); 11502 } 11503 } 11504 11505 // C++14 [namespace.udecl]p6: 11506 // A using-declaration shall not name a namespace. 11507 if (R.getAsSingle<NamespaceDecl>()) { 11508 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 11509 << SS.getRange(); 11510 return BuildInvalid(); 11511 } 11512 11513 // C++14 [namespace.udecl]p7: 11514 // A using-declaration shall not name a scoped enumerator. 11515 if (auto *ED = R.getAsSingle<EnumConstantDecl>()) { 11516 if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) { 11517 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum) 11518 << SS.getRange(); 11519 return BuildInvalid(); 11520 } 11521 } 11522 11523 UsingDecl *UD = BuildValid(); 11524 11525 // Some additional rules apply to inheriting constructors. 11526 if (UsingName.getName().getNameKind() == 11527 DeclarationName::CXXConstructorName) { 11528 // Suppress access diagnostics; the access check is instead performed at the 11529 // point of use for an inheriting constructor. 11530 R.suppressDiagnostics(); 11531 if (CheckInheritingConstructorUsingDecl(UD)) 11532 return UD; 11533 } 11534 11535 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 11536 UsingShadowDecl *PrevDecl = nullptr; 11537 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 11538 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 11539 } 11540 11541 return UD; 11542 } 11543 11544 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom, 11545 ArrayRef<NamedDecl *> Expansions) { 11546 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || 11547 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || 11548 isa<UsingPackDecl>(InstantiatedFrom)); 11549 11550 auto *UPD = 11551 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions); 11552 UPD->setAccess(InstantiatedFrom->getAccess()); 11553 CurContext->addDecl(UPD); 11554 return UPD; 11555 } 11556 11557 /// Additional checks for a using declaration referring to a constructor name. 11558 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 11559 assert(!UD->hasTypename() && "expecting a constructor name"); 11560 11561 const Type *SourceType = UD->getQualifier()->getAsType(); 11562 assert(SourceType && 11563 "Using decl naming constructor doesn't have type in scope spec."); 11564 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 11565 11566 // Check whether the named type is a direct base class. 11567 bool AnyDependentBases = false; 11568 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 11569 AnyDependentBases); 11570 if (!Base && !AnyDependentBases) { 11571 Diag(UD->getUsingLoc(), 11572 diag::err_using_decl_constructor_not_in_direct_base) 11573 << UD->getNameInfo().getSourceRange() 11574 << QualType(SourceType, 0) << TargetClass; 11575 UD->setInvalidDecl(); 11576 return true; 11577 } 11578 11579 if (Base) 11580 Base->setInheritConstructors(); 11581 11582 return false; 11583 } 11584 11585 /// Checks that the given using declaration is not an invalid 11586 /// redeclaration. Note that this is checking only for the using decl 11587 /// itself, not for any ill-formedness among the UsingShadowDecls. 11588 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 11589 bool HasTypenameKeyword, 11590 const CXXScopeSpec &SS, 11591 SourceLocation NameLoc, 11592 const LookupResult &Prev) { 11593 NestedNameSpecifier *Qual = SS.getScopeRep(); 11594 11595 // C++03 [namespace.udecl]p8: 11596 // C++0x [namespace.udecl]p10: 11597 // A using-declaration is a declaration and can therefore be used 11598 // repeatedly where (and only where) multiple declarations are 11599 // allowed. 11600 // 11601 // That's in non-member contexts. 11602 if (!CurContext->getRedeclContext()->isRecord()) { 11603 // A dependent qualifier outside a class can only ever resolve to an 11604 // enumeration type. Therefore it conflicts with any other non-type 11605 // declaration in the same scope. 11606 // FIXME: How should we check for dependent type-type conflicts at block 11607 // scope? 11608 if (Qual->isDependent() && !HasTypenameKeyword) { 11609 for (auto *D : Prev) { 11610 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) { 11611 bool OldCouldBeEnumerator = 11612 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D); 11613 Diag(NameLoc, 11614 OldCouldBeEnumerator ? diag::err_redefinition 11615 : diag::err_redefinition_different_kind) 11616 << Prev.getLookupName(); 11617 Diag(D->getLocation(), diag::note_previous_definition); 11618 return true; 11619 } 11620 } 11621 } 11622 return false; 11623 } 11624 11625 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 11626 NamedDecl *D = *I; 11627 11628 bool DTypename; 11629 NestedNameSpecifier *DQual; 11630 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 11631 DTypename = UD->hasTypename(); 11632 DQual = UD->getQualifier(); 11633 } else if (UnresolvedUsingValueDecl *UD 11634 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 11635 DTypename = false; 11636 DQual = UD->getQualifier(); 11637 } else if (UnresolvedUsingTypenameDecl *UD 11638 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 11639 DTypename = true; 11640 DQual = UD->getQualifier(); 11641 } else continue; 11642 11643 // using decls differ if one says 'typename' and the other doesn't. 11644 // FIXME: non-dependent using decls? 11645 if (HasTypenameKeyword != DTypename) continue; 11646 11647 // using decls differ if they name different scopes (but note that 11648 // template instantiation can cause this check to trigger when it 11649 // didn't before instantiation). 11650 if (Context.getCanonicalNestedNameSpecifier(Qual) != 11651 Context.getCanonicalNestedNameSpecifier(DQual)) 11652 continue; 11653 11654 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 11655 Diag(D->getLocation(), diag::note_using_decl) << 1; 11656 return true; 11657 } 11658 11659 return false; 11660 } 11661 11662 11663 /// Checks that the given nested-name qualifier used in a using decl 11664 /// in the current context is appropriately related to the current 11665 /// scope. If an error is found, diagnoses it and returns true. 11666 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 11667 bool HasTypename, 11668 const CXXScopeSpec &SS, 11669 const DeclarationNameInfo &NameInfo, 11670 SourceLocation NameLoc) { 11671 DeclContext *NamedContext = computeDeclContext(SS); 11672 11673 if (!CurContext->isRecord()) { 11674 // C++03 [namespace.udecl]p3: 11675 // C++0x [namespace.udecl]p8: 11676 // A using-declaration for a class member shall be a member-declaration. 11677 11678 // If we weren't able to compute a valid scope, it might validly be a 11679 // dependent class scope or a dependent enumeration unscoped scope. If 11680 // we have a 'typename' keyword, the scope must resolve to a class type. 11681 if ((HasTypename && !NamedContext) || 11682 (NamedContext && NamedContext->getRedeclContext()->isRecord())) { 11683 auto *RD = NamedContext 11684 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext()) 11685 : nullptr; 11686 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) 11687 RD = nullptr; 11688 11689 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 11690 << SS.getRange(); 11691 11692 // If we have a complete, non-dependent source type, try to suggest a 11693 // way to get the same effect. 11694 if (!RD) 11695 return true; 11696 11697 // Find what this using-declaration was referring to. 11698 LookupResult R(*this, NameInfo, LookupOrdinaryName); 11699 R.setHideTags(false); 11700 R.suppressDiagnostics(); 11701 LookupQualifiedName(R, RD); 11702 11703 if (R.getAsSingle<TypeDecl>()) { 11704 if (getLangOpts().CPlusPlus11) { 11705 // Convert 'using X::Y;' to 'using Y = X::Y;'. 11706 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 11707 << 0 // alias declaration 11708 << FixItHint::CreateInsertion(SS.getBeginLoc(), 11709 NameInfo.getName().getAsString() + 11710 " = "); 11711 } else { 11712 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 11713 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc()); 11714 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 11715 << 1 // typedef declaration 11716 << FixItHint::CreateReplacement(UsingLoc, "typedef") 11717 << FixItHint::CreateInsertion( 11718 InsertLoc, " " + NameInfo.getName().getAsString()); 11719 } 11720 } else if (R.getAsSingle<VarDecl>()) { 11721 // Don't provide a fixit outside C++11 mode; we don't want to suggest 11722 // repeating the type of the static data member here. 11723 FixItHint FixIt; 11724 if (getLangOpts().CPlusPlus11) { 11725 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 11726 FixIt = FixItHint::CreateReplacement( 11727 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 11728 } 11729 11730 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 11731 << 2 // reference declaration 11732 << FixIt; 11733 } else if (R.getAsSingle<EnumConstantDecl>()) { 11734 // Don't provide a fixit outside C++11 mode; we don't want to suggest 11735 // repeating the type of the enumeration here, and we can't do so if 11736 // the type is anonymous. 11737 FixItHint FixIt; 11738 if (getLangOpts().CPlusPlus11) { 11739 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 11740 FixIt = FixItHint::CreateReplacement( 11741 UsingLoc, 11742 "constexpr auto " + NameInfo.getName().getAsString() + " = "); 11743 } 11744 11745 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 11746 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable 11747 << FixIt; 11748 } 11749 return true; 11750 } 11751 11752 // Otherwise, this might be valid. 11753 return false; 11754 } 11755 11756 // The current scope is a record. 11757 11758 // If the named context is dependent, we can't decide much. 11759 if (!NamedContext) { 11760 // FIXME: in C++0x, we can diagnose if we can prove that the 11761 // nested-name-specifier does not refer to a base class, which is 11762 // still possible in some cases. 11763 11764 // Otherwise we have to conservatively report that things might be 11765 // okay. 11766 return false; 11767 } 11768 11769 if (!NamedContext->isRecord()) { 11770 // Ideally this would point at the last name in the specifier, 11771 // but we don't have that level of source info. 11772 Diag(SS.getRange().getBegin(), 11773 diag::err_using_decl_nested_name_specifier_is_not_class) 11774 << SS.getScopeRep() << SS.getRange(); 11775 return true; 11776 } 11777 11778 if (!NamedContext->isDependentContext() && 11779 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 11780 return true; 11781 11782 if (getLangOpts().CPlusPlus11) { 11783 // C++11 [namespace.udecl]p3: 11784 // In a using-declaration used as a member-declaration, the 11785 // nested-name-specifier shall name a base class of the class 11786 // being defined. 11787 11788 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 11789 cast<CXXRecordDecl>(NamedContext))) { 11790 if (CurContext == NamedContext) { 11791 Diag(NameLoc, 11792 diag::err_using_decl_nested_name_specifier_is_current_class) 11793 << SS.getRange(); 11794 return true; 11795 } 11796 11797 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) { 11798 Diag(SS.getRange().getBegin(), 11799 diag::err_using_decl_nested_name_specifier_is_not_base_class) 11800 << SS.getScopeRep() 11801 << cast<CXXRecordDecl>(CurContext) 11802 << SS.getRange(); 11803 } 11804 return true; 11805 } 11806 11807 return false; 11808 } 11809 11810 // C++03 [namespace.udecl]p4: 11811 // A using-declaration used as a member-declaration shall refer 11812 // to a member of a base class of the class being defined [etc.]. 11813 11814 // Salient point: SS doesn't have to name a base class as long as 11815 // lookup only finds members from base classes. Therefore we can 11816 // diagnose here only if we can prove that that can't happen, 11817 // i.e. if the class hierarchies provably don't intersect. 11818 11819 // TODO: it would be nice if "definitely valid" results were cached 11820 // in the UsingDecl and UsingShadowDecl so that these checks didn't 11821 // need to be repeated. 11822 11823 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases; 11824 auto Collect = [&Bases](const CXXRecordDecl *Base) { 11825 Bases.insert(Base); 11826 return true; 11827 }; 11828 11829 // Collect all bases. Return false if we find a dependent base. 11830 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect)) 11831 return false; 11832 11833 // Returns true if the base is dependent or is one of the accumulated base 11834 // classes. 11835 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) { 11836 return !Bases.count(Base); 11837 }; 11838 11839 // Return false if the class has a dependent base or if it or one 11840 // of its bases is present in the base set of the current context. 11841 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) || 11842 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase)) 11843 return false; 11844 11845 Diag(SS.getRange().getBegin(), 11846 diag::err_using_decl_nested_name_specifier_is_not_base_class) 11847 << SS.getScopeRep() 11848 << cast<CXXRecordDecl>(CurContext) 11849 << SS.getRange(); 11850 11851 return true; 11852 } 11853 11854 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS, 11855 MultiTemplateParamsArg TemplateParamLists, 11856 SourceLocation UsingLoc, UnqualifiedId &Name, 11857 const ParsedAttributesView &AttrList, 11858 TypeResult Type, Decl *DeclFromDeclSpec) { 11859 // Skip up to the relevant declaration scope. 11860 while (S->isTemplateParamScope()) 11861 S = S->getParent(); 11862 assert((S->getFlags() & Scope::DeclScope) && 11863 "got alias-declaration outside of declaration scope"); 11864 11865 if (Type.isInvalid()) 11866 return nullptr; 11867 11868 bool Invalid = false; 11869 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 11870 TypeSourceInfo *TInfo = nullptr; 11871 GetTypeFromParser(Type.get(), &TInfo); 11872 11873 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 11874 return nullptr; 11875 11876 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 11877 UPPC_DeclarationType)) { 11878 Invalid = true; 11879 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 11880 TInfo->getTypeLoc().getBeginLoc()); 11881 } 11882 11883 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 11884 TemplateParamLists.size() 11885 ? forRedeclarationInCurContext() 11886 : ForVisibleRedeclaration); 11887 LookupName(Previous, S); 11888 11889 // Warn about shadowing the name of a template parameter. 11890 if (Previous.isSingleResult() && 11891 Previous.getFoundDecl()->isTemplateParameter()) { 11892 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 11893 Previous.clear(); 11894 } 11895 11896 assert(Name.Kind == UnqualifiedIdKind::IK_Identifier && 11897 "name in alias declaration must be an identifier"); 11898 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 11899 Name.StartLocation, 11900 Name.Identifier, TInfo); 11901 11902 NewTD->setAccess(AS); 11903 11904 if (Invalid) 11905 NewTD->setInvalidDecl(); 11906 11907 ProcessDeclAttributeList(S, NewTD, AttrList); 11908 AddPragmaAttributes(S, NewTD); 11909 11910 CheckTypedefForVariablyModifiedType(S, NewTD); 11911 Invalid |= NewTD->isInvalidDecl(); 11912 11913 bool Redeclaration = false; 11914 11915 NamedDecl *NewND; 11916 if (TemplateParamLists.size()) { 11917 TypeAliasTemplateDecl *OldDecl = nullptr; 11918 TemplateParameterList *OldTemplateParams = nullptr; 11919 11920 if (TemplateParamLists.size() != 1) { 11921 Diag(UsingLoc, diag::err_alias_template_extra_headers) 11922 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 11923 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 11924 } 11925 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 11926 11927 // Check that we can declare a template here. 11928 if (CheckTemplateDeclScope(S, TemplateParams)) 11929 return nullptr; 11930 11931 // Only consider previous declarations in the same scope. 11932 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 11933 /*ExplicitInstantiationOrSpecialization*/false); 11934 if (!Previous.empty()) { 11935 Redeclaration = true; 11936 11937 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 11938 if (!OldDecl && !Invalid) { 11939 Diag(UsingLoc, diag::err_redefinition_different_kind) 11940 << Name.Identifier; 11941 11942 NamedDecl *OldD = Previous.getRepresentativeDecl(); 11943 if (OldD->getLocation().isValid()) 11944 Diag(OldD->getLocation(), diag::note_previous_definition); 11945 11946 Invalid = true; 11947 } 11948 11949 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 11950 if (TemplateParameterListsAreEqual(TemplateParams, 11951 OldDecl->getTemplateParameters(), 11952 /*Complain=*/true, 11953 TPL_TemplateMatch)) 11954 OldTemplateParams = 11955 OldDecl->getMostRecentDecl()->getTemplateParameters(); 11956 else 11957 Invalid = true; 11958 11959 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 11960 if (!Invalid && 11961 !Context.hasSameType(OldTD->getUnderlyingType(), 11962 NewTD->getUnderlyingType())) { 11963 // FIXME: The C++0x standard does not clearly say this is ill-formed, 11964 // but we can't reasonably accept it. 11965 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 11966 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 11967 if (OldTD->getLocation().isValid()) 11968 Diag(OldTD->getLocation(), diag::note_previous_definition); 11969 Invalid = true; 11970 } 11971 } 11972 } 11973 11974 // Merge any previous default template arguments into our parameters, 11975 // and check the parameter list. 11976 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 11977 TPC_TypeAliasTemplate)) 11978 return nullptr; 11979 11980 TypeAliasTemplateDecl *NewDecl = 11981 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 11982 Name.Identifier, TemplateParams, 11983 NewTD); 11984 NewTD->setDescribedAliasTemplate(NewDecl); 11985 11986 NewDecl->setAccess(AS); 11987 11988 if (Invalid) 11989 NewDecl->setInvalidDecl(); 11990 else if (OldDecl) { 11991 NewDecl->setPreviousDecl(OldDecl); 11992 CheckRedeclarationModuleOwnership(NewDecl, OldDecl); 11993 } 11994 11995 NewND = NewDecl; 11996 } else { 11997 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { 11998 setTagNameForLinkagePurposes(TD, NewTD); 11999 handleTagNumbering(TD, S); 12000 } 12001 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 12002 NewND = NewTD; 12003 } 12004 12005 PushOnScopeChains(NewND, S); 12006 ActOnDocumentableDecl(NewND); 12007 return NewND; 12008 } 12009 12010 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 12011 SourceLocation AliasLoc, 12012 IdentifierInfo *Alias, CXXScopeSpec &SS, 12013 SourceLocation IdentLoc, 12014 IdentifierInfo *Ident) { 12015 12016 // Lookup the namespace name. 12017 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 12018 LookupParsedName(R, S, &SS); 12019 12020 if (R.isAmbiguous()) 12021 return nullptr; 12022 12023 if (R.empty()) { 12024 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 12025 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 12026 return nullptr; 12027 } 12028 } 12029 assert(!R.isAmbiguous() && !R.empty()); 12030 NamedDecl *ND = R.getRepresentativeDecl(); 12031 12032 // Check if we have a previous declaration with the same name. 12033 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName, 12034 ForVisibleRedeclaration); 12035 LookupName(PrevR, S); 12036 12037 // Check we're not shadowing a template parameter. 12038 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) { 12039 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl()); 12040 PrevR.clear(); 12041 } 12042 12043 // Filter out any other lookup result from an enclosing scope. 12044 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false, 12045 /*AllowInlineNamespace*/false); 12046 12047 // Find the previous declaration and check that we can redeclare it. 12048 NamespaceAliasDecl *Prev = nullptr; 12049 if (PrevR.isSingleResult()) { 12050 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl(); 12051 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 12052 // We already have an alias with the same name that points to the same 12053 // namespace; check that it matches. 12054 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) { 12055 Prev = AD; 12056 } else if (isVisible(PrevDecl)) { 12057 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 12058 << Alias; 12059 Diag(AD->getLocation(), diag::note_previous_namespace_alias) 12060 << AD->getNamespace(); 12061 return nullptr; 12062 } 12063 } else if (isVisible(PrevDecl)) { 12064 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl()) 12065 ? diag::err_redefinition 12066 : diag::err_redefinition_different_kind; 12067 Diag(AliasLoc, DiagID) << Alias; 12068 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 12069 return nullptr; 12070 } 12071 } 12072 12073 // The use of a nested name specifier may trigger deprecation warnings. 12074 DiagnoseUseOfDecl(ND, IdentLoc); 12075 12076 NamespaceAliasDecl *AliasDecl = 12077 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 12078 Alias, SS.getWithLocInContext(Context), 12079 IdentLoc, ND); 12080 if (Prev) 12081 AliasDecl->setPreviousDecl(Prev); 12082 12083 PushOnScopeChains(AliasDecl, S); 12084 return AliasDecl; 12085 } 12086 12087 namespace { 12088 struct SpecialMemberExceptionSpecInfo 12089 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> { 12090 SourceLocation Loc; 12091 Sema::ImplicitExceptionSpecification ExceptSpec; 12092 12093 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD, 12094 Sema::CXXSpecialMember CSM, 12095 Sema::InheritedConstructorInfo *ICI, 12096 SourceLocation Loc) 12097 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {} 12098 12099 bool visitBase(CXXBaseSpecifier *Base); 12100 bool visitField(FieldDecl *FD); 12101 12102 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 12103 unsigned Quals); 12104 12105 void visitSubobjectCall(Subobject Subobj, 12106 Sema::SpecialMemberOverloadResult SMOR); 12107 }; 12108 } 12109 12110 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) { 12111 auto *RT = Base->getType()->getAs<RecordType>(); 12112 if (!RT) 12113 return false; 12114 12115 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl()); 12116 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 12117 if (auto *BaseCtor = SMOR.getMethod()) { 12118 visitSubobjectCall(Base, BaseCtor); 12119 return false; 12120 } 12121 12122 visitClassSubobject(BaseClass, Base, 0); 12123 return false; 12124 } 12125 12126 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) { 12127 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) { 12128 Expr *E = FD->getInClassInitializer(); 12129 if (!E) 12130 // FIXME: It's a little wasteful to build and throw away a 12131 // CXXDefaultInitExpr here. 12132 // FIXME: We should have a single context note pointing at Loc, and 12133 // this location should be MD->getLocation() instead, since that's 12134 // the location where we actually use the default init expression. 12135 E = S.BuildCXXDefaultInitExpr(Loc, FD).get(); 12136 if (E) 12137 ExceptSpec.CalledExpr(E); 12138 } else if (auto *RT = S.Context.getBaseElementType(FD->getType()) 12139 ->getAs<RecordType>()) { 12140 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD, 12141 FD->getType().getCVRQualifiers()); 12142 } 12143 return false; 12144 } 12145 12146 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class, 12147 Subobject Subobj, 12148 unsigned Quals) { 12149 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 12150 bool IsMutable = Field && Field->isMutable(); 12151 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable)); 12152 } 12153 12154 void SpecialMemberExceptionSpecInfo::visitSubobjectCall( 12155 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) { 12156 // Note, if lookup fails, it doesn't matter what exception specification we 12157 // choose because the special member will be deleted. 12158 if (CXXMethodDecl *MD = SMOR.getMethod()) 12159 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD); 12160 } 12161 12162 namespace { 12163 /// RAII object to register a special member as being currently declared. 12164 struct ComputingExceptionSpec { 12165 Sema &S; 12166 12167 ComputingExceptionSpec(Sema &S, CXXMethodDecl *MD, SourceLocation Loc) 12168 : S(S) { 12169 Sema::CodeSynthesisContext Ctx; 12170 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation; 12171 Ctx.PointOfInstantiation = Loc; 12172 Ctx.Entity = MD; 12173 S.pushCodeSynthesisContext(Ctx); 12174 } 12175 ~ComputingExceptionSpec() { 12176 S.popCodeSynthesisContext(); 12177 } 12178 }; 12179 } 12180 12181 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) { 12182 llvm::APSInt Result; 12183 ExprResult Converted = CheckConvertedConstantExpression( 12184 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool); 12185 ExplicitSpec.setExpr(Converted.get()); 12186 if (Converted.isUsable() && !Converted.get()->isValueDependent()) { 12187 ExplicitSpec.setKind(Result.getBoolValue() 12188 ? ExplicitSpecKind::ResolvedTrue 12189 : ExplicitSpecKind::ResolvedFalse); 12190 return true; 12191 } 12192 ExplicitSpec.setKind(ExplicitSpecKind::Unresolved); 12193 return false; 12194 } 12195 12196 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) { 12197 ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved); 12198 if (!ExplicitExpr->isTypeDependent()) 12199 tryResolveExplicitSpecifier(ES); 12200 return ES; 12201 } 12202 12203 static Sema::ImplicitExceptionSpecification 12204 ComputeDefaultedSpecialMemberExceptionSpec( 12205 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 12206 Sema::InheritedConstructorInfo *ICI) { 12207 ComputingExceptionSpec CES(S, MD, Loc); 12208 12209 CXXRecordDecl *ClassDecl = MD->getParent(); 12210 12211 // C++ [except.spec]p14: 12212 // An implicitly declared special member function (Clause 12) shall have an 12213 // exception-specification. [...] 12214 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation()); 12215 if (ClassDecl->isInvalidDecl()) 12216 return Info.ExceptSpec; 12217 12218 // FIXME: If this diagnostic fires, we're probably missing a check for 12219 // attempting to resolve an exception specification before it's known 12220 // at a higher level. 12221 if (S.RequireCompleteType(MD->getLocation(), 12222 S.Context.getRecordType(ClassDecl), 12223 diag::err_exception_spec_incomplete_type)) 12224 return Info.ExceptSpec; 12225 12226 // C++1z [except.spec]p7: 12227 // [Look for exceptions thrown by] a constructor selected [...] to 12228 // initialize a potentially constructed subobject, 12229 // C++1z [except.spec]p8: 12230 // The exception specification for an implicitly-declared destructor, or a 12231 // destructor without a noexcept-specifier, is potentially-throwing if and 12232 // only if any of the destructors for any of its potentially constructed 12233 // subojects is potentially throwing. 12234 // FIXME: We respect the first rule but ignore the "potentially constructed" 12235 // in the second rule to resolve a core issue (no number yet) that would have 12236 // us reject: 12237 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; }; 12238 // struct B : A {}; 12239 // struct C : B { void f(); }; 12240 // ... due to giving B::~B() a non-throwing exception specification. 12241 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases 12242 : Info.VisitAllBases); 12243 12244 return Info.ExceptSpec; 12245 } 12246 12247 namespace { 12248 /// RAII object to register a special member as being currently declared. 12249 struct DeclaringSpecialMember { 12250 Sema &S; 12251 Sema::SpecialMemberDecl D; 12252 Sema::ContextRAII SavedContext; 12253 bool WasAlreadyBeingDeclared; 12254 12255 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 12256 : S(S), D(RD, CSM), SavedContext(S, RD) { 12257 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 12258 if (WasAlreadyBeingDeclared) 12259 // This almost never happens, but if it does, ensure that our cache 12260 // doesn't contain a stale result. 12261 S.SpecialMemberCache.clear(); 12262 else { 12263 // Register a note to be produced if we encounter an error while 12264 // declaring the special member. 12265 Sema::CodeSynthesisContext Ctx; 12266 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember; 12267 // FIXME: We don't have a location to use here. Using the class's 12268 // location maintains the fiction that we declare all special members 12269 // with the class, but (1) it's not clear that lying about that helps our 12270 // users understand what's going on, and (2) there may be outer contexts 12271 // on the stack (some of which are relevant) and printing them exposes 12272 // our lies. 12273 Ctx.PointOfInstantiation = RD->getLocation(); 12274 Ctx.Entity = RD; 12275 Ctx.SpecialMember = CSM; 12276 S.pushCodeSynthesisContext(Ctx); 12277 } 12278 } 12279 ~DeclaringSpecialMember() { 12280 if (!WasAlreadyBeingDeclared) { 12281 S.SpecialMembersBeingDeclared.erase(D); 12282 S.popCodeSynthesisContext(); 12283 } 12284 } 12285 12286 /// Are we already trying to declare this special member? 12287 bool isAlreadyBeingDeclared() const { 12288 return WasAlreadyBeingDeclared; 12289 } 12290 }; 12291 } 12292 12293 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) { 12294 // Look up any existing declarations, but don't trigger declaration of all 12295 // implicit special members with this name. 12296 DeclarationName Name = FD->getDeclName(); 12297 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName, 12298 ForExternalRedeclaration); 12299 for (auto *D : FD->getParent()->lookup(Name)) 12300 if (auto *Acceptable = R.getAcceptableDecl(D)) 12301 R.addDecl(Acceptable); 12302 R.resolveKind(); 12303 R.suppressDiagnostics(); 12304 12305 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false); 12306 } 12307 12308 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem, 12309 QualType ResultTy, 12310 ArrayRef<QualType> Args) { 12311 // Build an exception specification pointing back at this constructor. 12312 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem); 12313 12314 LangAS AS = getDefaultCXXMethodAddrSpace(); 12315 if (AS != LangAS::Default) { 12316 EPI.TypeQuals.addAddressSpace(AS); 12317 } 12318 12319 auto QT = Context.getFunctionType(ResultTy, Args, EPI); 12320 SpecialMem->setType(QT); 12321 } 12322 12323 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 12324 CXXRecordDecl *ClassDecl) { 12325 // C++ [class.ctor]p5: 12326 // A default constructor for a class X is a constructor of class X 12327 // that can be called without an argument. If there is no 12328 // user-declared constructor for class X, a default constructor is 12329 // implicitly declared. An implicitly-declared default constructor 12330 // is an inline public member of its class. 12331 assert(ClassDecl->needsImplicitDefaultConstructor() && 12332 "Should not build implicit default constructor!"); 12333 12334 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 12335 if (DSM.isAlreadyBeingDeclared()) 12336 return nullptr; 12337 12338 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12339 CXXDefaultConstructor, 12340 false); 12341 12342 // Create the actual constructor declaration. 12343 CanQualType ClassType 12344 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 12345 SourceLocation ClassLoc = ClassDecl->getLocation(); 12346 DeclarationName Name 12347 = Context.DeclarationNames.getCXXConstructorName(ClassType); 12348 DeclarationNameInfo NameInfo(Name, ClassLoc); 12349 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 12350 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(), 12351 /*TInfo=*/nullptr, ExplicitSpecifier(), 12352 /*isInline=*/true, /*isImplicitlyDeclared=*/true, 12353 Constexpr ? CSK_constexpr : CSK_unspecified); 12354 DefaultCon->setAccess(AS_public); 12355 DefaultCon->setDefaulted(); 12356 12357 if (getLangOpts().CUDA) { 12358 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 12359 DefaultCon, 12360 /* ConstRHS */ false, 12361 /* Diagnose */ false); 12362 } 12363 12364 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None); 12365 12366 // We don't need to use SpecialMemberIsTrivial here; triviality for default 12367 // constructors is easy to compute. 12368 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 12369 12370 // Note that we have declared this constructor. 12371 ++getASTContext().NumImplicitDefaultConstructorsDeclared; 12372 12373 Scope *S = getScopeForContext(ClassDecl); 12374 CheckImplicitSpecialMemberDeclaration(S, DefaultCon); 12375 12376 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 12377 SetDeclDeleted(DefaultCon, ClassLoc); 12378 12379 if (S) 12380 PushOnScopeChains(DefaultCon, S, false); 12381 ClassDecl->addDecl(DefaultCon); 12382 12383 return DefaultCon; 12384 } 12385 12386 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 12387 CXXConstructorDecl *Constructor) { 12388 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 12389 !Constructor->doesThisDeclarationHaveABody() && 12390 !Constructor->isDeleted()) && 12391 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 12392 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 12393 return; 12394 12395 CXXRecordDecl *ClassDecl = Constructor->getParent(); 12396 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 12397 12398 SynthesizedFunctionScope Scope(*this, Constructor); 12399 12400 // The exception specification is needed because we are defining the 12401 // function. 12402 ResolveExceptionSpec(CurrentLocation, 12403 Constructor->getType()->castAs<FunctionProtoType>()); 12404 MarkVTableUsed(CurrentLocation, ClassDecl); 12405 12406 // Add a context note for diagnostics produced after this point. 12407 Scope.addContextNote(CurrentLocation); 12408 12409 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) { 12410 Constructor->setInvalidDecl(); 12411 return; 12412 } 12413 12414 SourceLocation Loc = Constructor->getEndLoc().isValid() 12415 ? Constructor->getEndLoc() 12416 : Constructor->getLocation(); 12417 Constructor->setBody(new (Context) CompoundStmt(Loc)); 12418 Constructor->markUsed(Context); 12419 12420 if (ASTMutationListener *L = getASTMutationListener()) { 12421 L->CompletedImplicitDefinition(Constructor); 12422 } 12423 12424 DiagnoseUninitializedFields(*this, Constructor); 12425 } 12426 12427 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 12428 // Perform any delayed checks on exception specifications. 12429 CheckDelayedMemberExceptionSpecs(); 12430 } 12431 12432 /// Find or create the fake constructor we synthesize to model constructing an 12433 /// object of a derived class via a constructor of a base class. 12434 CXXConstructorDecl * 12435 Sema::findInheritingConstructor(SourceLocation Loc, 12436 CXXConstructorDecl *BaseCtor, 12437 ConstructorUsingShadowDecl *Shadow) { 12438 CXXRecordDecl *Derived = Shadow->getParent(); 12439 SourceLocation UsingLoc = Shadow->getLocation(); 12440 12441 // FIXME: Add a new kind of DeclarationName for an inherited constructor. 12442 // For now we use the name of the base class constructor as a member of the 12443 // derived class to indicate a (fake) inherited constructor name. 12444 DeclarationName Name = BaseCtor->getDeclName(); 12445 12446 // Check to see if we already have a fake constructor for this inherited 12447 // constructor call. 12448 for (NamedDecl *Ctor : Derived->lookup(Name)) 12449 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor) 12450 ->getInheritedConstructor() 12451 .getConstructor(), 12452 BaseCtor)) 12453 return cast<CXXConstructorDecl>(Ctor); 12454 12455 DeclarationNameInfo NameInfo(Name, UsingLoc); 12456 TypeSourceInfo *TInfo = 12457 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc); 12458 FunctionProtoTypeLoc ProtoLoc = 12459 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 12460 12461 // Check the inherited constructor is valid and find the list of base classes 12462 // from which it was inherited. 12463 InheritedConstructorInfo ICI(*this, Loc, Shadow); 12464 12465 bool Constexpr = 12466 BaseCtor->isConstexpr() && 12467 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor, 12468 false, BaseCtor, &ICI); 12469 12470 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 12471 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo, 12472 BaseCtor->getExplicitSpecifier(), /*isInline=*/true, 12473 /*isImplicitlyDeclared=*/true, 12474 Constexpr ? BaseCtor->getConstexprKind() : CSK_unspecified, 12475 InheritedConstructor(Shadow, BaseCtor)); 12476 if (Shadow->isInvalidDecl()) 12477 DerivedCtor->setInvalidDecl(); 12478 12479 // Build an unevaluated exception specification for this fake constructor. 12480 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>(); 12481 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 12482 EPI.ExceptionSpec.Type = EST_Unevaluated; 12483 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 12484 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 12485 FPT->getParamTypes(), EPI)); 12486 12487 // Build the parameter declarations. 12488 SmallVector<ParmVarDecl *, 16> ParamDecls; 12489 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 12490 TypeSourceInfo *TInfo = 12491 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 12492 ParmVarDecl *PD = ParmVarDecl::Create( 12493 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 12494 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr); 12495 PD->setScopeInfo(0, I); 12496 PD->setImplicit(); 12497 // Ensure attributes are propagated onto parameters (this matters for 12498 // format, pass_object_size, ...). 12499 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I)); 12500 ParamDecls.push_back(PD); 12501 ProtoLoc.setParam(I, PD); 12502 } 12503 12504 // Set up the new constructor. 12505 assert(!BaseCtor->isDeleted() && "should not use deleted constructor"); 12506 DerivedCtor->setAccess(BaseCtor->getAccess()); 12507 DerivedCtor->setParams(ParamDecls); 12508 Derived->addDecl(DerivedCtor); 12509 12510 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI)) 12511 SetDeclDeleted(DerivedCtor, UsingLoc); 12512 12513 return DerivedCtor; 12514 } 12515 12516 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) { 12517 InheritedConstructorInfo ICI(*this, Ctor->getLocation(), 12518 Ctor->getInheritedConstructor().getShadowDecl()); 12519 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI, 12520 /*Diagnose*/true); 12521 } 12522 12523 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 12524 CXXConstructorDecl *Constructor) { 12525 CXXRecordDecl *ClassDecl = Constructor->getParent(); 12526 assert(Constructor->getInheritedConstructor() && 12527 !Constructor->doesThisDeclarationHaveABody() && 12528 !Constructor->isDeleted()); 12529 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 12530 return; 12531 12532 // Initializations are performed "as if by a defaulted default constructor", 12533 // so enter the appropriate scope. 12534 SynthesizedFunctionScope Scope(*this, Constructor); 12535 12536 // The exception specification is needed because we are defining the 12537 // function. 12538 ResolveExceptionSpec(CurrentLocation, 12539 Constructor->getType()->castAs<FunctionProtoType>()); 12540 MarkVTableUsed(CurrentLocation, ClassDecl); 12541 12542 // Add a context note for diagnostics produced after this point. 12543 Scope.addContextNote(CurrentLocation); 12544 12545 ConstructorUsingShadowDecl *Shadow = 12546 Constructor->getInheritedConstructor().getShadowDecl(); 12547 CXXConstructorDecl *InheritedCtor = 12548 Constructor->getInheritedConstructor().getConstructor(); 12549 12550 // [class.inhctor.init]p1: 12551 // initialization proceeds as if a defaulted default constructor is used to 12552 // initialize the D object and each base class subobject from which the 12553 // constructor was inherited 12554 12555 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow); 12556 CXXRecordDecl *RD = Shadow->getParent(); 12557 SourceLocation InitLoc = Shadow->getLocation(); 12558 12559 // Build explicit initializers for all base classes from which the 12560 // constructor was inherited. 12561 SmallVector<CXXCtorInitializer*, 8> Inits; 12562 for (bool VBase : {false, true}) { 12563 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) { 12564 if (B.isVirtual() != VBase) 12565 continue; 12566 12567 auto *BaseRD = B.getType()->getAsCXXRecordDecl(); 12568 if (!BaseRD) 12569 continue; 12570 12571 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor); 12572 if (!BaseCtor.first) 12573 continue; 12574 12575 MarkFunctionReferenced(CurrentLocation, BaseCtor.first); 12576 ExprResult Init = new (Context) CXXInheritedCtorInitExpr( 12577 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second); 12578 12579 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc); 12580 Inits.push_back(new (Context) CXXCtorInitializer( 12581 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc, 12582 SourceLocation())); 12583 } 12584 } 12585 12586 // We now proceed as if for a defaulted default constructor, with the relevant 12587 // initializers replaced. 12588 12589 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) { 12590 Constructor->setInvalidDecl(); 12591 return; 12592 } 12593 12594 Constructor->setBody(new (Context) CompoundStmt(InitLoc)); 12595 Constructor->markUsed(Context); 12596 12597 if (ASTMutationListener *L = getASTMutationListener()) { 12598 L->CompletedImplicitDefinition(Constructor); 12599 } 12600 12601 DiagnoseUninitializedFields(*this, Constructor); 12602 } 12603 12604 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 12605 // C++ [class.dtor]p2: 12606 // If a class has no user-declared destructor, a destructor is 12607 // declared implicitly. An implicitly-declared destructor is an 12608 // inline public member of its class. 12609 assert(ClassDecl->needsImplicitDestructor()); 12610 12611 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 12612 if (DSM.isAlreadyBeingDeclared()) 12613 return nullptr; 12614 12615 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12616 CXXDestructor, 12617 false); 12618 12619 // Create the actual destructor declaration. 12620 CanQualType ClassType 12621 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 12622 SourceLocation ClassLoc = ClassDecl->getLocation(); 12623 DeclarationName Name 12624 = Context.DeclarationNames.getCXXDestructorName(ClassType); 12625 DeclarationNameInfo NameInfo(Name, ClassLoc); 12626 CXXDestructorDecl *Destructor = 12627 CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 12628 QualType(), nullptr, /*isInline=*/true, 12629 /*isImplicitlyDeclared=*/true, 12630 Constexpr ? CSK_constexpr : CSK_unspecified); 12631 Destructor->setAccess(AS_public); 12632 Destructor->setDefaulted(); 12633 12634 if (getLangOpts().CUDA) { 12635 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 12636 Destructor, 12637 /* ConstRHS */ false, 12638 /* Diagnose */ false); 12639 } 12640 12641 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None); 12642 12643 // We don't need to use SpecialMemberIsTrivial here; triviality for 12644 // destructors is easy to compute. 12645 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 12646 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() || 12647 ClassDecl->hasTrivialDestructorForCall()); 12648 12649 // Note that we have declared this destructor. 12650 ++getASTContext().NumImplicitDestructorsDeclared; 12651 12652 Scope *S = getScopeForContext(ClassDecl); 12653 CheckImplicitSpecialMemberDeclaration(S, Destructor); 12654 12655 // We can't check whether an implicit destructor is deleted before we complete 12656 // the definition of the class, because its validity depends on the alignment 12657 // of the class. We'll check this from ActOnFields once the class is complete. 12658 if (ClassDecl->isCompleteDefinition() && 12659 ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 12660 SetDeclDeleted(Destructor, ClassLoc); 12661 12662 // Introduce this destructor into its scope. 12663 if (S) 12664 PushOnScopeChains(Destructor, S, false); 12665 ClassDecl->addDecl(Destructor); 12666 12667 return Destructor; 12668 } 12669 12670 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 12671 CXXDestructorDecl *Destructor) { 12672 assert((Destructor->isDefaulted() && 12673 !Destructor->doesThisDeclarationHaveABody() && 12674 !Destructor->isDeleted()) && 12675 "DefineImplicitDestructor - call it for implicit default dtor"); 12676 if (Destructor->willHaveBody() || Destructor->isInvalidDecl()) 12677 return; 12678 12679 CXXRecordDecl *ClassDecl = Destructor->getParent(); 12680 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 12681 12682 SynthesizedFunctionScope Scope(*this, Destructor); 12683 12684 // The exception specification is needed because we are defining the 12685 // function. 12686 ResolveExceptionSpec(CurrentLocation, 12687 Destructor->getType()->castAs<FunctionProtoType>()); 12688 MarkVTableUsed(CurrentLocation, ClassDecl); 12689 12690 // Add a context note for diagnostics produced after this point. 12691 Scope.addContextNote(CurrentLocation); 12692 12693 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 12694 Destructor->getParent()); 12695 12696 if (CheckDestructor(Destructor)) { 12697 Destructor->setInvalidDecl(); 12698 return; 12699 } 12700 12701 SourceLocation Loc = Destructor->getEndLoc().isValid() 12702 ? Destructor->getEndLoc() 12703 : Destructor->getLocation(); 12704 Destructor->setBody(new (Context) CompoundStmt(Loc)); 12705 Destructor->markUsed(Context); 12706 12707 if (ASTMutationListener *L = getASTMutationListener()) { 12708 L->CompletedImplicitDefinition(Destructor); 12709 } 12710 } 12711 12712 /// Perform any semantic analysis which needs to be delayed until all 12713 /// pending class member declarations have been parsed. 12714 void Sema::ActOnFinishCXXMemberDecls() { 12715 // If the context is an invalid C++ class, just suppress these checks. 12716 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 12717 if (Record->isInvalidDecl()) { 12718 DelayedOverridingExceptionSpecChecks.clear(); 12719 DelayedEquivalentExceptionSpecChecks.clear(); 12720 return; 12721 } 12722 checkForMultipleExportedDefaultConstructors(*this, Record); 12723 } 12724 } 12725 12726 void Sema::ActOnFinishCXXNonNestedClass() { 12727 referenceDLLExportedClassMethods(); 12728 12729 if (!DelayedDllExportMemberFunctions.empty()) { 12730 SmallVector<CXXMethodDecl*, 4> WorkList; 12731 std::swap(DelayedDllExportMemberFunctions, WorkList); 12732 for (CXXMethodDecl *M : WorkList) { 12733 DefineImplicitSpecialMember(*this, M, M->getLocation()); 12734 12735 // Pass the method to the consumer to get emitted. This is not necessary 12736 // for explicit instantiation definitions, as they will get emitted 12737 // anyway. 12738 if (M->getParent()->getTemplateSpecializationKind() != 12739 TSK_ExplicitInstantiationDefinition) 12740 ActOnFinishInlineFunctionDef(M); 12741 } 12742 } 12743 } 12744 12745 void Sema::referenceDLLExportedClassMethods() { 12746 if (!DelayedDllExportClasses.empty()) { 12747 // Calling ReferenceDllExportedMembers might cause the current function to 12748 // be called again, so use a local copy of DelayedDllExportClasses. 12749 SmallVector<CXXRecordDecl *, 4> WorkList; 12750 std::swap(DelayedDllExportClasses, WorkList); 12751 for (CXXRecordDecl *Class : WorkList) 12752 ReferenceDllExportedMembers(*this, Class); 12753 } 12754 } 12755 12756 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) { 12757 assert(getLangOpts().CPlusPlus11 && 12758 "adjusting dtor exception specs was introduced in c++11"); 12759 12760 if (Destructor->isDependentContext()) 12761 return; 12762 12763 // C++11 [class.dtor]p3: 12764 // A declaration of a destructor that does not have an exception- 12765 // specification is implicitly considered to have the same exception- 12766 // specification as an implicit declaration. 12767 const FunctionProtoType *DtorType = Destructor->getType()-> 12768 getAs<FunctionProtoType>(); 12769 if (DtorType->hasExceptionSpec()) 12770 return; 12771 12772 // Replace the destructor's type, building off the existing one. Fortunately, 12773 // the only thing of interest in the destructor type is its extended info. 12774 // The return and arguments are fixed. 12775 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 12776 EPI.ExceptionSpec.Type = EST_Unevaluated; 12777 EPI.ExceptionSpec.SourceDecl = Destructor; 12778 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 12779 12780 // FIXME: If the destructor has a body that could throw, and the newly created 12781 // spec doesn't allow exceptions, we should emit a warning, because this 12782 // change in behavior can break conforming C++03 programs at runtime. 12783 // However, we don't have a body or an exception specification yet, so it 12784 // needs to be done somewhere else. 12785 } 12786 12787 namespace { 12788 /// An abstract base class for all helper classes used in building the 12789 // copy/move operators. These classes serve as factory functions and help us 12790 // avoid using the same Expr* in the AST twice. 12791 class ExprBuilder { 12792 ExprBuilder(const ExprBuilder&) = delete; 12793 ExprBuilder &operator=(const ExprBuilder&) = delete; 12794 12795 protected: 12796 static Expr *assertNotNull(Expr *E) { 12797 assert(E && "Expression construction must not fail."); 12798 return E; 12799 } 12800 12801 public: 12802 ExprBuilder() {} 12803 virtual ~ExprBuilder() {} 12804 12805 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 12806 }; 12807 12808 class RefBuilder: public ExprBuilder { 12809 VarDecl *Var; 12810 QualType VarType; 12811 12812 public: 12813 Expr *build(Sema &S, SourceLocation Loc) const override { 12814 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc)); 12815 } 12816 12817 RefBuilder(VarDecl *Var, QualType VarType) 12818 : Var(Var), VarType(VarType) {} 12819 }; 12820 12821 class ThisBuilder: public ExprBuilder { 12822 public: 12823 Expr *build(Sema &S, SourceLocation Loc) const override { 12824 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 12825 } 12826 }; 12827 12828 class CastBuilder: public ExprBuilder { 12829 const ExprBuilder &Builder; 12830 QualType Type; 12831 ExprValueKind Kind; 12832 const CXXCastPath &Path; 12833 12834 public: 12835 Expr *build(Sema &S, SourceLocation Loc) const override { 12836 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 12837 CK_UncheckedDerivedToBase, Kind, 12838 &Path).get()); 12839 } 12840 12841 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 12842 const CXXCastPath &Path) 12843 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 12844 }; 12845 12846 class DerefBuilder: public ExprBuilder { 12847 const ExprBuilder &Builder; 12848 12849 public: 12850 Expr *build(Sema &S, SourceLocation Loc) const override { 12851 return assertNotNull( 12852 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 12853 } 12854 12855 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 12856 }; 12857 12858 class MemberBuilder: public ExprBuilder { 12859 const ExprBuilder &Builder; 12860 QualType Type; 12861 CXXScopeSpec SS; 12862 bool IsArrow; 12863 LookupResult &MemberLookup; 12864 12865 public: 12866 Expr *build(Sema &S, SourceLocation Loc) const override { 12867 return assertNotNull(S.BuildMemberReferenceExpr( 12868 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 12869 nullptr, MemberLookup, nullptr, nullptr).get()); 12870 } 12871 12872 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 12873 LookupResult &MemberLookup) 12874 : Builder(Builder), Type(Type), IsArrow(IsArrow), 12875 MemberLookup(MemberLookup) {} 12876 }; 12877 12878 class MoveCastBuilder: public ExprBuilder { 12879 const ExprBuilder &Builder; 12880 12881 public: 12882 Expr *build(Sema &S, SourceLocation Loc) const override { 12883 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 12884 } 12885 12886 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 12887 }; 12888 12889 class LvalueConvBuilder: public ExprBuilder { 12890 const ExprBuilder &Builder; 12891 12892 public: 12893 Expr *build(Sema &S, SourceLocation Loc) const override { 12894 return assertNotNull( 12895 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 12896 } 12897 12898 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 12899 }; 12900 12901 class SubscriptBuilder: public ExprBuilder { 12902 const ExprBuilder &Base; 12903 const ExprBuilder &Index; 12904 12905 public: 12906 Expr *build(Sema &S, SourceLocation Loc) const override { 12907 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 12908 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 12909 } 12910 12911 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 12912 : Base(Base), Index(Index) {} 12913 }; 12914 12915 } // end anonymous namespace 12916 12917 /// When generating a defaulted copy or move assignment operator, if a field 12918 /// should be copied with __builtin_memcpy rather than via explicit assignments, 12919 /// do so. This optimization only applies for arrays of scalars, and for arrays 12920 /// of class type where the selected copy/move-assignment operator is trivial. 12921 static StmtResult 12922 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 12923 const ExprBuilder &ToB, const ExprBuilder &FromB) { 12924 // Compute the size of the memory buffer to be copied. 12925 QualType SizeType = S.Context.getSizeType(); 12926 llvm::APInt Size(S.Context.getTypeSize(SizeType), 12927 S.Context.getTypeSizeInChars(T).getQuantity()); 12928 12929 // Take the address of the field references for "from" and "to". We 12930 // directly construct UnaryOperators here because semantic analysis 12931 // does not permit us to take the address of an xvalue. 12932 Expr *From = FromB.build(S, Loc); 12933 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 12934 S.Context.getPointerType(From->getType()), 12935 VK_RValue, OK_Ordinary, Loc, false); 12936 Expr *To = ToB.build(S, Loc); 12937 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 12938 S.Context.getPointerType(To->getType()), 12939 VK_RValue, OK_Ordinary, Loc, false); 12940 12941 const Type *E = T->getBaseElementTypeUnsafe(); 12942 bool NeedsCollectableMemCpy = 12943 E->isRecordType() && 12944 E->castAs<RecordType>()->getDecl()->hasObjectMember(); 12945 12946 // Create a reference to the __builtin_objc_memmove_collectable function 12947 StringRef MemCpyName = NeedsCollectableMemCpy ? 12948 "__builtin_objc_memmove_collectable" : 12949 "__builtin_memcpy"; 12950 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 12951 Sema::LookupOrdinaryName); 12952 S.LookupName(R, S.TUScope, true); 12953 12954 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 12955 if (!MemCpy) 12956 // Something went horribly wrong earlier, and we will have complained 12957 // about it. 12958 return StmtError(); 12959 12960 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 12961 VK_RValue, Loc, nullptr); 12962 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 12963 12964 Expr *CallArgs[] = { 12965 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 12966 }; 12967 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 12968 Loc, CallArgs, Loc); 12969 12970 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 12971 return Call.getAs<Stmt>(); 12972 } 12973 12974 /// Builds a statement that copies/moves the given entity from \p From to 12975 /// \c To. 12976 /// 12977 /// This routine is used to copy/move the members of a class with an 12978 /// implicitly-declared copy/move assignment operator. When the entities being 12979 /// copied are arrays, this routine builds for loops to copy them. 12980 /// 12981 /// \param S The Sema object used for type-checking. 12982 /// 12983 /// \param Loc The location where the implicit copy/move is being generated. 12984 /// 12985 /// \param T The type of the expressions being copied/moved. Both expressions 12986 /// must have this type. 12987 /// 12988 /// \param To The expression we are copying/moving to. 12989 /// 12990 /// \param From The expression we are copying/moving from. 12991 /// 12992 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 12993 /// Otherwise, it's a non-static member subobject. 12994 /// 12995 /// \param Copying Whether we're copying or moving. 12996 /// 12997 /// \param Depth Internal parameter recording the depth of the recursion. 12998 /// 12999 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 13000 /// if a memcpy should be used instead. 13001 static StmtResult 13002 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 13003 const ExprBuilder &To, const ExprBuilder &From, 13004 bool CopyingBaseSubobject, bool Copying, 13005 unsigned Depth = 0) { 13006 // C++11 [class.copy]p28: 13007 // Each subobject is assigned in the manner appropriate to its type: 13008 // 13009 // - if the subobject is of class type, as if by a call to operator= with 13010 // the subobject as the object expression and the corresponding 13011 // subobject of x as a single function argument (as if by explicit 13012 // qualification; that is, ignoring any possible virtual overriding 13013 // functions in more derived classes); 13014 // 13015 // C++03 [class.copy]p13: 13016 // - if the subobject is of class type, the copy assignment operator for 13017 // the class is used (as if by explicit qualification; that is, 13018 // ignoring any possible virtual overriding functions in more derived 13019 // classes); 13020 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 13021 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 13022 13023 // Look for operator=. 13024 DeclarationName Name 13025 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 13026 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 13027 S.LookupQualifiedName(OpLookup, ClassDecl, false); 13028 13029 // Prior to C++11, filter out any result that isn't a copy/move-assignment 13030 // operator. 13031 if (!S.getLangOpts().CPlusPlus11) { 13032 LookupResult::Filter F = OpLookup.makeFilter(); 13033 while (F.hasNext()) { 13034 NamedDecl *D = F.next(); 13035 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 13036 if (Method->isCopyAssignmentOperator() || 13037 (!Copying && Method->isMoveAssignmentOperator())) 13038 continue; 13039 13040 F.erase(); 13041 } 13042 F.done(); 13043 } 13044 13045 // Suppress the protected check (C++ [class.protected]) for each of the 13046 // assignment operators we found. This strange dance is required when 13047 // we're assigning via a base classes's copy-assignment operator. To 13048 // ensure that we're getting the right base class subobject (without 13049 // ambiguities), we need to cast "this" to that subobject type; to 13050 // ensure that we don't go through the virtual call mechanism, we need 13051 // to qualify the operator= name with the base class (see below). However, 13052 // this means that if the base class has a protected copy assignment 13053 // operator, the protected member access check will fail. So, we 13054 // rewrite "protected" access to "public" access in this case, since we 13055 // know by construction that we're calling from a derived class. 13056 if (CopyingBaseSubobject) { 13057 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 13058 L != LEnd; ++L) { 13059 if (L.getAccess() == AS_protected) 13060 L.setAccess(AS_public); 13061 } 13062 } 13063 13064 // Create the nested-name-specifier that will be used to qualify the 13065 // reference to operator=; this is required to suppress the virtual 13066 // call mechanism. 13067 CXXScopeSpec SS; 13068 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 13069 SS.MakeTrivial(S.Context, 13070 NestedNameSpecifier::Create(S.Context, nullptr, false, 13071 CanonicalT), 13072 Loc); 13073 13074 // Create the reference to operator=. 13075 ExprResult OpEqualRef 13076 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false, 13077 SS, /*TemplateKWLoc=*/SourceLocation(), 13078 /*FirstQualifierInScope=*/nullptr, 13079 OpLookup, 13080 /*TemplateArgs=*/nullptr, /*S*/nullptr, 13081 /*SuppressQualifierCheck=*/true); 13082 if (OpEqualRef.isInvalid()) 13083 return StmtError(); 13084 13085 // Build the call to the assignment operator. 13086 13087 Expr *FromInst = From.build(S, Loc); 13088 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 13089 OpEqualRef.getAs<Expr>(), 13090 Loc, FromInst, Loc); 13091 if (Call.isInvalid()) 13092 return StmtError(); 13093 13094 // If we built a call to a trivial 'operator=' while copying an array, 13095 // bail out. We'll replace the whole shebang with a memcpy. 13096 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 13097 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 13098 return StmtResult((Stmt*)nullptr); 13099 13100 // Convert to an expression-statement, and clean up any produced 13101 // temporaries. 13102 return S.ActOnExprStmt(Call); 13103 } 13104 13105 // - if the subobject is of scalar type, the built-in assignment 13106 // operator is used. 13107 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 13108 if (!ArrayTy) { 13109 ExprResult Assignment = S.CreateBuiltinBinOp( 13110 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 13111 if (Assignment.isInvalid()) 13112 return StmtError(); 13113 return S.ActOnExprStmt(Assignment); 13114 } 13115 13116 // - if the subobject is an array, each element is assigned, in the 13117 // manner appropriate to the element type; 13118 13119 // Construct a loop over the array bounds, e.g., 13120 // 13121 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 13122 // 13123 // that will copy each of the array elements. 13124 QualType SizeType = S.Context.getSizeType(); 13125 13126 // Create the iteration variable. 13127 IdentifierInfo *IterationVarName = nullptr; 13128 { 13129 SmallString<8> Str; 13130 llvm::raw_svector_ostream OS(Str); 13131 OS << "__i" << Depth; 13132 IterationVarName = &S.Context.Idents.get(OS.str()); 13133 } 13134 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 13135 IterationVarName, SizeType, 13136 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 13137 SC_None); 13138 13139 // Initialize the iteration variable to zero. 13140 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 13141 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 13142 13143 // Creates a reference to the iteration variable. 13144 RefBuilder IterationVarRef(IterationVar, SizeType); 13145 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 13146 13147 // Create the DeclStmt that holds the iteration variable. 13148 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 13149 13150 // Subscript the "from" and "to" expressions with the iteration variable. 13151 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 13152 MoveCastBuilder FromIndexMove(FromIndexCopy); 13153 const ExprBuilder *FromIndex; 13154 if (Copying) 13155 FromIndex = &FromIndexCopy; 13156 else 13157 FromIndex = &FromIndexMove; 13158 13159 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 13160 13161 // Build the copy/move for an individual element of the array. 13162 StmtResult Copy = 13163 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 13164 ToIndex, *FromIndex, CopyingBaseSubobject, 13165 Copying, Depth + 1); 13166 // Bail out if copying fails or if we determined that we should use memcpy. 13167 if (Copy.isInvalid() || !Copy.get()) 13168 return Copy; 13169 13170 // Create the comparison against the array bound. 13171 llvm::APInt Upper 13172 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 13173 Expr *Comparison 13174 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc), 13175 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 13176 BO_NE, S.Context.BoolTy, 13177 VK_RValue, OK_Ordinary, Loc, FPOptions()); 13178 13179 // Create the pre-increment of the iteration variable. We can determine 13180 // whether the increment will overflow based on the value of the array 13181 // bound. 13182 Expr *Increment = new (S.Context) 13183 UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType, 13184 VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue()); 13185 13186 // Construct the loop that copies all elements of this array. 13187 return S.ActOnForStmt( 13188 Loc, Loc, InitStmt, 13189 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean), 13190 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get()); 13191 } 13192 13193 static StmtResult 13194 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 13195 const ExprBuilder &To, const ExprBuilder &From, 13196 bool CopyingBaseSubobject, bool Copying) { 13197 // Maybe we should use a memcpy? 13198 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 13199 T.isTriviallyCopyableType(S.Context)) 13200 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 13201 13202 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 13203 CopyingBaseSubobject, 13204 Copying, 0)); 13205 13206 // If we ended up picking a trivial assignment operator for an array of a 13207 // non-trivially-copyable class type, just emit a memcpy. 13208 if (!Result.isInvalid() && !Result.get()) 13209 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 13210 13211 return Result; 13212 } 13213 13214 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 13215 // Note: The following rules are largely analoguous to the copy 13216 // constructor rules. Note that virtual bases are not taken into account 13217 // for determining the argument type of the operator. Note also that 13218 // operators taking an object instead of a reference are allowed. 13219 assert(ClassDecl->needsImplicitCopyAssignment()); 13220 13221 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 13222 if (DSM.isAlreadyBeingDeclared()) 13223 return nullptr; 13224 13225 QualType ArgType = Context.getTypeDeclType(ClassDecl); 13226 LangAS AS = getDefaultCXXMethodAddrSpace(); 13227 if (AS != LangAS::Default) 13228 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 13229 QualType RetType = Context.getLValueReferenceType(ArgType); 13230 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 13231 if (Const) 13232 ArgType = ArgType.withConst(); 13233 13234 ArgType = Context.getLValueReferenceType(ArgType); 13235 13236 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 13237 CXXCopyAssignment, 13238 Const); 13239 13240 // An implicitly-declared copy assignment operator is an inline public 13241 // member of its class. 13242 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 13243 SourceLocation ClassLoc = ClassDecl->getLocation(); 13244 DeclarationNameInfo NameInfo(Name, ClassLoc); 13245 CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create( 13246 Context, ClassDecl, ClassLoc, NameInfo, QualType(), 13247 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 13248 /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified, 13249 SourceLocation()); 13250 CopyAssignment->setAccess(AS_public); 13251 CopyAssignment->setDefaulted(); 13252 CopyAssignment->setImplicit(); 13253 13254 if (getLangOpts().CUDA) { 13255 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 13256 CopyAssignment, 13257 /* ConstRHS */ Const, 13258 /* Diagnose */ false); 13259 } 13260 13261 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType); 13262 13263 // Add the parameter to the operator. 13264 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 13265 ClassLoc, ClassLoc, 13266 /*Id=*/nullptr, ArgType, 13267 /*TInfo=*/nullptr, SC_None, 13268 nullptr); 13269 CopyAssignment->setParams(FromParam); 13270 13271 CopyAssignment->setTrivial( 13272 ClassDecl->needsOverloadResolutionForCopyAssignment() 13273 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 13274 : ClassDecl->hasTrivialCopyAssignment()); 13275 13276 // Note that we have added this copy-assignment operator. 13277 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared; 13278 13279 Scope *S = getScopeForContext(ClassDecl); 13280 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment); 13281 13282 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 13283 SetDeclDeleted(CopyAssignment, ClassLoc); 13284 13285 if (S) 13286 PushOnScopeChains(CopyAssignment, S, false); 13287 ClassDecl->addDecl(CopyAssignment); 13288 13289 return CopyAssignment; 13290 } 13291 13292 /// Diagnose an implicit copy operation for a class which is odr-used, but 13293 /// which is deprecated because the class has a user-declared copy constructor, 13294 /// copy assignment operator, or destructor. 13295 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) { 13296 assert(CopyOp->isImplicit()); 13297 13298 CXXRecordDecl *RD = CopyOp->getParent(); 13299 CXXMethodDecl *UserDeclaredOperation = nullptr; 13300 13301 // In Microsoft mode, assignment operations don't affect constructors and 13302 // vice versa. 13303 if (RD->hasUserDeclaredDestructor()) { 13304 UserDeclaredOperation = RD->getDestructor(); 13305 } else if (!isa<CXXConstructorDecl>(CopyOp) && 13306 RD->hasUserDeclaredCopyConstructor() && 13307 !S.getLangOpts().MSVCCompat) { 13308 // Find any user-declared copy constructor. 13309 for (auto *I : RD->ctors()) { 13310 if (I->isCopyConstructor()) { 13311 UserDeclaredOperation = I; 13312 break; 13313 } 13314 } 13315 assert(UserDeclaredOperation); 13316 } else if (isa<CXXConstructorDecl>(CopyOp) && 13317 RD->hasUserDeclaredCopyAssignment() && 13318 !S.getLangOpts().MSVCCompat) { 13319 // Find any user-declared move assignment operator. 13320 for (auto *I : RD->methods()) { 13321 if (I->isCopyAssignmentOperator()) { 13322 UserDeclaredOperation = I; 13323 break; 13324 } 13325 } 13326 assert(UserDeclaredOperation); 13327 } 13328 13329 if (UserDeclaredOperation && UserDeclaredOperation->isUserProvided()) { 13330 S.Diag(UserDeclaredOperation->getLocation(), 13331 isa<CXXDestructorDecl>(UserDeclaredOperation) 13332 ? diag::warn_deprecated_copy_dtor_operation 13333 : diag::warn_deprecated_copy_operation) 13334 << RD << /*copy assignment*/ !isa<CXXConstructorDecl>(CopyOp); 13335 } 13336 } 13337 13338 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 13339 CXXMethodDecl *CopyAssignOperator) { 13340 assert((CopyAssignOperator->isDefaulted() && 13341 CopyAssignOperator->isOverloadedOperator() && 13342 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 13343 !CopyAssignOperator->doesThisDeclarationHaveABody() && 13344 !CopyAssignOperator->isDeleted()) && 13345 "DefineImplicitCopyAssignment called for wrong function"); 13346 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl()) 13347 return; 13348 13349 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 13350 if (ClassDecl->isInvalidDecl()) { 13351 CopyAssignOperator->setInvalidDecl(); 13352 return; 13353 } 13354 13355 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 13356 13357 // The exception specification is needed because we are defining the 13358 // function. 13359 ResolveExceptionSpec(CurrentLocation, 13360 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 13361 13362 // Add a context note for diagnostics produced after this point. 13363 Scope.addContextNote(CurrentLocation); 13364 13365 // C++11 [class.copy]p18: 13366 // The [definition of an implicitly declared copy assignment operator] is 13367 // deprecated if the class has a user-declared copy constructor or a 13368 // user-declared destructor. 13369 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 13370 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator); 13371 13372 // C++0x [class.copy]p30: 13373 // The implicitly-defined or explicitly-defaulted copy assignment operator 13374 // for a non-union class X performs memberwise copy assignment of its 13375 // subobjects. The direct base classes of X are assigned first, in the 13376 // order of their declaration in the base-specifier-list, and then the 13377 // immediate non-static data members of X are assigned, in the order in 13378 // which they were declared in the class definition. 13379 13380 // The statements that form the synthesized function body. 13381 SmallVector<Stmt*, 8> Statements; 13382 13383 // The parameter for the "other" object, which we are copying from. 13384 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 13385 Qualifiers OtherQuals = Other->getType().getQualifiers(); 13386 QualType OtherRefType = Other->getType(); 13387 if (const LValueReferenceType *OtherRef 13388 = OtherRefType->getAs<LValueReferenceType>()) { 13389 OtherRefType = OtherRef->getPointeeType(); 13390 OtherQuals = OtherRefType.getQualifiers(); 13391 } 13392 13393 // Our location for everything implicitly-generated. 13394 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid() 13395 ? CopyAssignOperator->getEndLoc() 13396 : CopyAssignOperator->getLocation(); 13397 13398 // Builds a DeclRefExpr for the "other" object. 13399 RefBuilder OtherRef(Other, OtherRefType); 13400 13401 // Builds the "this" pointer. 13402 ThisBuilder This; 13403 13404 // Assign base classes. 13405 bool Invalid = false; 13406 for (auto &Base : ClassDecl->bases()) { 13407 // Form the assignment: 13408 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 13409 QualType BaseType = Base.getType().getUnqualifiedType(); 13410 if (!BaseType->isRecordType()) { 13411 Invalid = true; 13412 continue; 13413 } 13414 13415 CXXCastPath BasePath; 13416 BasePath.push_back(&Base); 13417 13418 // Construct the "from" expression, which is an implicit cast to the 13419 // appropriately-qualified base type. 13420 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 13421 VK_LValue, BasePath); 13422 13423 // Dereference "this". 13424 DerefBuilder DerefThis(This); 13425 CastBuilder To(DerefThis, 13426 Context.getQualifiedType( 13427 BaseType, CopyAssignOperator->getMethodQualifiers()), 13428 VK_LValue, BasePath); 13429 13430 // Build the copy. 13431 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 13432 To, From, 13433 /*CopyingBaseSubobject=*/true, 13434 /*Copying=*/true); 13435 if (Copy.isInvalid()) { 13436 CopyAssignOperator->setInvalidDecl(); 13437 return; 13438 } 13439 13440 // Success! Record the copy. 13441 Statements.push_back(Copy.getAs<Expr>()); 13442 } 13443 13444 // Assign non-static members. 13445 for (auto *Field : ClassDecl->fields()) { 13446 // FIXME: We should form some kind of AST representation for the implied 13447 // memcpy in a union copy operation. 13448 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 13449 continue; 13450 13451 if (Field->isInvalidDecl()) { 13452 Invalid = true; 13453 continue; 13454 } 13455 13456 // Check for members of reference type; we can't copy those. 13457 if (Field->getType()->isReferenceType()) { 13458 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 13459 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 13460 Diag(Field->getLocation(), diag::note_declared_at); 13461 Invalid = true; 13462 continue; 13463 } 13464 13465 // Check for members of const-qualified, non-class type. 13466 QualType BaseType = Context.getBaseElementType(Field->getType()); 13467 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 13468 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 13469 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 13470 Diag(Field->getLocation(), diag::note_declared_at); 13471 Invalid = true; 13472 continue; 13473 } 13474 13475 // Suppress assigning zero-width bitfields. 13476 if (Field->isZeroLengthBitField(Context)) 13477 continue; 13478 13479 QualType FieldType = Field->getType().getNonReferenceType(); 13480 if (FieldType->isIncompleteArrayType()) { 13481 assert(ClassDecl->hasFlexibleArrayMember() && 13482 "Incomplete array type is not valid"); 13483 continue; 13484 } 13485 13486 // Build references to the field in the object we're copying from and to. 13487 CXXScopeSpec SS; // Intentionally empty 13488 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 13489 LookupMemberName); 13490 MemberLookup.addDecl(Field); 13491 MemberLookup.resolveKind(); 13492 13493 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 13494 13495 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 13496 13497 // Build the copy of this field. 13498 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 13499 To, From, 13500 /*CopyingBaseSubobject=*/false, 13501 /*Copying=*/true); 13502 if (Copy.isInvalid()) { 13503 CopyAssignOperator->setInvalidDecl(); 13504 return; 13505 } 13506 13507 // Success! Record the copy. 13508 Statements.push_back(Copy.getAs<Stmt>()); 13509 } 13510 13511 if (!Invalid) { 13512 // Add a "return *this;" 13513 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 13514 13515 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 13516 if (Return.isInvalid()) 13517 Invalid = true; 13518 else 13519 Statements.push_back(Return.getAs<Stmt>()); 13520 } 13521 13522 if (Invalid) { 13523 CopyAssignOperator->setInvalidDecl(); 13524 return; 13525 } 13526 13527 StmtResult Body; 13528 { 13529 CompoundScopeRAII CompoundScope(*this); 13530 Body = ActOnCompoundStmt(Loc, Loc, Statements, 13531 /*isStmtExpr=*/false); 13532 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 13533 } 13534 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 13535 CopyAssignOperator->markUsed(Context); 13536 13537 if (ASTMutationListener *L = getASTMutationListener()) { 13538 L->CompletedImplicitDefinition(CopyAssignOperator); 13539 } 13540 } 13541 13542 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 13543 assert(ClassDecl->needsImplicitMoveAssignment()); 13544 13545 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 13546 if (DSM.isAlreadyBeingDeclared()) 13547 return nullptr; 13548 13549 // Note: The following rules are largely analoguous to the move 13550 // constructor rules. 13551 13552 QualType ArgType = Context.getTypeDeclType(ClassDecl); 13553 LangAS AS = getDefaultCXXMethodAddrSpace(); 13554 if (AS != LangAS::Default) 13555 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 13556 QualType RetType = Context.getLValueReferenceType(ArgType); 13557 ArgType = Context.getRValueReferenceType(ArgType); 13558 13559 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 13560 CXXMoveAssignment, 13561 false); 13562 13563 // An implicitly-declared move assignment operator is an inline public 13564 // member of its class. 13565 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 13566 SourceLocation ClassLoc = ClassDecl->getLocation(); 13567 DeclarationNameInfo NameInfo(Name, ClassLoc); 13568 CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create( 13569 Context, ClassDecl, ClassLoc, NameInfo, QualType(), 13570 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 13571 /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified, 13572 SourceLocation()); 13573 MoveAssignment->setAccess(AS_public); 13574 MoveAssignment->setDefaulted(); 13575 MoveAssignment->setImplicit(); 13576 13577 if (getLangOpts().CUDA) { 13578 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 13579 MoveAssignment, 13580 /* ConstRHS */ false, 13581 /* Diagnose */ false); 13582 } 13583 13584 // Build an exception specification pointing back at this member. 13585 FunctionProtoType::ExtProtoInfo EPI = 13586 getImplicitMethodEPI(*this, MoveAssignment); 13587 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 13588 13589 // Add the parameter to the operator. 13590 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 13591 ClassLoc, ClassLoc, 13592 /*Id=*/nullptr, ArgType, 13593 /*TInfo=*/nullptr, SC_None, 13594 nullptr); 13595 MoveAssignment->setParams(FromParam); 13596 13597 MoveAssignment->setTrivial( 13598 ClassDecl->needsOverloadResolutionForMoveAssignment() 13599 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 13600 : ClassDecl->hasTrivialMoveAssignment()); 13601 13602 // Note that we have added this copy-assignment operator. 13603 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared; 13604 13605 Scope *S = getScopeForContext(ClassDecl); 13606 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment); 13607 13608 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 13609 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 13610 SetDeclDeleted(MoveAssignment, ClassLoc); 13611 } 13612 13613 if (S) 13614 PushOnScopeChains(MoveAssignment, S, false); 13615 ClassDecl->addDecl(MoveAssignment); 13616 13617 return MoveAssignment; 13618 } 13619 13620 /// Check if we're implicitly defining a move assignment operator for a class 13621 /// with virtual bases. Such a move assignment might move-assign the virtual 13622 /// base multiple times. 13623 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 13624 SourceLocation CurrentLocation) { 13625 assert(!Class->isDependentContext() && "should not define dependent move"); 13626 13627 // Only a virtual base could get implicitly move-assigned multiple times. 13628 // Only a non-trivial move assignment can observe this. We only want to 13629 // diagnose if we implicitly define an assignment operator that assigns 13630 // two base classes, both of which move-assign the same virtual base. 13631 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 13632 Class->getNumBases() < 2) 13633 return; 13634 13635 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 13636 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 13637 VBaseMap VBases; 13638 13639 for (auto &BI : Class->bases()) { 13640 Worklist.push_back(&BI); 13641 while (!Worklist.empty()) { 13642 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 13643 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 13644 13645 // If the base has no non-trivial move assignment operators, 13646 // we don't care about moves from it. 13647 if (!Base->hasNonTrivialMoveAssignment()) 13648 continue; 13649 13650 // If there's nothing virtual here, skip it. 13651 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 13652 continue; 13653 13654 // If we're not actually going to call a move assignment for this base, 13655 // or the selected move assignment is trivial, skip it. 13656 Sema::SpecialMemberOverloadResult SMOR = 13657 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 13658 /*ConstArg*/false, /*VolatileArg*/false, 13659 /*RValueThis*/true, /*ConstThis*/false, 13660 /*VolatileThis*/false); 13661 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() || 13662 !SMOR.getMethod()->isMoveAssignmentOperator()) 13663 continue; 13664 13665 if (BaseSpec->isVirtual()) { 13666 // We're going to move-assign this virtual base, and its move 13667 // assignment operator is not trivial. If this can happen for 13668 // multiple distinct direct bases of Class, diagnose it. (If it 13669 // only happens in one base, we'll diagnose it when synthesizing 13670 // that base class's move assignment operator.) 13671 CXXBaseSpecifier *&Existing = 13672 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 13673 .first->second; 13674 if (Existing && Existing != &BI) { 13675 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 13676 << Class << Base; 13677 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here) 13678 << (Base->getCanonicalDecl() == 13679 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 13680 << Base << Existing->getType() << Existing->getSourceRange(); 13681 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here) 13682 << (Base->getCanonicalDecl() == 13683 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 13684 << Base << BI.getType() << BaseSpec->getSourceRange(); 13685 13686 // Only diagnose each vbase once. 13687 Existing = nullptr; 13688 } 13689 } else { 13690 // Only walk over bases that have defaulted move assignment operators. 13691 // We assume that any user-provided move assignment operator handles 13692 // the multiple-moves-of-vbase case itself somehow. 13693 if (!SMOR.getMethod()->isDefaulted()) 13694 continue; 13695 13696 // We're going to move the base classes of Base. Add them to the list. 13697 for (auto &BI : Base->bases()) 13698 Worklist.push_back(&BI); 13699 } 13700 } 13701 } 13702 } 13703 13704 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 13705 CXXMethodDecl *MoveAssignOperator) { 13706 assert((MoveAssignOperator->isDefaulted() && 13707 MoveAssignOperator->isOverloadedOperator() && 13708 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 13709 !MoveAssignOperator->doesThisDeclarationHaveABody() && 13710 !MoveAssignOperator->isDeleted()) && 13711 "DefineImplicitMoveAssignment called for wrong function"); 13712 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl()) 13713 return; 13714 13715 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 13716 if (ClassDecl->isInvalidDecl()) { 13717 MoveAssignOperator->setInvalidDecl(); 13718 return; 13719 } 13720 13721 // C++0x [class.copy]p28: 13722 // The implicitly-defined or move assignment operator for a non-union class 13723 // X performs memberwise move assignment of its subobjects. The direct base 13724 // classes of X are assigned first, in the order of their declaration in the 13725 // base-specifier-list, and then the immediate non-static data members of X 13726 // are assigned, in the order in which they were declared in the class 13727 // definition. 13728 13729 // Issue a warning if our implicit move assignment operator will move 13730 // from a virtual base more than once. 13731 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 13732 13733 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 13734 13735 // The exception specification is needed because we are defining the 13736 // function. 13737 ResolveExceptionSpec(CurrentLocation, 13738 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 13739 13740 // Add a context note for diagnostics produced after this point. 13741 Scope.addContextNote(CurrentLocation); 13742 13743 // The statements that form the synthesized function body. 13744 SmallVector<Stmt*, 8> Statements; 13745 13746 // The parameter for the "other" object, which we are move from. 13747 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 13748 QualType OtherRefType = Other->getType()-> 13749 getAs<RValueReferenceType>()->getPointeeType(); 13750 13751 // Our location for everything implicitly-generated. 13752 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid() 13753 ? MoveAssignOperator->getEndLoc() 13754 : MoveAssignOperator->getLocation(); 13755 13756 // Builds a reference to the "other" object. 13757 RefBuilder OtherRef(Other, OtherRefType); 13758 // Cast to rvalue. 13759 MoveCastBuilder MoveOther(OtherRef); 13760 13761 // Builds the "this" pointer. 13762 ThisBuilder This; 13763 13764 // Assign base classes. 13765 bool Invalid = false; 13766 for (auto &Base : ClassDecl->bases()) { 13767 // C++11 [class.copy]p28: 13768 // It is unspecified whether subobjects representing virtual base classes 13769 // are assigned more than once by the implicitly-defined copy assignment 13770 // operator. 13771 // FIXME: Do not assign to a vbase that will be assigned by some other base 13772 // class. For a move-assignment, this can result in the vbase being moved 13773 // multiple times. 13774 13775 // Form the assignment: 13776 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 13777 QualType BaseType = Base.getType().getUnqualifiedType(); 13778 if (!BaseType->isRecordType()) { 13779 Invalid = true; 13780 continue; 13781 } 13782 13783 CXXCastPath BasePath; 13784 BasePath.push_back(&Base); 13785 13786 // Construct the "from" expression, which is an implicit cast to the 13787 // appropriately-qualified base type. 13788 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 13789 13790 // Dereference "this". 13791 DerefBuilder DerefThis(This); 13792 13793 // Implicitly cast "this" to the appropriately-qualified base type. 13794 CastBuilder To(DerefThis, 13795 Context.getQualifiedType( 13796 BaseType, MoveAssignOperator->getMethodQualifiers()), 13797 VK_LValue, BasePath); 13798 13799 // Build the move. 13800 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 13801 To, From, 13802 /*CopyingBaseSubobject=*/true, 13803 /*Copying=*/false); 13804 if (Move.isInvalid()) { 13805 MoveAssignOperator->setInvalidDecl(); 13806 return; 13807 } 13808 13809 // Success! Record the move. 13810 Statements.push_back(Move.getAs<Expr>()); 13811 } 13812 13813 // Assign non-static members. 13814 for (auto *Field : ClassDecl->fields()) { 13815 // FIXME: We should form some kind of AST representation for the implied 13816 // memcpy in a union copy operation. 13817 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 13818 continue; 13819 13820 if (Field->isInvalidDecl()) { 13821 Invalid = true; 13822 continue; 13823 } 13824 13825 // Check for members of reference type; we can't move those. 13826 if (Field->getType()->isReferenceType()) { 13827 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 13828 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 13829 Diag(Field->getLocation(), diag::note_declared_at); 13830 Invalid = true; 13831 continue; 13832 } 13833 13834 // Check for members of const-qualified, non-class type. 13835 QualType BaseType = Context.getBaseElementType(Field->getType()); 13836 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 13837 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 13838 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 13839 Diag(Field->getLocation(), diag::note_declared_at); 13840 Invalid = true; 13841 continue; 13842 } 13843 13844 // Suppress assigning zero-width bitfields. 13845 if (Field->isZeroLengthBitField(Context)) 13846 continue; 13847 13848 QualType FieldType = Field->getType().getNonReferenceType(); 13849 if (FieldType->isIncompleteArrayType()) { 13850 assert(ClassDecl->hasFlexibleArrayMember() && 13851 "Incomplete array type is not valid"); 13852 continue; 13853 } 13854 13855 // Build references to the field in the object we're copying from and to. 13856 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 13857 LookupMemberName); 13858 MemberLookup.addDecl(Field); 13859 MemberLookup.resolveKind(); 13860 MemberBuilder From(MoveOther, OtherRefType, 13861 /*IsArrow=*/false, MemberLookup); 13862 MemberBuilder To(This, getCurrentThisType(), 13863 /*IsArrow=*/true, MemberLookup); 13864 13865 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 13866 "Member reference with rvalue base must be rvalue except for reference " 13867 "members, which aren't allowed for move assignment."); 13868 13869 // Build the move of this field. 13870 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 13871 To, From, 13872 /*CopyingBaseSubobject=*/false, 13873 /*Copying=*/false); 13874 if (Move.isInvalid()) { 13875 MoveAssignOperator->setInvalidDecl(); 13876 return; 13877 } 13878 13879 // Success! Record the copy. 13880 Statements.push_back(Move.getAs<Stmt>()); 13881 } 13882 13883 if (!Invalid) { 13884 // Add a "return *this;" 13885 ExprResult ThisObj = 13886 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 13887 13888 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 13889 if (Return.isInvalid()) 13890 Invalid = true; 13891 else 13892 Statements.push_back(Return.getAs<Stmt>()); 13893 } 13894 13895 if (Invalid) { 13896 MoveAssignOperator->setInvalidDecl(); 13897 return; 13898 } 13899 13900 StmtResult Body; 13901 { 13902 CompoundScopeRAII CompoundScope(*this); 13903 Body = ActOnCompoundStmt(Loc, Loc, Statements, 13904 /*isStmtExpr=*/false); 13905 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 13906 } 13907 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 13908 MoveAssignOperator->markUsed(Context); 13909 13910 if (ASTMutationListener *L = getASTMutationListener()) { 13911 L->CompletedImplicitDefinition(MoveAssignOperator); 13912 } 13913 } 13914 13915 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 13916 CXXRecordDecl *ClassDecl) { 13917 // C++ [class.copy]p4: 13918 // If the class definition does not explicitly declare a copy 13919 // constructor, one is declared implicitly. 13920 assert(ClassDecl->needsImplicitCopyConstructor()); 13921 13922 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 13923 if (DSM.isAlreadyBeingDeclared()) 13924 return nullptr; 13925 13926 QualType ClassType = Context.getTypeDeclType(ClassDecl); 13927 QualType ArgType = ClassType; 13928 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 13929 if (Const) 13930 ArgType = ArgType.withConst(); 13931 13932 LangAS AS = getDefaultCXXMethodAddrSpace(); 13933 if (AS != LangAS::Default) 13934 ArgType = Context.getAddrSpaceQualType(ArgType, AS); 13935 13936 ArgType = Context.getLValueReferenceType(ArgType); 13937 13938 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 13939 CXXCopyConstructor, 13940 Const); 13941 13942 DeclarationName Name 13943 = Context.DeclarationNames.getCXXConstructorName( 13944 Context.getCanonicalType(ClassType)); 13945 SourceLocation ClassLoc = ClassDecl->getLocation(); 13946 DeclarationNameInfo NameInfo(Name, ClassLoc); 13947 13948 // An implicitly-declared copy constructor is an inline public 13949 // member of its class. 13950 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 13951 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 13952 ExplicitSpecifier(), 13953 /*isInline=*/true, 13954 /*isImplicitlyDeclared=*/true, 13955 Constexpr ? CSK_constexpr : CSK_unspecified); 13956 CopyConstructor->setAccess(AS_public); 13957 CopyConstructor->setDefaulted(); 13958 13959 if (getLangOpts().CUDA) { 13960 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 13961 CopyConstructor, 13962 /* ConstRHS */ Const, 13963 /* Diagnose */ false); 13964 } 13965 13966 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType); 13967 13968 // Add the parameter to the constructor. 13969 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 13970 ClassLoc, ClassLoc, 13971 /*IdentifierInfo=*/nullptr, 13972 ArgType, /*TInfo=*/nullptr, 13973 SC_None, nullptr); 13974 CopyConstructor->setParams(FromParam); 13975 13976 CopyConstructor->setTrivial( 13977 ClassDecl->needsOverloadResolutionForCopyConstructor() 13978 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 13979 : ClassDecl->hasTrivialCopyConstructor()); 13980 13981 CopyConstructor->setTrivialForCall( 13982 ClassDecl->hasAttr<TrivialABIAttr>() || 13983 (ClassDecl->needsOverloadResolutionForCopyConstructor() 13984 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor, 13985 TAH_ConsiderTrivialABI) 13986 : ClassDecl->hasTrivialCopyConstructorForCall())); 13987 13988 // Note that we have declared this constructor. 13989 ++getASTContext().NumImplicitCopyConstructorsDeclared; 13990 13991 Scope *S = getScopeForContext(ClassDecl); 13992 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor); 13993 13994 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) { 13995 ClassDecl->setImplicitCopyConstructorIsDeleted(); 13996 SetDeclDeleted(CopyConstructor, ClassLoc); 13997 } 13998 13999 if (S) 14000 PushOnScopeChains(CopyConstructor, S, false); 14001 ClassDecl->addDecl(CopyConstructor); 14002 14003 return CopyConstructor; 14004 } 14005 14006 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 14007 CXXConstructorDecl *CopyConstructor) { 14008 assert((CopyConstructor->isDefaulted() && 14009 CopyConstructor->isCopyConstructor() && 14010 !CopyConstructor->doesThisDeclarationHaveABody() && 14011 !CopyConstructor->isDeleted()) && 14012 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 14013 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl()) 14014 return; 14015 14016 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 14017 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 14018 14019 SynthesizedFunctionScope Scope(*this, CopyConstructor); 14020 14021 // The exception specification is needed because we are defining the 14022 // function. 14023 ResolveExceptionSpec(CurrentLocation, 14024 CopyConstructor->getType()->castAs<FunctionProtoType>()); 14025 MarkVTableUsed(CurrentLocation, ClassDecl); 14026 14027 // Add a context note for diagnostics produced after this point. 14028 Scope.addContextNote(CurrentLocation); 14029 14030 // C++11 [class.copy]p7: 14031 // The [definition of an implicitly declared copy constructor] is 14032 // deprecated if the class has a user-declared copy assignment operator 14033 // or a user-declared destructor. 14034 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 14035 diagnoseDeprecatedCopyOperation(*this, CopyConstructor); 14036 14037 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) { 14038 CopyConstructor->setInvalidDecl(); 14039 } else { 14040 SourceLocation Loc = CopyConstructor->getEndLoc().isValid() 14041 ? CopyConstructor->getEndLoc() 14042 : CopyConstructor->getLocation(); 14043 Sema::CompoundScopeRAII CompoundScope(*this); 14044 CopyConstructor->setBody( 14045 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 14046 CopyConstructor->markUsed(Context); 14047 } 14048 14049 if (ASTMutationListener *L = getASTMutationListener()) { 14050 L->CompletedImplicitDefinition(CopyConstructor); 14051 } 14052 } 14053 14054 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 14055 CXXRecordDecl *ClassDecl) { 14056 assert(ClassDecl->needsImplicitMoveConstructor()); 14057 14058 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 14059 if (DSM.isAlreadyBeingDeclared()) 14060 return nullptr; 14061 14062 QualType ClassType = Context.getTypeDeclType(ClassDecl); 14063 14064 QualType ArgType = ClassType; 14065 LangAS AS = getDefaultCXXMethodAddrSpace(); 14066 if (AS != LangAS::Default) 14067 ArgType = Context.getAddrSpaceQualType(ClassType, AS); 14068 ArgType = Context.getRValueReferenceType(ArgType); 14069 14070 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 14071 CXXMoveConstructor, 14072 false); 14073 14074 DeclarationName Name 14075 = Context.DeclarationNames.getCXXConstructorName( 14076 Context.getCanonicalType(ClassType)); 14077 SourceLocation ClassLoc = ClassDecl->getLocation(); 14078 DeclarationNameInfo NameInfo(Name, ClassLoc); 14079 14080 // C++11 [class.copy]p11: 14081 // An implicitly-declared copy/move constructor is an inline public 14082 // member of its class. 14083 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 14084 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 14085 ExplicitSpecifier(), 14086 /*isInline=*/true, 14087 /*isImplicitlyDeclared=*/true, 14088 Constexpr ? CSK_constexpr : CSK_unspecified); 14089 MoveConstructor->setAccess(AS_public); 14090 MoveConstructor->setDefaulted(); 14091 14092 if (getLangOpts().CUDA) { 14093 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 14094 MoveConstructor, 14095 /* ConstRHS */ false, 14096 /* Diagnose */ false); 14097 } 14098 14099 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType); 14100 14101 // Add the parameter to the constructor. 14102 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 14103 ClassLoc, ClassLoc, 14104 /*IdentifierInfo=*/nullptr, 14105 ArgType, /*TInfo=*/nullptr, 14106 SC_None, nullptr); 14107 MoveConstructor->setParams(FromParam); 14108 14109 MoveConstructor->setTrivial( 14110 ClassDecl->needsOverloadResolutionForMoveConstructor() 14111 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 14112 : ClassDecl->hasTrivialMoveConstructor()); 14113 14114 MoveConstructor->setTrivialForCall( 14115 ClassDecl->hasAttr<TrivialABIAttr>() || 14116 (ClassDecl->needsOverloadResolutionForMoveConstructor() 14117 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor, 14118 TAH_ConsiderTrivialABI) 14119 : ClassDecl->hasTrivialMoveConstructorForCall())); 14120 14121 // Note that we have declared this constructor. 14122 ++getASTContext().NumImplicitMoveConstructorsDeclared; 14123 14124 Scope *S = getScopeForContext(ClassDecl); 14125 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor); 14126 14127 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 14128 ClassDecl->setImplicitMoveConstructorIsDeleted(); 14129 SetDeclDeleted(MoveConstructor, ClassLoc); 14130 } 14131 14132 if (S) 14133 PushOnScopeChains(MoveConstructor, S, false); 14134 ClassDecl->addDecl(MoveConstructor); 14135 14136 return MoveConstructor; 14137 } 14138 14139 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 14140 CXXConstructorDecl *MoveConstructor) { 14141 assert((MoveConstructor->isDefaulted() && 14142 MoveConstructor->isMoveConstructor() && 14143 !MoveConstructor->doesThisDeclarationHaveABody() && 14144 !MoveConstructor->isDeleted()) && 14145 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 14146 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl()) 14147 return; 14148 14149 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 14150 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 14151 14152 SynthesizedFunctionScope Scope(*this, MoveConstructor); 14153 14154 // The exception specification is needed because we are defining the 14155 // function. 14156 ResolveExceptionSpec(CurrentLocation, 14157 MoveConstructor->getType()->castAs<FunctionProtoType>()); 14158 MarkVTableUsed(CurrentLocation, ClassDecl); 14159 14160 // Add a context note for diagnostics produced after this point. 14161 Scope.addContextNote(CurrentLocation); 14162 14163 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) { 14164 MoveConstructor->setInvalidDecl(); 14165 } else { 14166 SourceLocation Loc = MoveConstructor->getEndLoc().isValid() 14167 ? MoveConstructor->getEndLoc() 14168 : MoveConstructor->getLocation(); 14169 Sema::CompoundScopeRAII CompoundScope(*this); 14170 MoveConstructor->setBody(ActOnCompoundStmt( 14171 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 14172 MoveConstructor->markUsed(Context); 14173 } 14174 14175 if (ASTMutationListener *L = getASTMutationListener()) { 14176 L->CompletedImplicitDefinition(MoveConstructor); 14177 } 14178 } 14179 14180 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 14181 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 14182 } 14183 14184 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 14185 SourceLocation CurrentLocation, 14186 CXXConversionDecl *Conv) { 14187 SynthesizedFunctionScope Scope(*this, Conv); 14188 assert(!Conv->getReturnType()->isUndeducedType()); 14189 14190 CXXRecordDecl *Lambda = Conv->getParent(); 14191 FunctionDecl *CallOp = Lambda->getLambdaCallOperator(); 14192 FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(); 14193 14194 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) { 14195 CallOp = InstantiateFunctionDeclaration( 14196 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 14197 if (!CallOp) 14198 return; 14199 14200 Invoker = InstantiateFunctionDeclaration( 14201 Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 14202 if (!Invoker) 14203 return; 14204 } 14205 14206 if (CallOp->isInvalidDecl()) 14207 return; 14208 14209 // Mark the call operator referenced (and add to pending instantiations 14210 // if necessary). 14211 // For both the conversion and static-invoker template specializations 14212 // we construct their body's in this function, so no need to add them 14213 // to the PendingInstantiations. 14214 MarkFunctionReferenced(CurrentLocation, CallOp); 14215 14216 // Fill in the __invoke function with a dummy implementation. IR generation 14217 // will fill in the actual details. Update its type in case it contained 14218 // an 'auto'. 14219 Invoker->markUsed(Context); 14220 Invoker->setReferenced(); 14221 Invoker->setType(Conv->getReturnType()->getPointeeType()); 14222 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 14223 14224 // Construct the body of the conversion function { return __invoke; }. 14225 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 14226 VK_LValue, Conv->getLocation()); 14227 assert(FunctionRef && "Can't refer to __invoke function?"); 14228 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 14229 Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(), 14230 Conv->getLocation())); 14231 Conv->markUsed(Context); 14232 Conv->setReferenced(); 14233 14234 if (ASTMutationListener *L = getASTMutationListener()) { 14235 L->CompletedImplicitDefinition(Conv); 14236 L->CompletedImplicitDefinition(Invoker); 14237 } 14238 } 14239 14240 14241 14242 void Sema::DefineImplicitLambdaToBlockPointerConversion( 14243 SourceLocation CurrentLocation, 14244 CXXConversionDecl *Conv) 14245 { 14246 assert(!Conv->getParent()->isGenericLambda()); 14247 14248 SynthesizedFunctionScope Scope(*this, Conv); 14249 14250 // Copy-initialize the lambda object as needed to capture it. 14251 Expr *This = ActOnCXXThis(CurrentLocation).get(); 14252 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 14253 14254 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 14255 Conv->getLocation(), 14256 Conv, DerefThis); 14257 14258 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 14259 // behavior. Note that only the general conversion function does this 14260 // (since it's unusable otherwise); in the case where we inline the 14261 // block literal, it has block literal lifetime semantics. 14262 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 14263 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 14264 CK_CopyAndAutoreleaseBlockObject, 14265 BuildBlock.get(), nullptr, VK_RValue); 14266 14267 if (BuildBlock.isInvalid()) { 14268 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 14269 Conv->setInvalidDecl(); 14270 return; 14271 } 14272 14273 // Create the return statement that returns the block from the conversion 14274 // function. 14275 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 14276 if (Return.isInvalid()) { 14277 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 14278 Conv->setInvalidDecl(); 14279 return; 14280 } 14281 14282 // Set the body of the conversion function. 14283 Stmt *ReturnS = Return.get(); 14284 Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(), 14285 Conv->getLocation())); 14286 Conv->markUsed(Context); 14287 14288 // We're done; notify the mutation listener, if any. 14289 if (ASTMutationListener *L = getASTMutationListener()) { 14290 L->CompletedImplicitDefinition(Conv); 14291 } 14292 } 14293 14294 /// Determine whether the given list arguments contains exactly one 14295 /// "real" (non-default) argument. 14296 static bool hasOneRealArgument(MultiExprArg Args) { 14297 switch (Args.size()) { 14298 case 0: 14299 return false; 14300 14301 default: 14302 if (!Args[1]->isDefaultArgument()) 14303 return false; 14304 14305 LLVM_FALLTHROUGH; 14306 case 1: 14307 return !Args[0]->isDefaultArgument(); 14308 } 14309 14310 return false; 14311 } 14312 14313 ExprResult 14314 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 14315 NamedDecl *FoundDecl, 14316 CXXConstructorDecl *Constructor, 14317 MultiExprArg ExprArgs, 14318 bool HadMultipleCandidates, 14319 bool IsListInitialization, 14320 bool IsStdInitListInitialization, 14321 bool RequiresZeroInit, 14322 unsigned ConstructKind, 14323 SourceRange ParenRange) { 14324 bool Elidable = false; 14325 14326 // C++0x [class.copy]p34: 14327 // When certain criteria are met, an implementation is allowed to 14328 // omit the copy/move construction of a class object, even if the 14329 // copy/move constructor and/or destructor for the object have 14330 // side effects. [...] 14331 // - when a temporary class object that has not been bound to a 14332 // reference (12.2) would be copied/moved to a class object 14333 // with the same cv-unqualified type, the copy/move operation 14334 // can be omitted by constructing the temporary object 14335 // directly into the target of the omitted copy/move 14336 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor && 14337 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 14338 Expr *SubExpr = ExprArgs[0]; 14339 Elidable = SubExpr->isTemporaryObject( 14340 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 14341 } 14342 14343 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, 14344 FoundDecl, Constructor, 14345 Elidable, ExprArgs, HadMultipleCandidates, 14346 IsListInitialization, 14347 IsStdInitListInitialization, RequiresZeroInit, 14348 ConstructKind, ParenRange); 14349 } 14350 14351 ExprResult 14352 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 14353 NamedDecl *FoundDecl, 14354 CXXConstructorDecl *Constructor, 14355 bool Elidable, 14356 MultiExprArg ExprArgs, 14357 bool HadMultipleCandidates, 14358 bool IsListInitialization, 14359 bool IsStdInitListInitialization, 14360 bool RequiresZeroInit, 14361 unsigned ConstructKind, 14362 SourceRange ParenRange) { 14363 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) { 14364 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow); 14365 if (DiagnoseUseOfDecl(Constructor, ConstructLoc)) 14366 return ExprError(); 14367 } 14368 14369 return BuildCXXConstructExpr( 14370 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs, 14371 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 14372 RequiresZeroInit, ConstructKind, ParenRange); 14373 } 14374 14375 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 14376 /// including handling of its default argument expressions. 14377 ExprResult 14378 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 14379 CXXConstructorDecl *Constructor, 14380 bool Elidable, 14381 MultiExprArg ExprArgs, 14382 bool HadMultipleCandidates, 14383 bool IsListInitialization, 14384 bool IsStdInitListInitialization, 14385 bool RequiresZeroInit, 14386 unsigned ConstructKind, 14387 SourceRange ParenRange) { 14388 assert(declaresSameEntity( 14389 Constructor->getParent(), 14390 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && 14391 "given constructor for wrong type"); 14392 MarkFunctionReferenced(ConstructLoc, Constructor); 14393 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor)) 14394 return ExprError(); 14395 14396 return CXXConstructExpr::Create( 14397 Context, DeclInitType, ConstructLoc, Constructor, Elidable, 14398 ExprArgs, HadMultipleCandidates, IsListInitialization, 14399 IsStdInitListInitialization, RequiresZeroInit, 14400 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 14401 ParenRange); 14402 } 14403 14404 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 14405 assert(Field->hasInClassInitializer()); 14406 14407 // If we already have the in-class initializer nothing needs to be done. 14408 if (Field->getInClassInitializer()) 14409 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext); 14410 14411 // If we might have already tried and failed to instantiate, don't try again. 14412 if (Field->isInvalidDecl()) 14413 return ExprError(); 14414 14415 // Maybe we haven't instantiated the in-class initializer. Go check the 14416 // pattern FieldDecl to see if it has one. 14417 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 14418 14419 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 14420 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 14421 DeclContext::lookup_result Lookup = 14422 ClassPattern->lookup(Field->getDeclName()); 14423 14424 // Lookup can return at most two results: the pattern for the field, or the 14425 // injected class name of the parent record. No other member can have the 14426 // same name as the field. 14427 // In modules mode, lookup can return multiple results (coming from 14428 // different modules). 14429 assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) && 14430 "more than two lookup results for field name"); 14431 FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]); 14432 if (!Pattern) { 14433 assert(isa<CXXRecordDecl>(Lookup[0]) && 14434 "cannot have other non-field member with same name"); 14435 for (auto L : Lookup) 14436 if (isa<FieldDecl>(L)) { 14437 Pattern = cast<FieldDecl>(L); 14438 break; 14439 } 14440 assert(Pattern && "We must have set the Pattern!"); 14441 } 14442 14443 if (!Pattern->hasInClassInitializer() || 14444 InstantiateInClassInitializer(Loc, Field, Pattern, 14445 getTemplateInstantiationArgs(Field))) { 14446 // Don't diagnose this again. 14447 Field->setInvalidDecl(); 14448 return ExprError(); 14449 } 14450 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext); 14451 } 14452 14453 // DR1351: 14454 // If the brace-or-equal-initializer of a non-static data member 14455 // invokes a defaulted default constructor of its class or of an 14456 // enclosing class in a potentially evaluated subexpression, the 14457 // program is ill-formed. 14458 // 14459 // This resolution is unworkable: the exception specification of the 14460 // default constructor can be needed in an unevaluated context, in 14461 // particular, in the operand of a noexcept-expression, and we can be 14462 // unable to compute an exception specification for an enclosed class. 14463 // 14464 // Any attempt to resolve the exception specification of a defaulted default 14465 // constructor before the initializer is lexically complete will ultimately 14466 // come here at which point we can diagnose it. 14467 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 14468 Diag(Loc, diag::err_in_class_initializer_not_yet_parsed) 14469 << OutermostClass << Field; 14470 Diag(Field->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed); 14471 // Recover by marking the field invalid, unless we're in a SFINAE context. 14472 if (!isSFINAEContext()) 14473 Field->setInvalidDecl(); 14474 return ExprError(); 14475 } 14476 14477 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 14478 if (VD->isInvalidDecl()) return; 14479 14480 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 14481 if (ClassDecl->isInvalidDecl()) return; 14482 if (ClassDecl->hasIrrelevantDestructor()) return; 14483 if (ClassDecl->isDependentContext()) return; 14484 14485 if (VD->isNoDestroy(getASTContext())) 14486 return; 14487 14488 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 14489 14490 // If this is an array, we'll require the destructor during initialization, so 14491 // we can skip over this. We still want to emit exit-time destructor warnings 14492 // though. 14493 if (!VD->getType()->isArrayType()) { 14494 MarkFunctionReferenced(VD->getLocation(), Destructor); 14495 CheckDestructorAccess(VD->getLocation(), Destructor, 14496 PDiag(diag::err_access_dtor_var) 14497 << VD->getDeclName() << VD->getType()); 14498 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 14499 } 14500 14501 if (Destructor->isTrivial()) return; 14502 14503 // If the destructor is constexpr, check whether the variable has constant 14504 // destruction now. 14505 if (Destructor->isConstexpr() && VD->getInit() && 14506 !VD->getInit()->isValueDependent() && VD->evaluateValue()) { 14507 SmallVector<PartialDiagnosticAt, 8> Notes; 14508 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr()) { 14509 Diag(VD->getLocation(), 14510 diag::err_constexpr_var_requires_const_destruction) << VD; 14511 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 14512 Diag(Notes[I].first, Notes[I].second); 14513 } 14514 } 14515 14516 if (!VD->hasGlobalStorage()) return; 14517 14518 // Emit warning for non-trivial dtor in global scope (a real global, 14519 // class-static, function-static). 14520 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 14521 14522 // TODO: this should be re-enabled for static locals by !CXAAtExit 14523 if (!VD->isStaticLocal()) 14524 Diag(VD->getLocation(), diag::warn_global_destructor); 14525 } 14526 14527 /// Given a constructor and the set of arguments provided for the 14528 /// constructor, convert the arguments and add any required default arguments 14529 /// to form a proper call to this constructor. 14530 /// 14531 /// \returns true if an error occurred, false otherwise. 14532 bool 14533 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 14534 MultiExprArg ArgsPtr, 14535 SourceLocation Loc, 14536 SmallVectorImpl<Expr*> &ConvertedArgs, 14537 bool AllowExplicit, 14538 bool IsListInitialization) { 14539 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 14540 unsigned NumArgs = ArgsPtr.size(); 14541 Expr **Args = ArgsPtr.data(); 14542 14543 const FunctionProtoType *Proto 14544 = Constructor->getType()->getAs<FunctionProtoType>(); 14545 assert(Proto && "Constructor without a prototype?"); 14546 unsigned NumParams = Proto->getNumParams(); 14547 14548 // If too few arguments are available, we'll fill in the rest with defaults. 14549 if (NumArgs < NumParams) 14550 ConvertedArgs.reserve(NumParams); 14551 else 14552 ConvertedArgs.reserve(NumArgs); 14553 14554 VariadicCallType CallType = 14555 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 14556 SmallVector<Expr *, 8> AllArgs; 14557 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 14558 Proto, 0, 14559 llvm::makeArrayRef(Args, NumArgs), 14560 AllArgs, 14561 CallType, AllowExplicit, 14562 IsListInitialization); 14563 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 14564 14565 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 14566 14567 CheckConstructorCall(Constructor, 14568 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 14569 Proto, Loc); 14570 14571 return Invalid; 14572 } 14573 14574 static inline bool 14575 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 14576 const FunctionDecl *FnDecl) { 14577 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 14578 if (isa<NamespaceDecl>(DC)) { 14579 return SemaRef.Diag(FnDecl->getLocation(), 14580 diag::err_operator_new_delete_declared_in_namespace) 14581 << FnDecl->getDeclName(); 14582 } 14583 14584 if (isa<TranslationUnitDecl>(DC) && 14585 FnDecl->getStorageClass() == SC_Static) { 14586 return SemaRef.Diag(FnDecl->getLocation(), 14587 diag::err_operator_new_delete_declared_static) 14588 << FnDecl->getDeclName(); 14589 } 14590 14591 return false; 14592 } 14593 14594 static QualType 14595 RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) { 14596 QualType QTy = PtrTy->getPointeeType(); 14597 QTy = SemaRef.Context.removeAddrSpaceQualType(QTy); 14598 return SemaRef.Context.getPointerType(QTy); 14599 } 14600 14601 static inline bool 14602 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 14603 CanQualType ExpectedResultType, 14604 CanQualType ExpectedFirstParamType, 14605 unsigned DependentParamTypeDiag, 14606 unsigned InvalidParamTypeDiag) { 14607 QualType ResultType = 14608 FnDecl->getType()->getAs<FunctionType>()->getReturnType(); 14609 14610 // Check that the result type is not dependent. 14611 if (ResultType->isDependentType()) 14612 return SemaRef.Diag(FnDecl->getLocation(), 14613 diag::err_operator_new_delete_dependent_result_type) 14614 << FnDecl->getDeclName() << ExpectedResultType; 14615 14616 // The operator is valid on any address space for OpenCL. 14617 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 14618 if (auto *PtrTy = ResultType->getAs<PointerType>()) { 14619 ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 14620 } 14621 } 14622 14623 // Check that the result type is what we expect. 14624 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 14625 return SemaRef.Diag(FnDecl->getLocation(), 14626 diag::err_operator_new_delete_invalid_result_type) 14627 << FnDecl->getDeclName() << ExpectedResultType; 14628 14629 // A function template must have at least 2 parameters. 14630 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 14631 return SemaRef.Diag(FnDecl->getLocation(), 14632 diag::err_operator_new_delete_template_too_few_parameters) 14633 << FnDecl->getDeclName(); 14634 14635 // The function decl must have at least 1 parameter. 14636 if (FnDecl->getNumParams() == 0) 14637 return SemaRef.Diag(FnDecl->getLocation(), 14638 diag::err_operator_new_delete_too_few_parameters) 14639 << FnDecl->getDeclName(); 14640 14641 // Check the first parameter type is not dependent. 14642 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 14643 if (FirstParamType->isDependentType()) 14644 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 14645 << FnDecl->getDeclName() << ExpectedFirstParamType; 14646 14647 // Check that the first parameter type is what we expect. 14648 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 14649 // The operator is valid on any address space for OpenCL. 14650 if (auto *PtrTy = 14651 FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) { 14652 FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 14653 } 14654 } 14655 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 14656 ExpectedFirstParamType) 14657 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 14658 << FnDecl->getDeclName() << ExpectedFirstParamType; 14659 14660 return false; 14661 } 14662 14663 static bool 14664 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 14665 // C++ [basic.stc.dynamic.allocation]p1: 14666 // A program is ill-formed if an allocation function is declared in a 14667 // namespace scope other than global scope or declared static in global 14668 // scope. 14669 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 14670 return true; 14671 14672 CanQualType SizeTy = 14673 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 14674 14675 // C++ [basic.stc.dynamic.allocation]p1: 14676 // The return type shall be void*. The first parameter shall have type 14677 // std::size_t. 14678 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 14679 SizeTy, 14680 diag::err_operator_new_dependent_param_type, 14681 diag::err_operator_new_param_type)) 14682 return true; 14683 14684 // C++ [basic.stc.dynamic.allocation]p1: 14685 // The first parameter shall not have an associated default argument. 14686 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 14687 return SemaRef.Diag(FnDecl->getLocation(), 14688 diag::err_operator_new_default_arg) 14689 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 14690 14691 return false; 14692 } 14693 14694 static bool 14695 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 14696 // C++ [basic.stc.dynamic.deallocation]p1: 14697 // A program is ill-formed if deallocation functions are declared in a 14698 // namespace scope other than global scope or declared static in global 14699 // scope. 14700 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 14701 return true; 14702 14703 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl); 14704 14705 // C++ P0722: 14706 // Within a class C, the first parameter of a destroying operator delete 14707 // shall be of type C *. The first parameter of any other deallocation 14708 // function shall be of type void *. 14709 CanQualType ExpectedFirstParamType = 14710 MD && MD->isDestroyingOperatorDelete() 14711 ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType( 14712 SemaRef.Context.getRecordType(MD->getParent()))) 14713 : SemaRef.Context.VoidPtrTy; 14714 14715 // C++ [basic.stc.dynamic.deallocation]p2: 14716 // Each deallocation function shall return void 14717 if (CheckOperatorNewDeleteTypes( 14718 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType, 14719 diag::err_operator_delete_dependent_param_type, 14720 diag::err_operator_delete_param_type)) 14721 return true; 14722 14723 // C++ P0722: 14724 // A destroying operator delete shall be a usual deallocation function. 14725 if (MD && !MD->getParent()->isDependentContext() && 14726 MD->isDestroyingOperatorDelete() && 14727 !SemaRef.isUsualDeallocationFunction(MD)) { 14728 SemaRef.Diag(MD->getLocation(), 14729 diag::err_destroying_operator_delete_not_usual); 14730 return true; 14731 } 14732 14733 return false; 14734 } 14735 14736 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 14737 /// of this overloaded operator is well-formed. If so, returns false; 14738 /// otherwise, emits appropriate diagnostics and returns true. 14739 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 14740 assert(FnDecl && FnDecl->isOverloadedOperator() && 14741 "Expected an overloaded operator declaration"); 14742 14743 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 14744 14745 // C++ [over.oper]p5: 14746 // The allocation and deallocation functions, operator new, 14747 // operator new[], operator delete and operator delete[], are 14748 // described completely in 3.7.3. The attributes and restrictions 14749 // found in the rest of this subclause do not apply to them unless 14750 // explicitly stated in 3.7.3. 14751 if (Op == OO_Delete || Op == OO_Array_Delete) 14752 return CheckOperatorDeleteDeclaration(*this, FnDecl); 14753 14754 if (Op == OO_New || Op == OO_Array_New) 14755 return CheckOperatorNewDeclaration(*this, FnDecl); 14756 14757 // C++ [over.oper]p6: 14758 // An operator function shall either be a non-static member 14759 // function or be a non-member function and have at least one 14760 // parameter whose type is a class, a reference to a class, an 14761 // enumeration, or a reference to an enumeration. 14762 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 14763 if (MethodDecl->isStatic()) 14764 return Diag(FnDecl->getLocation(), 14765 diag::err_operator_overload_static) << FnDecl->getDeclName(); 14766 } else { 14767 bool ClassOrEnumParam = false; 14768 for (auto Param : FnDecl->parameters()) { 14769 QualType ParamType = Param->getType().getNonReferenceType(); 14770 if (ParamType->isDependentType() || ParamType->isRecordType() || 14771 ParamType->isEnumeralType()) { 14772 ClassOrEnumParam = true; 14773 break; 14774 } 14775 } 14776 14777 if (!ClassOrEnumParam) 14778 return Diag(FnDecl->getLocation(), 14779 diag::err_operator_overload_needs_class_or_enum) 14780 << FnDecl->getDeclName(); 14781 } 14782 14783 // C++ [over.oper]p8: 14784 // An operator function cannot have default arguments (8.3.6), 14785 // except where explicitly stated below. 14786 // 14787 // Only the function-call operator allows default arguments 14788 // (C++ [over.call]p1). 14789 if (Op != OO_Call) { 14790 for (auto Param : FnDecl->parameters()) { 14791 if (Param->hasDefaultArg()) 14792 return Diag(Param->getLocation(), 14793 diag::err_operator_overload_default_arg) 14794 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 14795 } 14796 } 14797 14798 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 14799 { false, false, false } 14800 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 14801 , { Unary, Binary, MemberOnly } 14802 #include "clang/Basic/OperatorKinds.def" 14803 }; 14804 14805 bool CanBeUnaryOperator = OperatorUses[Op][0]; 14806 bool CanBeBinaryOperator = OperatorUses[Op][1]; 14807 bool MustBeMemberOperator = OperatorUses[Op][2]; 14808 14809 // C++ [over.oper]p8: 14810 // [...] Operator functions cannot have more or fewer parameters 14811 // than the number required for the corresponding operator, as 14812 // described in the rest of this subclause. 14813 unsigned NumParams = FnDecl->getNumParams() 14814 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 14815 if (Op != OO_Call && 14816 ((NumParams == 1 && !CanBeUnaryOperator) || 14817 (NumParams == 2 && !CanBeBinaryOperator) || 14818 (NumParams < 1) || (NumParams > 2))) { 14819 // We have the wrong number of parameters. 14820 unsigned ErrorKind; 14821 if (CanBeUnaryOperator && CanBeBinaryOperator) { 14822 ErrorKind = 2; // 2 -> unary or binary. 14823 } else if (CanBeUnaryOperator) { 14824 ErrorKind = 0; // 0 -> unary 14825 } else { 14826 assert(CanBeBinaryOperator && 14827 "All non-call overloaded operators are unary or binary!"); 14828 ErrorKind = 1; // 1 -> binary 14829 } 14830 14831 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 14832 << FnDecl->getDeclName() << NumParams << ErrorKind; 14833 } 14834 14835 // Overloaded operators other than operator() cannot be variadic. 14836 if (Op != OO_Call && 14837 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 14838 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 14839 << FnDecl->getDeclName(); 14840 } 14841 14842 // Some operators must be non-static member functions. 14843 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 14844 return Diag(FnDecl->getLocation(), 14845 diag::err_operator_overload_must_be_member) 14846 << FnDecl->getDeclName(); 14847 } 14848 14849 // C++ [over.inc]p1: 14850 // The user-defined function called operator++ implements the 14851 // prefix and postfix ++ operator. If this function is a member 14852 // function with no parameters, or a non-member function with one 14853 // parameter of class or enumeration type, it defines the prefix 14854 // increment operator ++ for objects of that type. If the function 14855 // is a member function with one parameter (which shall be of type 14856 // int) or a non-member function with two parameters (the second 14857 // of which shall be of type int), it defines the postfix 14858 // increment operator ++ for objects of that type. 14859 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 14860 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 14861 QualType ParamType = LastParam->getType(); 14862 14863 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 14864 !ParamType->isDependentType()) 14865 return Diag(LastParam->getLocation(), 14866 diag::err_operator_overload_post_incdec_must_be_int) 14867 << LastParam->getType() << (Op == OO_MinusMinus); 14868 } 14869 14870 return false; 14871 } 14872 14873 static bool 14874 checkLiteralOperatorTemplateParameterList(Sema &SemaRef, 14875 FunctionTemplateDecl *TpDecl) { 14876 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters(); 14877 14878 // Must have one or two template parameters. 14879 if (TemplateParams->size() == 1) { 14880 NonTypeTemplateParmDecl *PmDecl = 14881 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0)); 14882 14883 // The template parameter must be a char parameter pack. 14884 if (PmDecl && PmDecl->isTemplateParameterPack() && 14885 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy)) 14886 return false; 14887 14888 } else if (TemplateParams->size() == 2) { 14889 TemplateTypeParmDecl *PmType = 14890 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0)); 14891 NonTypeTemplateParmDecl *PmArgs = 14892 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1)); 14893 14894 // The second template parameter must be a parameter pack with the 14895 // first template parameter as its type. 14896 if (PmType && PmArgs && !PmType->isTemplateParameterPack() && 14897 PmArgs->isTemplateParameterPack()) { 14898 const TemplateTypeParmType *TArgs = 14899 PmArgs->getType()->getAs<TemplateTypeParmType>(); 14900 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 14901 TArgs->getIndex() == PmType->getIndex()) { 14902 if (!SemaRef.inTemplateInstantiation()) 14903 SemaRef.Diag(TpDecl->getLocation(), 14904 diag::ext_string_literal_operator_template); 14905 return false; 14906 } 14907 } 14908 } 14909 14910 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(), 14911 diag::err_literal_operator_template) 14912 << TpDecl->getTemplateParameters()->getSourceRange(); 14913 return true; 14914 } 14915 14916 /// CheckLiteralOperatorDeclaration - Check whether the declaration 14917 /// of this literal operator function is well-formed. If so, returns 14918 /// false; otherwise, emits appropriate diagnostics and returns true. 14919 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 14920 if (isa<CXXMethodDecl>(FnDecl)) { 14921 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 14922 << FnDecl->getDeclName(); 14923 return true; 14924 } 14925 14926 if (FnDecl->isExternC()) { 14927 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 14928 if (const LinkageSpecDecl *LSD = 14929 FnDecl->getDeclContext()->getExternCContext()) 14930 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here); 14931 return true; 14932 } 14933 14934 // This might be the definition of a literal operator template. 14935 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 14936 14937 // This might be a specialization of a literal operator template. 14938 if (!TpDecl) 14939 TpDecl = FnDecl->getPrimaryTemplate(); 14940 14941 // template <char...> type operator "" name() and 14942 // template <class T, T...> type operator "" name() are the only valid 14943 // template signatures, and the only valid signatures with no parameters. 14944 if (TpDecl) { 14945 if (FnDecl->param_size() != 0) { 14946 Diag(FnDecl->getLocation(), 14947 diag::err_literal_operator_template_with_params); 14948 return true; 14949 } 14950 14951 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl)) 14952 return true; 14953 14954 } else if (FnDecl->param_size() == 1) { 14955 const ParmVarDecl *Param = FnDecl->getParamDecl(0); 14956 14957 QualType ParamType = Param->getType().getUnqualifiedType(); 14958 14959 // Only unsigned long long int, long double, any character type, and const 14960 // char * are allowed as the only parameters. 14961 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) || 14962 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) || 14963 Context.hasSameType(ParamType, Context.CharTy) || 14964 Context.hasSameType(ParamType, Context.WideCharTy) || 14965 Context.hasSameType(ParamType, Context.Char8Ty) || 14966 Context.hasSameType(ParamType, Context.Char16Ty) || 14967 Context.hasSameType(ParamType, Context.Char32Ty)) { 14968 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) { 14969 QualType InnerType = Ptr->getPointeeType(); 14970 14971 // Pointer parameter must be a const char *. 14972 if (!(Context.hasSameType(InnerType.getUnqualifiedType(), 14973 Context.CharTy) && 14974 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) { 14975 Diag(Param->getSourceRange().getBegin(), 14976 diag::err_literal_operator_param) 14977 << ParamType << "'const char *'" << Param->getSourceRange(); 14978 return true; 14979 } 14980 14981 } else if (ParamType->isRealFloatingType()) { 14982 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 14983 << ParamType << Context.LongDoubleTy << Param->getSourceRange(); 14984 return true; 14985 14986 } else if (ParamType->isIntegerType()) { 14987 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 14988 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange(); 14989 return true; 14990 14991 } else { 14992 Diag(Param->getSourceRange().getBegin(), 14993 diag::err_literal_operator_invalid_param) 14994 << ParamType << Param->getSourceRange(); 14995 return true; 14996 } 14997 14998 } else if (FnDecl->param_size() == 2) { 14999 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 15000 15001 // First, verify that the first parameter is correct. 15002 15003 QualType FirstParamType = (*Param)->getType().getUnqualifiedType(); 15004 15005 // Two parameter function must have a pointer to const as a 15006 // first parameter; let's strip those qualifiers. 15007 const PointerType *PT = FirstParamType->getAs<PointerType>(); 15008 15009 if (!PT) { 15010 Diag((*Param)->getSourceRange().getBegin(), 15011 diag::err_literal_operator_param) 15012 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 15013 return true; 15014 } 15015 15016 QualType PointeeType = PT->getPointeeType(); 15017 // First parameter must be const 15018 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) { 15019 Diag((*Param)->getSourceRange().getBegin(), 15020 diag::err_literal_operator_param) 15021 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 15022 return true; 15023 } 15024 15025 QualType InnerType = PointeeType.getUnqualifiedType(); 15026 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and 15027 // const char32_t* are allowed as the first parameter to a two-parameter 15028 // function 15029 if (!(Context.hasSameType(InnerType, Context.CharTy) || 15030 Context.hasSameType(InnerType, Context.WideCharTy) || 15031 Context.hasSameType(InnerType, Context.Char8Ty) || 15032 Context.hasSameType(InnerType, Context.Char16Ty) || 15033 Context.hasSameType(InnerType, Context.Char32Ty))) { 15034 Diag((*Param)->getSourceRange().getBegin(), 15035 diag::err_literal_operator_param) 15036 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 15037 return true; 15038 } 15039 15040 // Move on to the second and final parameter. 15041 ++Param; 15042 15043 // The second parameter must be a std::size_t. 15044 QualType SecondParamType = (*Param)->getType().getUnqualifiedType(); 15045 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) { 15046 Diag((*Param)->getSourceRange().getBegin(), 15047 diag::err_literal_operator_param) 15048 << SecondParamType << Context.getSizeType() 15049 << (*Param)->getSourceRange(); 15050 return true; 15051 } 15052 } else { 15053 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count); 15054 return true; 15055 } 15056 15057 // Parameters are good. 15058 15059 // A parameter-declaration-clause containing a default argument is not 15060 // equivalent to any of the permitted forms. 15061 for (auto Param : FnDecl->parameters()) { 15062 if (Param->hasDefaultArg()) { 15063 Diag(Param->getDefaultArgRange().getBegin(), 15064 diag::err_literal_operator_default_argument) 15065 << Param->getDefaultArgRange(); 15066 break; 15067 } 15068 } 15069 15070 StringRef LiteralName 15071 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 15072 if (LiteralName[0] != '_' && 15073 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) { 15074 // C++11 [usrlit.suffix]p1: 15075 // Literal suffix identifiers that do not start with an underscore 15076 // are reserved for future standardization. 15077 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 15078 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 15079 } 15080 15081 return false; 15082 } 15083 15084 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 15085 /// linkage specification, including the language and (if present) 15086 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 15087 /// language string literal. LBraceLoc, if valid, provides the location of 15088 /// the '{' brace. Otherwise, this linkage specification does not 15089 /// have any braces. 15090 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 15091 Expr *LangStr, 15092 SourceLocation LBraceLoc) { 15093 StringLiteral *Lit = cast<StringLiteral>(LangStr); 15094 if (!Lit->isAscii()) { 15095 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 15096 << LangStr->getSourceRange(); 15097 return nullptr; 15098 } 15099 15100 StringRef Lang = Lit->getString(); 15101 LinkageSpecDecl::LanguageIDs Language; 15102 if (Lang == "C") 15103 Language = LinkageSpecDecl::lang_c; 15104 else if (Lang == "C++") 15105 Language = LinkageSpecDecl::lang_cxx; 15106 else { 15107 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 15108 << LangStr->getSourceRange(); 15109 return nullptr; 15110 } 15111 15112 // FIXME: Add all the various semantics of linkage specifications 15113 15114 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 15115 LangStr->getExprLoc(), Language, 15116 LBraceLoc.isValid()); 15117 CurContext->addDecl(D); 15118 PushDeclContext(S, D); 15119 return D; 15120 } 15121 15122 /// ActOnFinishLinkageSpecification - Complete the definition of 15123 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 15124 /// valid, it's the position of the closing '}' brace in a linkage 15125 /// specification that uses braces. 15126 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 15127 Decl *LinkageSpec, 15128 SourceLocation RBraceLoc) { 15129 if (RBraceLoc.isValid()) { 15130 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 15131 LSDecl->setRBraceLoc(RBraceLoc); 15132 } 15133 PopDeclContext(); 15134 return LinkageSpec; 15135 } 15136 15137 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 15138 const ParsedAttributesView &AttrList, 15139 SourceLocation SemiLoc) { 15140 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 15141 // Attribute declarations appertain to empty declaration so we handle 15142 // them here. 15143 ProcessDeclAttributeList(S, ED, AttrList); 15144 15145 CurContext->addDecl(ED); 15146 return ED; 15147 } 15148 15149 /// Perform semantic analysis for the variable declaration that 15150 /// occurs within a C++ catch clause, returning the newly-created 15151 /// variable. 15152 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 15153 TypeSourceInfo *TInfo, 15154 SourceLocation StartLoc, 15155 SourceLocation Loc, 15156 IdentifierInfo *Name) { 15157 bool Invalid = false; 15158 QualType ExDeclType = TInfo->getType(); 15159 15160 // Arrays and functions decay. 15161 if (ExDeclType->isArrayType()) 15162 ExDeclType = Context.getArrayDecayedType(ExDeclType); 15163 else if (ExDeclType->isFunctionType()) 15164 ExDeclType = Context.getPointerType(ExDeclType); 15165 15166 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 15167 // The exception-declaration shall not denote a pointer or reference to an 15168 // incomplete type, other than [cv] void*. 15169 // N2844 forbids rvalue references. 15170 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 15171 Diag(Loc, diag::err_catch_rvalue_ref); 15172 Invalid = true; 15173 } 15174 15175 if (ExDeclType->isVariablyModifiedType()) { 15176 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType; 15177 Invalid = true; 15178 } 15179 15180 QualType BaseType = ExDeclType; 15181 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 15182 unsigned DK = diag::err_catch_incomplete; 15183 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 15184 BaseType = Ptr->getPointeeType(); 15185 Mode = 1; 15186 DK = diag::err_catch_incomplete_ptr; 15187 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 15188 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 15189 BaseType = Ref->getPointeeType(); 15190 Mode = 2; 15191 DK = diag::err_catch_incomplete_ref; 15192 } 15193 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 15194 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 15195 Invalid = true; 15196 15197 if (!Invalid && !ExDeclType->isDependentType() && 15198 RequireNonAbstractType(Loc, ExDeclType, 15199 diag::err_abstract_type_in_decl, 15200 AbstractVariableType)) 15201 Invalid = true; 15202 15203 // Only the non-fragile NeXT runtime currently supports C++ catches 15204 // of ObjC types, and no runtime supports catching ObjC types by value. 15205 if (!Invalid && getLangOpts().ObjC) { 15206 QualType T = ExDeclType; 15207 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 15208 T = RT->getPointeeType(); 15209 15210 if (T->isObjCObjectType()) { 15211 Diag(Loc, diag::err_objc_object_catch); 15212 Invalid = true; 15213 } else if (T->isObjCObjectPointerType()) { 15214 // FIXME: should this be a test for macosx-fragile specifically? 15215 if (getLangOpts().ObjCRuntime.isFragile()) 15216 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 15217 } 15218 } 15219 15220 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 15221 ExDeclType, TInfo, SC_None); 15222 ExDecl->setExceptionVariable(true); 15223 15224 // In ARC, infer 'retaining' for variables of retainable type. 15225 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 15226 Invalid = true; 15227 15228 if (!Invalid && !ExDeclType->isDependentType()) { 15229 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 15230 // Insulate this from anything else we might currently be parsing. 15231 EnterExpressionEvaluationContext scope( 15232 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 15233 15234 // C++ [except.handle]p16: 15235 // The object declared in an exception-declaration or, if the 15236 // exception-declaration does not specify a name, a temporary (12.2) is 15237 // copy-initialized (8.5) from the exception object. [...] 15238 // The object is destroyed when the handler exits, after the destruction 15239 // of any automatic objects initialized within the handler. 15240 // 15241 // We just pretend to initialize the object with itself, then make sure 15242 // it can be destroyed later. 15243 QualType initType = Context.getExceptionObjectType(ExDeclType); 15244 15245 InitializedEntity entity = 15246 InitializedEntity::InitializeVariable(ExDecl); 15247 InitializationKind initKind = 15248 InitializationKind::CreateCopy(Loc, SourceLocation()); 15249 15250 Expr *opaqueValue = 15251 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 15252 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 15253 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 15254 if (result.isInvalid()) 15255 Invalid = true; 15256 else { 15257 // If the constructor used was non-trivial, set this as the 15258 // "initializer". 15259 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 15260 if (!construct->getConstructor()->isTrivial()) { 15261 Expr *init = MaybeCreateExprWithCleanups(construct); 15262 ExDecl->setInit(init); 15263 } 15264 15265 // And make sure it's destructable. 15266 FinalizeVarWithDestructor(ExDecl, recordType); 15267 } 15268 } 15269 } 15270 15271 if (Invalid) 15272 ExDecl->setInvalidDecl(); 15273 15274 return ExDecl; 15275 } 15276 15277 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 15278 /// handler. 15279 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 15280 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 15281 bool Invalid = D.isInvalidType(); 15282 15283 // Check for unexpanded parameter packs. 15284 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 15285 UPPC_ExceptionType)) { 15286 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 15287 D.getIdentifierLoc()); 15288 Invalid = true; 15289 } 15290 15291 IdentifierInfo *II = D.getIdentifier(); 15292 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 15293 LookupOrdinaryName, 15294 ForVisibleRedeclaration)) { 15295 // The scope should be freshly made just for us. There is just no way 15296 // it contains any previous declaration, except for function parameters in 15297 // a function-try-block's catch statement. 15298 assert(!S->isDeclScope(PrevDecl)); 15299 if (isDeclInScope(PrevDecl, CurContext, S)) { 15300 Diag(D.getIdentifierLoc(), diag::err_redefinition) 15301 << D.getIdentifier(); 15302 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 15303 Invalid = true; 15304 } else if (PrevDecl->isTemplateParameter()) 15305 // Maybe we will complain about the shadowed template parameter. 15306 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 15307 } 15308 15309 if (D.getCXXScopeSpec().isSet() && !Invalid) { 15310 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 15311 << D.getCXXScopeSpec().getRange(); 15312 Invalid = true; 15313 } 15314 15315 VarDecl *ExDecl = BuildExceptionDeclaration( 15316 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier()); 15317 if (Invalid) 15318 ExDecl->setInvalidDecl(); 15319 15320 // Add the exception declaration into this scope. 15321 if (II) 15322 PushOnScopeChains(ExDecl, S); 15323 else 15324 CurContext->addDecl(ExDecl); 15325 15326 ProcessDeclAttributes(S, ExDecl, D); 15327 return ExDecl; 15328 } 15329 15330 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 15331 Expr *AssertExpr, 15332 Expr *AssertMessageExpr, 15333 SourceLocation RParenLoc) { 15334 StringLiteral *AssertMessage = 15335 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 15336 15337 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 15338 return nullptr; 15339 15340 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 15341 AssertMessage, RParenLoc, false); 15342 } 15343 15344 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 15345 Expr *AssertExpr, 15346 StringLiteral *AssertMessage, 15347 SourceLocation RParenLoc, 15348 bool Failed) { 15349 assert(AssertExpr != nullptr && "Expected non-null condition"); 15350 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 15351 !Failed) { 15352 // In a static_assert-declaration, the constant-expression shall be a 15353 // constant expression that can be contextually converted to bool. 15354 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 15355 if (Converted.isInvalid()) 15356 Failed = true; 15357 15358 ExprResult FullAssertExpr = 15359 ActOnFinishFullExpr(Converted.get(), StaticAssertLoc, 15360 /*DiscardedValue*/ false, 15361 /*IsConstexpr*/ true); 15362 if (FullAssertExpr.isInvalid()) 15363 Failed = true; 15364 else 15365 AssertExpr = FullAssertExpr.get(); 15366 15367 llvm::APSInt Cond; 15368 if (!Failed && VerifyIntegerConstantExpression(AssertExpr, &Cond, 15369 diag::err_static_assert_expression_is_not_constant, 15370 /*AllowFold=*/false).isInvalid()) 15371 Failed = true; 15372 15373 if (!Failed && !Cond) { 15374 SmallString<256> MsgBuffer; 15375 llvm::raw_svector_ostream Msg(MsgBuffer); 15376 if (AssertMessage) 15377 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 15378 15379 Expr *InnerCond = nullptr; 15380 std::string InnerCondDescription; 15381 std::tie(InnerCond, InnerCondDescription) = 15382 findFailedBooleanCondition(Converted.get()); 15383 if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) { 15384 // Drill down into concept specialization expressions to see why they 15385 // weren't satisfied. 15386 Diag(StaticAssertLoc, diag::err_static_assert_failed) 15387 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 15388 ConstraintSatisfaction Satisfaction; 15389 if (!CheckConstraintSatisfaction(InnerCond, Satisfaction)) 15390 DiagnoseUnsatisfiedConstraint(Satisfaction); 15391 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond) 15392 && !isa<IntegerLiteral>(InnerCond)) { 15393 Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed) 15394 << InnerCondDescription << !AssertMessage 15395 << Msg.str() << InnerCond->getSourceRange(); 15396 } else { 15397 Diag(StaticAssertLoc, diag::err_static_assert_failed) 15398 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 15399 } 15400 Failed = true; 15401 } 15402 } else { 15403 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc, 15404 /*DiscardedValue*/false, 15405 /*IsConstexpr*/true); 15406 if (FullAssertExpr.isInvalid()) 15407 Failed = true; 15408 else 15409 AssertExpr = FullAssertExpr.get(); 15410 } 15411 15412 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 15413 AssertExpr, AssertMessage, RParenLoc, 15414 Failed); 15415 15416 CurContext->addDecl(Decl); 15417 return Decl; 15418 } 15419 15420 /// Perform semantic analysis of the given friend type declaration. 15421 /// 15422 /// \returns A friend declaration that. 15423 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 15424 SourceLocation FriendLoc, 15425 TypeSourceInfo *TSInfo) { 15426 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 15427 15428 QualType T = TSInfo->getType(); 15429 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 15430 15431 // C++03 [class.friend]p2: 15432 // An elaborated-type-specifier shall be used in a friend declaration 15433 // for a class.* 15434 // 15435 // * The class-key of the elaborated-type-specifier is required. 15436 if (!CodeSynthesisContexts.empty()) { 15437 // Do not complain about the form of friend template types during any kind 15438 // of code synthesis. For template instantiation, we will have complained 15439 // when the template was defined. 15440 } else { 15441 if (!T->isElaboratedTypeSpecifier()) { 15442 // If we evaluated the type to a record type, suggest putting 15443 // a tag in front. 15444 if (const RecordType *RT = T->getAs<RecordType>()) { 15445 RecordDecl *RD = RT->getDecl(); 15446 15447 SmallString<16> InsertionText(" "); 15448 InsertionText += RD->getKindName(); 15449 15450 Diag(TypeRange.getBegin(), 15451 getLangOpts().CPlusPlus11 ? 15452 diag::warn_cxx98_compat_unelaborated_friend_type : 15453 diag::ext_unelaborated_friend_type) 15454 << (unsigned) RD->getTagKind() 15455 << T 15456 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc), 15457 InsertionText); 15458 } else { 15459 Diag(FriendLoc, 15460 getLangOpts().CPlusPlus11 ? 15461 diag::warn_cxx98_compat_nonclass_type_friend : 15462 diag::ext_nonclass_type_friend) 15463 << T 15464 << TypeRange; 15465 } 15466 } else if (T->getAs<EnumType>()) { 15467 Diag(FriendLoc, 15468 getLangOpts().CPlusPlus11 ? 15469 diag::warn_cxx98_compat_enum_friend : 15470 diag::ext_enum_friend) 15471 << T 15472 << TypeRange; 15473 } 15474 15475 // C++11 [class.friend]p3: 15476 // A friend declaration that does not declare a function shall have one 15477 // of the following forms: 15478 // friend elaborated-type-specifier ; 15479 // friend simple-type-specifier ; 15480 // friend typename-specifier ; 15481 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 15482 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 15483 } 15484 15485 // If the type specifier in a friend declaration designates a (possibly 15486 // cv-qualified) class type, that class is declared as a friend; otherwise, 15487 // the friend declaration is ignored. 15488 return FriendDecl::Create(Context, CurContext, 15489 TSInfo->getTypeLoc().getBeginLoc(), TSInfo, 15490 FriendLoc); 15491 } 15492 15493 /// Handle a friend tag declaration where the scope specifier was 15494 /// templated. 15495 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 15496 unsigned TagSpec, SourceLocation TagLoc, 15497 CXXScopeSpec &SS, IdentifierInfo *Name, 15498 SourceLocation NameLoc, 15499 const ParsedAttributesView &Attr, 15500 MultiTemplateParamsArg TempParamLists) { 15501 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 15502 15503 bool IsMemberSpecialization = false; 15504 bool Invalid = false; 15505 15506 if (TemplateParameterList *TemplateParams = 15507 MatchTemplateParametersToScopeSpecifier( 15508 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 15509 IsMemberSpecialization, Invalid)) { 15510 if (TemplateParams->size() > 0) { 15511 // This is a declaration of a class template. 15512 if (Invalid) 15513 return nullptr; 15514 15515 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 15516 NameLoc, Attr, TemplateParams, AS_public, 15517 /*ModulePrivateLoc=*/SourceLocation(), 15518 FriendLoc, TempParamLists.size() - 1, 15519 TempParamLists.data()).get(); 15520 } else { 15521 // The "template<>" header is extraneous. 15522 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 15523 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 15524 IsMemberSpecialization = true; 15525 } 15526 } 15527 15528 if (Invalid) return nullptr; 15529 15530 bool isAllExplicitSpecializations = true; 15531 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 15532 if (TempParamLists[I]->size()) { 15533 isAllExplicitSpecializations = false; 15534 break; 15535 } 15536 } 15537 15538 // FIXME: don't ignore attributes. 15539 15540 // If it's explicit specializations all the way down, just forget 15541 // about the template header and build an appropriate non-templated 15542 // friend. TODO: for source fidelity, remember the headers. 15543 if (isAllExplicitSpecializations) { 15544 if (SS.isEmpty()) { 15545 bool Owned = false; 15546 bool IsDependent = false; 15547 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 15548 Attr, AS_public, 15549 /*ModulePrivateLoc=*/SourceLocation(), 15550 MultiTemplateParamsArg(), Owned, IsDependent, 15551 /*ScopedEnumKWLoc=*/SourceLocation(), 15552 /*ScopedEnumUsesClassTag=*/false, 15553 /*UnderlyingType=*/TypeResult(), 15554 /*IsTypeSpecifier=*/false, 15555 /*IsTemplateParamOrArg=*/false); 15556 } 15557 15558 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 15559 ElaboratedTypeKeyword Keyword 15560 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 15561 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 15562 *Name, NameLoc); 15563 if (T.isNull()) 15564 return nullptr; 15565 15566 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 15567 if (isa<DependentNameType>(T)) { 15568 DependentNameTypeLoc TL = 15569 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 15570 TL.setElaboratedKeywordLoc(TagLoc); 15571 TL.setQualifierLoc(QualifierLoc); 15572 TL.setNameLoc(NameLoc); 15573 } else { 15574 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 15575 TL.setElaboratedKeywordLoc(TagLoc); 15576 TL.setQualifierLoc(QualifierLoc); 15577 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 15578 } 15579 15580 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 15581 TSI, FriendLoc, TempParamLists); 15582 Friend->setAccess(AS_public); 15583 CurContext->addDecl(Friend); 15584 return Friend; 15585 } 15586 15587 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 15588 15589 15590 15591 // Handle the case of a templated-scope friend class. e.g. 15592 // template <class T> class A<T>::B; 15593 // FIXME: we don't support these right now. 15594 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 15595 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 15596 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 15597 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 15598 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 15599 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 15600 TL.setElaboratedKeywordLoc(TagLoc); 15601 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 15602 TL.setNameLoc(NameLoc); 15603 15604 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 15605 TSI, FriendLoc, TempParamLists); 15606 Friend->setAccess(AS_public); 15607 Friend->setUnsupportedFriend(true); 15608 CurContext->addDecl(Friend); 15609 return Friend; 15610 } 15611 15612 /// Handle a friend type declaration. This works in tandem with 15613 /// ActOnTag. 15614 /// 15615 /// Notes on friend class templates: 15616 /// 15617 /// We generally treat friend class declarations as if they were 15618 /// declaring a class. So, for example, the elaborated type specifier 15619 /// in a friend declaration is required to obey the restrictions of a 15620 /// class-head (i.e. no typedefs in the scope chain), template 15621 /// parameters are required to match up with simple template-ids, &c. 15622 /// However, unlike when declaring a template specialization, it's 15623 /// okay to refer to a template specialization without an empty 15624 /// template parameter declaration, e.g. 15625 /// friend class A<T>::B<unsigned>; 15626 /// We permit this as a special case; if there are any template 15627 /// parameters present at all, require proper matching, i.e. 15628 /// template <> template \<class T> friend class A<int>::B; 15629 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 15630 MultiTemplateParamsArg TempParams) { 15631 SourceLocation Loc = DS.getBeginLoc(); 15632 15633 assert(DS.isFriendSpecified()); 15634 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 15635 15636 // C++ [class.friend]p3: 15637 // A friend declaration that does not declare a function shall have one of 15638 // the following forms: 15639 // friend elaborated-type-specifier ; 15640 // friend simple-type-specifier ; 15641 // friend typename-specifier ; 15642 // 15643 // Any declaration with a type qualifier does not have that form. (It's 15644 // legal to specify a qualified type as a friend, you just can't write the 15645 // keywords.) 15646 if (DS.getTypeQualifiers()) { 15647 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 15648 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const"; 15649 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 15650 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile"; 15651 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 15652 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict"; 15653 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 15654 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic"; 15655 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 15656 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned"; 15657 } 15658 15659 // Try to convert the decl specifier to a type. This works for 15660 // friend templates because ActOnTag never produces a ClassTemplateDecl 15661 // for a TUK_Friend. 15662 Declarator TheDeclarator(DS, DeclaratorContext::MemberContext); 15663 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 15664 QualType T = TSI->getType(); 15665 if (TheDeclarator.isInvalidType()) 15666 return nullptr; 15667 15668 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 15669 return nullptr; 15670 15671 // This is definitely an error in C++98. It's probably meant to 15672 // be forbidden in C++0x, too, but the specification is just 15673 // poorly written. 15674 // 15675 // The problem is with declarations like the following: 15676 // template <T> friend A<T>::foo; 15677 // where deciding whether a class C is a friend or not now hinges 15678 // on whether there exists an instantiation of A that causes 15679 // 'foo' to equal C. There are restrictions on class-heads 15680 // (which we declare (by fiat) elaborated friend declarations to 15681 // be) that makes this tractable. 15682 // 15683 // FIXME: handle "template <> friend class A<T>;", which 15684 // is possibly well-formed? Who even knows? 15685 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 15686 Diag(Loc, diag::err_tagless_friend_type_template) 15687 << DS.getSourceRange(); 15688 return nullptr; 15689 } 15690 15691 // C++98 [class.friend]p1: A friend of a class is a function 15692 // or class that is not a member of the class . . . 15693 // This is fixed in DR77, which just barely didn't make the C++03 15694 // deadline. It's also a very silly restriction that seriously 15695 // affects inner classes and which nobody else seems to implement; 15696 // thus we never diagnose it, not even in -pedantic. 15697 // 15698 // But note that we could warn about it: it's always useless to 15699 // friend one of your own members (it's not, however, worthless to 15700 // friend a member of an arbitrary specialization of your template). 15701 15702 Decl *D; 15703 if (!TempParams.empty()) 15704 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 15705 TempParams, 15706 TSI, 15707 DS.getFriendSpecLoc()); 15708 else 15709 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 15710 15711 if (!D) 15712 return nullptr; 15713 15714 D->setAccess(AS_public); 15715 CurContext->addDecl(D); 15716 15717 return D; 15718 } 15719 15720 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 15721 MultiTemplateParamsArg TemplateParams) { 15722 const DeclSpec &DS = D.getDeclSpec(); 15723 15724 assert(DS.isFriendSpecified()); 15725 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 15726 15727 SourceLocation Loc = D.getIdentifierLoc(); 15728 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 15729 15730 // C++ [class.friend]p1 15731 // A friend of a class is a function or class.... 15732 // Note that this sees through typedefs, which is intended. 15733 // It *doesn't* see through dependent types, which is correct 15734 // according to [temp.arg.type]p3: 15735 // If a declaration acquires a function type through a 15736 // type dependent on a template-parameter and this causes 15737 // a declaration that does not use the syntactic form of a 15738 // function declarator to have a function type, the program 15739 // is ill-formed. 15740 if (!TInfo->getType()->isFunctionType()) { 15741 Diag(Loc, diag::err_unexpected_friend); 15742 15743 // It might be worthwhile to try to recover by creating an 15744 // appropriate declaration. 15745 return nullptr; 15746 } 15747 15748 // C++ [namespace.memdef]p3 15749 // - If a friend declaration in a non-local class first declares a 15750 // class or function, the friend class or function is a member 15751 // of the innermost enclosing namespace. 15752 // - The name of the friend is not found by simple name lookup 15753 // until a matching declaration is provided in that namespace 15754 // scope (either before or after the class declaration granting 15755 // friendship). 15756 // - If a friend function is called, its name may be found by the 15757 // name lookup that considers functions from namespaces and 15758 // classes associated with the types of the function arguments. 15759 // - When looking for a prior declaration of a class or a function 15760 // declared as a friend, scopes outside the innermost enclosing 15761 // namespace scope are not considered. 15762 15763 CXXScopeSpec &SS = D.getCXXScopeSpec(); 15764 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 15765 assert(NameInfo.getName()); 15766 15767 // Check for unexpanded parameter packs. 15768 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 15769 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 15770 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 15771 return nullptr; 15772 15773 // The context we found the declaration in, or in which we should 15774 // create the declaration. 15775 DeclContext *DC; 15776 Scope *DCScope = S; 15777 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 15778 ForExternalRedeclaration); 15779 15780 // There are five cases here. 15781 // - There's no scope specifier and we're in a local class. Only look 15782 // for functions declared in the immediately-enclosing block scope. 15783 // We recover from invalid scope qualifiers as if they just weren't there. 15784 FunctionDecl *FunctionContainingLocalClass = nullptr; 15785 if ((SS.isInvalid() || !SS.isSet()) && 15786 (FunctionContainingLocalClass = 15787 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 15788 // C++11 [class.friend]p11: 15789 // If a friend declaration appears in a local class and the name 15790 // specified is an unqualified name, a prior declaration is 15791 // looked up without considering scopes that are outside the 15792 // innermost enclosing non-class scope. For a friend function 15793 // declaration, if there is no prior declaration, the program is 15794 // ill-formed. 15795 15796 // Find the innermost enclosing non-class scope. This is the block 15797 // scope containing the local class definition (or for a nested class, 15798 // the outer local class). 15799 DCScope = S->getFnParent(); 15800 15801 // Look up the function name in the scope. 15802 Previous.clear(LookupLocalFriendName); 15803 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 15804 15805 if (!Previous.empty()) { 15806 // All possible previous declarations must have the same context: 15807 // either they were declared at block scope or they are members of 15808 // one of the enclosing local classes. 15809 DC = Previous.getRepresentativeDecl()->getDeclContext(); 15810 } else { 15811 // This is ill-formed, but provide the context that we would have 15812 // declared the function in, if we were permitted to, for error recovery. 15813 DC = FunctionContainingLocalClass; 15814 } 15815 adjustContextForLocalExternDecl(DC); 15816 15817 // C++ [class.friend]p6: 15818 // A function can be defined in a friend declaration of a class if and 15819 // only if the class is a non-local class (9.8), the function name is 15820 // unqualified, and the function has namespace scope. 15821 if (D.isFunctionDefinition()) { 15822 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 15823 } 15824 15825 // - There's no scope specifier, in which case we just go to the 15826 // appropriate scope and look for a function or function template 15827 // there as appropriate. 15828 } else if (SS.isInvalid() || !SS.isSet()) { 15829 // C++11 [namespace.memdef]p3: 15830 // If the name in a friend declaration is neither qualified nor 15831 // a template-id and the declaration is a function or an 15832 // elaborated-type-specifier, the lookup to determine whether 15833 // the entity has been previously declared shall not consider 15834 // any scopes outside the innermost enclosing namespace. 15835 bool isTemplateId = 15836 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId; 15837 15838 // Find the appropriate context according to the above. 15839 DC = CurContext; 15840 15841 // Skip class contexts. If someone can cite chapter and verse 15842 // for this behavior, that would be nice --- it's what GCC and 15843 // EDG do, and it seems like a reasonable intent, but the spec 15844 // really only says that checks for unqualified existing 15845 // declarations should stop at the nearest enclosing namespace, 15846 // not that they should only consider the nearest enclosing 15847 // namespace. 15848 while (DC->isRecord()) 15849 DC = DC->getParent(); 15850 15851 DeclContext *LookupDC = DC; 15852 while (LookupDC->isTransparentContext()) 15853 LookupDC = LookupDC->getParent(); 15854 15855 while (true) { 15856 LookupQualifiedName(Previous, LookupDC); 15857 15858 if (!Previous.empty()) { 15859 DC = LookupDC; 15860 break; 15861 } 15862 15863 if (isTemplateId) { 15864 if (isa<TranslationUnitDecl>(LookupDC)) break; 15865 } else { 15866 if (LookupDC->isFileContext()) break; 15867 } 15868 LookupDC = LookupDC->getParent(); 15869 } 15870 15871 DCScope = getScopeForDeclContext(S, DC); 15872 15873 // - There's a non-dependent scope specifier, in which case we 15874 // compute it and do a previous lookup there for a function 15875 // or function template. 15876 } else if (!SS.getScopeRep()->isDependent()) { 15877 DC = computeDeclContext(SS); 15878 if (!DC) return nullptr; 15879 15880 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 15881 15882 LookupQualifiedName(Previous, DC); 15883 15884 // C++ [class.friend]p1: A friend of a class is a function or 15885 // class that is not a member of the class . . . 15886 if (DC->Equals(CurContext)) 15887 Diag(DS.getFriendSpecLoc(), 15888 getLangOpts().CPlusPlus11 ? 15889 diag::warn_cxx98_compat_friend_is_member : 15890 diag::err_friend_is_member); 15891 15892 if (D.isFunctionDefinition()) { 15893 // C++ [class.friend]p6: 15894 // A function can be defined in a friend declaration of a class if and 15895 // only if the class is a non-local class (9.8), the function name is 15896 // unqualified, and the function has namespace scope. 15897 // 15898 // FIXME: We should only do this if the scope specifier names the 15899 // innermost enclosing namespace; otherwise the fixit changes the 15900 // meaning of the code. 15901 SemaDiagnosticBuilder DB 15902 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 15903 15904 DB << SS.getScopeRep(); 15905 if (DC->isFileContext()) 15906 DB << FixItHint::CreateRemoval(SS.getRange()); 15907 SS.clear(); 15908 } 15909 15910 // - There's a scope specifier that does not match any template 15911 // parameter lists, in which case we use some arbitrary context, 15912 // create a method or method template, and wait for instantiation. 15913 // - There's a scope specifier that does match some template 15914 // parameter lists, which we don't handle right now. 15915 } else { 15916 if (D.isFunctionDefinition()) { 15917 // C++ [class.friend]p6: 15918 // A function can be defined in a friend declaration of a class if and 15919 // only if the class is a non-local class (9.8), the function name is 15920 // unqualified, and the function has namespace scope. 15921 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 15922 << SS.getScopeRep(); 15923 } 15924 15925 DC = CurContext; 15926 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 15927 } 15928 15929 if (!DC->isRecord()) { 15930 int DiagArg = -1; 15931 switch (D.getName().getKind()) { 15932 case UnqualifiedIdKind::IK_ConstructorTemplateId: 15933 case UnqualifiedIdKind::IK_ConstructorName: 15934 DiagArg = 0; 15935 break; 15936 case UnqualifiedIdKind::IK_DestructorName: 15937 DiagArg = 1; 15938 break; 15939 case UnqualifiedIdKind::IK_ConversionFunctionId: 15940 DiagArg = 2; 15941 break; 15942 case UnqualifiedIdKind::IK_DeductionGuideName: 15943 DiagArg = 3; 15944 break; 15945 case UnqualifiedIdKind::IK_Identifier: 15946 case UnqualifiedIdKind::IK_ImplicitSelfParam: 15947 case UnqualifiedIdKind::IK_LiteralOperatorId: 15948 case UnqualifiedIdKind::IK_OperatorFunctionId: 15949 case UnqualifiedIdKind::IK_TemplateId: 15950 break; 15951 } 15952 // This implies that it has to be an operator or function. 15953 if (DiagArg >= 0) { 15954 Diag(Loc, diag::err_introducing_special_friend) << DiagArg; 15955 return nullptr; 15956 } 15957 } 15958 15959 // FIXME: This is an egregious hack to cope with cases where the scope stack 15960 // does not contain the declaration context, i.e., in an out-of-line 15961 // definition of a class. 15962 Scope FakeDCScope(S, Scope::DeclScope, Diags); 15963 if (!DCScope) { 15964 FakeDCScope.setEntity(DC); 15965 DCScope = &FakeDCScope; 15966 } 15967 15968 bool AddToScope = true; 15969 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 15970 TemplateParams, AddToScope); 15971 if (!ND) return nullptr; 15972 15973 assert(ND->getLexicalDeclContext() == CurContext); 15974 15975 // If we performed typo correction, we might have added a scope specifier 15976 // and changed the decl context. 15977 DC = ND->getDeclContext(); 15978 15979 // Add the function declaration to the appropriate lookup tables, 15980 // adjusting the redeclarations list as necessary. We don't 15981 // want to do this yet if the friending class is dependent. 15982 // 15983 // Also update the scope-based lookup if the target context's 15984 // lookup context is in lexical scope. 15985 if (!CurContext->isDependentContext()) { 15986 DC = DC->getRedeclContext(); 15987 DC->makeDeclVisibleInContext(ND); 15988 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 15989 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 15990 } 15991 15992 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 15993 D.getIdentifierLoc(), ND, 15994 DS.getFriendSpecLoc()); 15995 FrD->setAccess(AS_public); 15996 CurContext->addDecl(FrD); 15997 15998 if (ND->isInvalidDecl()) { 15999 FrD->setInvalidDecl(); 16000 } else { 16001 if (DC->isRecord()) CheckFriendAccess(ND); 16002 16003 FunctionDecl *FD; 16004 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 16005 FD = FTD->getTemplatedDecl(); 16006 else 16007 FD = cast<FunctionDecl>(ND); 16008 16009 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 16010 // default argument expression, that declaration shall be a definition 16011 // and shall be the only declaration of the function or function 16012 // template in the translation unit. 16013 if (functionDeclHasDefaultArgument(FD)) { 16014 // We can't look at FD->getPreviousDecl() because it may not have been set 16015 // if we're in a dependent context. If the function is known to be a 16016 // redeclaration, we will have narrowed Previous down to the right decl. 16017 if (D.isRedeclaration()) { 16018 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 16019 Diag(Previous.getRepresentativeDecl()->getLocation(), 16020 diag::note_previous_declaration); 16021 } else if (!D.isFunctionDefinition()) 16022 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 16023 } 16024 16025 // Mark templated-scope function declarations as unsupported. 16026 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 16027 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 16028 << SS.getScopeRep() << SS.getRange() 16029 << cast<CXXRecordDecl>(CurContext); 16030 FrD->setUnsupportedFriend(true); 16031 } 16032 } 16033 16034 return ND; 16035 } 16036 16037 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 16038 AdjustDeclIfTemplate(Dcl); 16039 16040 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 16041 if (!Fn) { 16042 Diag(DelLoc, diag::err_deleted_non_function); 16043 return; 16044 } 16045 16046 // Deleted function does not have a body. 16047 Fn->setWillHaveBody(false); 16048 16049 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 16050 // Don't consider the implicit declaration we generate for explicit 16051 // specializations. FIXME: Do not generate these implicit declarations. 16052 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 16053 Prev->getPreviousDecl()) && 16054 !Prev->isDefined()) { 16055 Diag(DelLoc, diag::err_deleted_decl_not_first); 16056 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 16057 Prev->isImplicit() ? diag::note_previous_implicit_declaration 16058 : diag::note_previous_declaration); 16059 } 16060 // If the declaration wasn't the first, we delete the function anyway for 16061 // recovery. 16062 Fn = Fn->getCanonicalDecl(); 16063 } 16064 16065 // dllimport/dllexport cannot be deleted. 16066 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 16067 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 16068 Fn->setInvalidDecl(); 16069 } 16070 16071 if (Fn->isDeleted()) 16072 return; 16073 16074 // C++11 [basic.start.main]p3: 16075 // A program that defines main as deleted [...] is ill-formed. 16076 if (Fn->isMain()) 16077 Diag(DelLoc, diag::err_deleted_main); 16078 16079 // C++11 [dcl.fct.def.delete]p4: 16080 // A deleted function is implicitly inline. 16081 Fn->setImplicitlyInline(); 16082 Fn->setDeletedAsWritten(); 16083 16084 // See if we're deleting a function which is already known to override a 16085 // non-deleted virtual function. 16086 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 16087 bool IssuedDiagnostic = false; 16088 for (const CXXMethodDecl *O : MD->overridden_methods()) { 16089 if (!(*MD->begin_overridden_methods())->isDeleted()) { 16090 if (!IssuedDiagnostic) { 16091 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 16092 IssuedDiagnostic = true; 16093 } 16094 Diag(O->getLocation(), diag::note_overridden_virtual_function); 16095 } 16096 } 16097 // If this function was implicitly deleted because it was defaulted, 16098 // explain why it was deleted. 16099 if (IssuedDiagnostic && MD->isDefaulted()) 16100 DiagnoseDeletedDefaultedFunction(MD); 16101 } 16102 } 16103 16104 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 16105 if (!Dcl || Dcl->isInvalidDecl()) 16106 return; 16107 16108 auto *FD = dyn_cast<FunctionDecl>(Dcl); 16109 if (!FD) { 16110 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) { 16111 if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) { 16112 Diag(DefaultLoc, diag::err_defaulted_comparison_template); 16113 return; 16114 } 16115 } 16116 16117 Diag(DefaultLoc, diag::err_default_special_members) 16118 << getLangOpts().CPlusPlus2a; 16119 return; 16120 } 16121 16122 // Reject if this can't possibly be a defaultable function. 16123 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD); 16124 if (!DefKind && 16125 // A dependent function that doesn't locally look defaultable can 16126 // still instantiate to a defaultable function if it's a constructor 16127 // or assignment operator. 16128 (!FD->isDependentContext() || 16129 (!isa<CXXConstructorDecl>(FD) && 16130 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) { 16131 Diag(DefaultLoc, diag::err_default_special_members) 16132 << getLangOpts().CPlusPlus2a; 16133 return; 16134 } 16135 16136 if (DefKind.isComparison() && 16137 !isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 16138 Diag(FD->getLocation(), diag::err_defaulted_comparison_out_of_class) 16139 << (int)DefKind.asComparison(); 16140 return; 16141 } 16142 16143 // Issue compatibility warning. We already warned if the operator is 16144 // 'operator<=>' when parsing the '<=>' token. 16145 if (DefKind.isComparison() && 16146 DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) { 16147 Diag(DefaultLoc, getLangOpts().CPlusPlus2a 16148 ? diag::warn_cxx17_compat_defaulted_comparison 16149 : diag::ext_defaulted_comparison); 16150 } 16151 16152 FD->setDefaulted(); 16153 FD->setExplicitlyDefaulted(); 16154 16155 // Defer checking functions that are defaulted in a dependent context. 16156 if (FD->isDependentContext()) 16157 return; 16158 16159 // Unset that we will have a body for this function. We might not, 16160 // if it turns out to be trivial, and we don't need this marking now 16161 // that we've marked it as defaulted. 16162 FD->setWillHaveBody(false); 16163 16164 // If this definition appears within the record, do the checking when 16165 // the record is complete. This is always the case for a defaulted 16166 // comparison. 16167 if (DefKind.isComparison()) 16168 return; 16169 auto *MD = cast<CXXMethodDecl>(FD); 16170 16171 const FunctionDecl *Primary = FD; 16172 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern()) 16173 // Ask the template instantiation pattern that actually had the 16174 // '= default' on it. 16175 Primary = Pattern; 16176 16177 // If the method was defaulted on its first declaration, we will have 16178 // already performed the checking in CheckCompletedCXXClass. Such a 16179 // declaration doesn't trigger an implicit definition. 16180 if (Primary->getCanonicalDecl()->isDefaulted()) 16181 return; 16182 16183 if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember())) 16184 MD->setInvalidDecl(); 16185 else 16186 DefineImplicitSpecialMember(*this, MD, DefaultLoc); 16187 } 16188 16189 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 16190 for (Stmt *SubStmt : S->children()) { 16191 if (!SubStmt) 16192 continue; 16193 if (isa<ReturnStmt>(SubStmt)) 16194 Self.Diag(SubStmt->getBeginLoc(), 16195 diag::err_return_in_constructor_handler); 16196 if (!isa<Expr>(SubStmt)) 16197 SearchForReturnInStmt(Self, SubStmt); 16198 } 16199 } 16200 16201 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 16202 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 16203 CXXCatchStmt *Handler = TryBlock->getHandler(I); 16204 SearchForReturnInStmt(*this, Handler); 16205 } 16206 } 16207 16208 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 16209 const CXXMethodDecl *Old) { 16210 const auto *NewFT = New->getType()->getAs<FunctionProtoType>(); 16211 const auto *OldFT = Old->getType()->getAs<FunctionProtoType>(); 16212 16213 if (OldFT->hasExtParameterInfos()) { 16214 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I) 16215 // A parameter of the overriding method should be annotated with noescape 16216 // if the corresponding parameter of the overridden method is annotated. 16217 if (OldFT->getExtParameterInfo(I).isNoEscape() && 16218 !NewFT->getExtParameterInfo(I).isNoEscape()) { 16219 Diag(New->getParamDecl(I)->getLocation(), 16220 diag::warn_overriding_method_missing_noescape); 16221 Diag(Old->getParamDecl(I)->getLocation(), 16222 diag::note_overridden_marked_noescape); 16223 } 16224 } 16225 16226 // Virtual overrides must have the same code_seg. 16227 const auto *OldCSA = Old->getAttr<CodeSegAttr>(); 16228 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 16229 if ((NewCSA || OldCSA) && 16230 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) { 16231 Diag(New->getLocation(), diag::err_mismatched_code_seg_override); 16232 Diag(Old->getLocation(), diag::note_previous_declaration); 16233 return true; 16234 } 16235 16236 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 16237 16238 // If the calling conventions match, everything is fine 16239 if (NewCC == OldCC) 16240 return false; 16241 16242 // If the calling conventions mismatch because the new function is static, 16243 // suppress the calling convention mismatch error; the error about static 16244 // function override (err_static_overrides_virtual from 16245 // Sema::CheckFunctionDeclaration) is more clear. 16246 if (New->getStorageClass() == SC_Static) 16247 return false; 16248 16249 Diag(New->getLocation(), 16250 diag::err_conflicting_overriding_cc_attributes) 16251 << New->getDeclName() << New->getType() << Old->getType(); 16252 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 16253 return true; 16254 } 16255 16256 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 16257 const CXXMethodDecl *Old) { 16258 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType(); 16259 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType(); 16260 16261 if (Context.hasSameType(NewTy, OldTy) || 16262 NewTy->isDependentType() || OldTy->isDependentType()) 16263 return false; 16264 16265 // Check if the return types are covariant 16266 QualType NewClassTy, OldClassTy; 16267 16268 /// Both types must be pointers or references to classes. 16269 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 16270 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 16271 NewClassTy = NewPT->getPointeeType(); 16272 OldClassTy = OldPT->getPointeeType(); 16273 } 16274 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 16275 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 16276 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 16277 NewClassTy = NewRT->getPointeeType(); 16278 OldClassTy = OldRT->getPointeeType(); 16279 } 16280 } 16281 } 16282 16283 // The return types aren't either both pointers or references to a class type. 16284 if (NewClassTy.isNull()) { 16285 Diag(New->getLocation(), 16286 diag::err_different_return_type_for_overriding_virtual_function) 16287 << New->getDeclName() << NewTy << OldTy 16288 << New->getReturnTypeSourceRange(); 16289 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 16290 << Old->getReturnTypeSourceRange(); 16291 16292 return true; 16293 } 16294 16295 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 16296 // C++14 [class.virtual]p8: 16297 // If the class type in the covariant return type of D::f differs from 16298 // that of B::f, the class type in the return type of D::f shall be 16299 // complete at the point of declaration of D::f or shall be the class 16300 // type D. 16301 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 16302 if (!RT->isBeingDefined() && 16303 RequireCompleteType(New->getLocation(), NewClassTy, 16304 diag::err_covariant_return_incomplete, 16305 New->getDeclName())) 16306 return true; 16307 } 16308 16309 // Check if the new class derives from the old class. 16310 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) { 16311 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 16312 << New->getDeclName() << NewTy << OldTy 16313 << New->getReturnTypeSourceRange(); 16314 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 16315 << Old->getReturnTypeSourceRange(); 16316 return true; 16317 } 16318 16319 // Check if we the conversion from derived to base is valid. 16320 if (CheckDerivedToBaseConversion( 16321 NewClassTy, OldClassTy, 16322 diag::err_covariant_return_inaccessible_base, 16323 diag::err_covariant_return_ambiguous_derived_to_base_conv, 16324 New->getLocation(), New->getReturnTypeSourceRange(), 16325 New->getDeclName(), nullptr)) { 16326 // FIXME: this note won't trigger for delayed access control 16327 // diagnostics, and it's impossible to get an undelayed error 16328 // here from access control during the original parse because 16329 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 16330 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 16331 << Old->getReturnTypeSourceRange(); 16332 return true; 16333 } 16334 } 16335 16336 // The qualifiers of the return types must be the same. 16337 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 16338 Diag(New->getLocation(), 16339 diag::err_covariant_return_type_different_qualifications) 16340 << New->getDeclName() << NewTy << OldTy 16341 << New->getReturnTypeSourceRange(); 16342 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 16343 << Old->getReturnTypeSourceRange(); 16344 return true; 16345 } 16346 16347 16348 // The new class type must have the same or less qualifiers as the old type. 16349 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 16350 Diag(New->getLocation(), 16351 diag::err_covariant_return_type_class_type_more_qualified) 16352 << New->getDeclName() << NewTy << OldTy 16353 << New->getReturnTypeSourceRange(); 16354 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 16355 << Old->getReturnTypeSourceRange(); 16356 return true; 16357 } 16358 16359 return false; 16360 } 16361 16362 /// Mark the given method pure. 16363 /// 16364 /// \param Method the method to be marked pure. 16365 /// 16366 /// \param InitRange the source range that covers the "0" initializer. 16367 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 16368 SourceLocation EndLoc = InitRange.getEnd(); 16369 if (EndLoc.isValid()) 16370 Method->setRangeEnd(EndLoc); 16371 16372 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 16373 Method->setPure(); 16374 return false; 16375 } 16376 16377 if (!Method->isInvalidDecl()) 16378 Diag(Method->getLocation(), diag::err_non_virtual_pure) 16379 << Method->getDeclName() << InitRange; 16380 return true; 16381 } 16382 16383 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) { 16384 if (D->getFriendObjectKind()) 16385 Diag(D->getLocation(), diag::err_pure_friend); 16386 else if (auto *M = dyn_cast<CXXMethodDecl>(D)) 16387 CheckPureMethod(M, ZeroLoc); 16388 else 16389 Diag(D->getLocation(), diag::err_illegal_initializer); 16390 } 16391 16392 /// Determine whether the given declaration is a global variable or 16393 /// static data member. 16394 static bool isNonlocalVariable(const Decl *D) { 16395 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 16396 return Var->hasGlobalStorage(); 16397 16398 return false; 16399 } 16400 16401 /// Invoked when we are about to parse an initializer for the declaration 16402 /// 'Dcl'. 16403 /// 16404 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 16405 /// static data member of class X, names should be looked up in the scope of 16406 /// class X. If the declaration had a scope specifier, a scope will have 16407 /// been created and passed in for this purpose. Otherwise, S will be null. 16408 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 16409 // If there is no declaration, there was an error parsing it. 16410 if (!D || D->isInvalidDecl()) 16411 return; 16412 16413 // We will always have a nested name specifier here, but this declaration 16414 // might not be out of line if the specifier names the current namespace: 16415 // extern int n; 16416 // int ::n = 0; 16417 if (S && D->isOutOfLine()) 16418 EnterDeclaratorContext(S, D->getDeclContext()); 16419 16420 // If we are parsing the initializer for a static data member, push a 16421 // new expression evaluation context that is associated with this static 16422 // data member. 16423 if (isNonlocalVariable(D)) 16424 PushExpressionEvaluationContext( 16425 ExpressionEvaluationContext::PotentiallyEvaluated, D); 16426 } 16427 16428 /// Invoked after we are finished parsing an initializer for the declaration D. 16429 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 16430 // If there is no declaration, there was an error parsing it. 16431 if (!D || D->isInvalidDecl()) 16432 return; 16433 16434 if (isNonlocalVariable(D)) 16435 PopExpressionEvaluationContext(); 16436 16437 if (S && D->isOutOfLine()) 16438 ExitDeclaratorContext(S); 16439 } 16440 16441 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 16442 /// C++ if/switch/while/for statement. 16443 /// e.g: "if (int x = f()) {...}" 16444 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 16445 // C++ 6.4p2: 16446 // The declarator shall not specify a function or an array. 16447 // The type-specifier-seq shall not contain typedef and shall not declare a 16448 // new class or enumeration. 16449 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 16450 "Parser allowed 'typedef' as storage class of condition decl."); 16451 16452 Decl *Dcl = ActOnDeclarator(S, D); 16453 if (!Dcl) 16454 return true; 16455 16456 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 16457 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 16458 << D.getSourceRange(); 16459 return true; 16460 } 16461 16462 return Dcl; 16463 } 16464 16465 void Sema::LoadExternalVTableUses() { 16466 if (!ExternalSource) 16467 return; 16468 16469 SmallVector<ExternalVTableUse, 4> VTables; 16470 ExternalSource->ReadUsedVTables(VTables); 16471 SmallVector<VTableUse, 4> NewUses; 16472 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 16473 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 16474 = VTablesUsed.find(VTables[I].Record); 16475 // Even if a definition wasn't required before, it may be required now. 16476 if (Pos != VTablesUsed.end()) { 16477 if (!Pos->second && VTables[I].DefinitionRequired) 16478 Pos->second = true; 16479 continue; 16480 } 16481 16482 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 16483 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 16484 } 16485 16486 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 16487 } 16488 16489 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 16490 bool DefinitionRequired) { 16491 // Ignore any vtable uses in unevaluated operands or for classes that do 16492 // not have a vtable. 16493 if (!Class->isDynamicClass() || Class->isDependentContext() || 16494 CurContext->isDependentContext() || isUnevaluatedContext()) 16495 return; 16496 // Do not mark as used if compiling for the device outside of the target 16497 // region. 16498 if (LangOpts.OpenMP && LangOpts.OpenMPIsDevice && 16499 !isInOpenMPDeclareTargetContext() && 16500 !isInOpenMPTargetExecutionDirective()) { 16501 if (!DefinitionRequired) 16502 MarkVirtualMembersReferenced(Loc, Class); 16503 return; 16504 } 16505 16506 // Try to insert this class into the map. 16507 LoadExternalVTableUses(); 16508 Class = Class->getCanonicalDecl(); 16509 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 16510 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 16511 if (!Pos.second) { 16512 // If we already had an entry, check to see if we are promoting this vtable 16513 // to require a definition. If so, we need to reappend to the VTableUses 16514 // list, since we may have already processed the first entry. 16515 if (DefinitionRequired && !Pos.first->second) { 16516 Pos.first->second = true; 16517 } else { 16518 // Otherwise, we can early exit. 16519 return; 16520 } 16521 } else { 16522 // The Microsoft ABI requires that we perform the destructor body 16523 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 16524 // the deleting destructor is emitted with the vtable, not with the 16525 // destructor definition as in the Itanium ABI. 16526 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 16527 CXXDestructorDecl *DD = Class->getDestructor(); 16528 if (DD && DD->isVirtual() && !DD->isDeleted()) { 16529 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) { 16530 // If this is an out-of-line declaration, marking it referenced will 16531 // not do anything. Manually call CheckDestructor to look up operator 16532 // delete(). 16533 ContextRAII SavedContext(*this, DD); 16534 CheckDestructor(DD); 16535 } else { 16536 MarkFunctionReferenced(Loc, Class->getDestructor()); 16537 } 16538 } 16539 } 16540 } 16541 16542 // Local classes need to have their virtual members marked 16543 // immediately. For all other classes, we mark their virtual members 16544 // at the end of the translation unit. 16545 if (Class->isLocalClass()) 16546 MarkVirtualMembersReferenced(Loc, Class); 16547 else 16548 VTableUses.push_back(std::make_pair(Class, Loc)); 16549 } 16550 16551 bool Sema::DefineUsedVTables() { 16552 LoadExternalVTableUses(); 16553 if (VTableUses.empty()) 16554 return false; 16555 16556 // Note: The VTableUses vector could grow as a result of marking 16557 // the members of a class as "used", so we check the size each 16558 // time through the loop and prefer indices (which are stable) to 16559 // iterators (which are not). 16560 bool DefinedAnything = false; 16561 for (unsigned I = 0; I != VTableUses.size(); ++I) { 16562 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 16563 if (!Class) 16564 continue; 16565 TemplateSpecializationKind ClassTSK = 16566 Class->getTemplateSpecializationKind(); 16567 16568 SourceLocation Loc = VTableUses[I].second; 16569 16570 bool DefineVTable = true; 16571 16572 // If this class has a key function, but that key function is 16573 // defined in another translation unit, we don't need to emit the 16574 // vtable even though we're using it. 16575 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 16576 if (KeyFunction && !KeyFunction->hasBody()) { 16577 // The key function is in another translation unit. 16578 DefineVTable = false; 16579 TemplateSpecializationKind TSK = 16580 KeyFunction->getTemplateSpecializationKind(); 16581 assert(TSK != TSK_ExplicitInstantiationDefinition && 16582 TSK != TSK_ImplicitInstantiation && 16583 "Instantiations don't have key functions"); 16584 (void)TSK; 16585 } else if (!KeyFunction) { 16586 // If we have a class with no key function that is the subject 16587 // of an explicit instantiation declaration, suppress the 16588 // vtable; it will live with the explicit instantiation 16589 // definition. 16590 bool IsExplicitInstantiationDeclaration = 16591 ClassTSK == TSK_ExplicitInstantiationDeclaration; 16592 for (auto R : Class->redecls()) { 16593 TemplateSpecializationKind TSK 16594 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 16595 if (TSK == TSK_ExplicitInstantiationDeclaration) 16596 IsExplicitInstantiationDeclaration = true; 16597 else if (TSK == TSK_ExplicitInstantiationDefinition) { 16598 IsExplicitInstantiationDeclaration = false; 16599 break; 16600 } 16601 } 16602 16603 if (IsExplicitInstantiationDeclaration) 16604 DefineVTable = false; 16605 } 16606 16607 // The exception specifications for all virtual members may be needed even 16608 // if we are not providing an authoritative form of the vtable in this TU. 16609 // We may choose to emit it available_externally anyway. 16610 if (!DefineVTable) { 16611 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 16612 continue; 16613 } 16614 16615 // Mark all of the virtual members of this class as referenced, so 16616 // that we can build a vtable. Then, tell the AST consumer that a 16617 // vtable for this class is required. 16618 DefinedAnything = true; 16619 MarkVirtualMembersReferenced(Loc, Class); 16620 CXXRecordDecl *Canonical = Class->getCanonicalDecl(); 16621 if (VTablesUsed[Canonical]) 16622 Consumer.HandleVTable(Class); 16623 16624 // Warn if we're emitting a weak vtable. The vtable will be weak if there is 16625 // no key function or the key function is inlined. Don't warn in C++ ABIs 16626 // that lack key functions, since the user won't be able to make one. 16627 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() && 16628 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) { 16629 const FunctionDecl *KeyFunctionDef = nullptr; 16630 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) && 16631 KeyFunctionDef->isInlined())) { 16632 Diag(Class->getLocation(), 16633 ClassTSK == TSK_ExplicitInstantiationDefinition 16634 ? diag::warn_weak_template_vtable 16635 : diag::warn_weak_vtable) 16636 << Class; 16637 } 16638 } 16639 } 16640 VTableUses.clear(); 16641 16642 return DefinedAnything; 16643 } 16644 16645 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 16646 const CXXRecordDecl *RD) { 16647 for (const auto *I : RD->methods()) 16648 if (I->isVirtual() && !I->isPure()) 16649 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 16650 } 16651 16652 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 16653 const CXXRecordDecl *RD, 16654 bool ConstexprOnly) { 16655 // Mark all functions which will appear in RD's vtable as used. 16656 CXXFinalOverriderMap FinalOverriders; 16657 RD->getFinalOverriders(FinalOverriders); 16658 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 16659 E = FinalOverriders.end(); 16660 I != E; ++I) { 16661 for (OverridingMethods::const_iterator OI = I->second.begin(), 16662 OE = I->second.end(); 16663 OI != OE; ++OI) { 16664 assert(OI->second.size() > 0 && "no final overrider"); 16665 CXXMethodDecl *Overrider = OI->second.front().Method; 16666 16667 // C++ [basic.def.odr]p2: 16668 // [...] A virtual member function is used if it is not pure. [...] 16669 if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr())) 16670 MarkFunctionReferenced(Loc, Overrider); 16671 } 16672 } 16673 16674 // Only classes that have virtual bases need a VTT. 16675 if (RD->getNumVBases() == 0) 16676 return; 16677 16678 for (const auto &I : RD->bases()) { 16679 const auto *Base = 16680 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 16681 if (Base->getNumVBases() == 0) 16682 continue; 16683 MarkVirtualMembersReferenced(Loc, Base); 16684 } 16685 } 16686 16687 /// SetIvarInitializers - This routine builds initialization ASTs for the 16688 /// Objective-C implementation whose ivars need be initialized. 16689 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 16690 if (!getLangOpts().CPlusPlus) 16691 return; 16692 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 16693 SmallVector<ObjCIvarDecl*, 8> ivars; 16694 CollectIvarsToConstructOrDestruct(OID, ivars); 16695 if (ivars.empty()) 16696 return; 16697 SmallVector<CXXCtorInitializer*, 32> AllToInit; 16698 for (unsigned i = 0; i < ivars.size(); i++) { 16699 FieldDecl *Field = ivars[i]; 16700 if (Field->isInvalidDecl()) 16701 continue; 16702 16703 CXXCtorInitializer *Member; 16704 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 16705 InitializationKind InitKind = 16706 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 16707 16708 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 16709 ExprResult MemberInit = 16710 InitSeq.Perform(*this, InitEntity, InitKind, None); 16711 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 16712 // Note, MemberInit could actually come back empty if no initialization 16713 // is required (e.g., because it would call a trivial default constructor) 16714 if (!MemberInit.get() || MemberInit.isInvalid()) 16715 continue; 16716 16717 Member = 16718 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 16719 SourceLocation(), 16720 MemberInit.getAs<Expr>(), 16721 SourceLocation()); 16722 AllToInit.push_back(Member); 16723 16724 // Be sure that the destructor is accessible and is marked as referenced. 16725 if (const RecordType *RecordTy = 16726 Context.getBaseElementType(Field->getType()) 16727 ->getAs<RecordType>()) { 16728 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 16729 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 16730 MarkFunctionReferenced(Field->getLocation(), Destructor); 16731 CheckDestructorAccess(Field->getLocation(), Destructor, 16732 PDiag(diag::err_access_dtor_ivar) 16733 << Context.getBaseElementType(Field->getType())); 16734 } 16735 } 16736 } 16737 ObjCImplementation->setIvarInitializers(Context, 16738 AllToInit.data(), AllToInit.size()); 16739 } 16740 } 16741 16742 static 16743 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 16744 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid, 16745 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid, 16746 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current, 16747 Sema &S) { 16748 if (Ctor->isInvalidDecl()) 16749 return; 16750 16751 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 16752 16753 // Target may not be determinable yet, for instance if this is a dependent 16754 // call in an uninstantiated template. 16755 if (Target) { 16756 const FunctionDecl *FNTarget = nullptr; 16757 (void)Target->hasBody(FNTarget); 16758 Target = const_cast<CXXConstructorDecl*>( 16759 cast_or_null<CXXConstructorDecl>(FNTarget)); 16760 } 16761 16762 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 16763 // Avoid dereferencing a null pointer here. 16764 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 16765 16766 if (!Current.insert(Canonical).second) 16767 return; 16768 16769 // We know that beyond here, we aren't chaining into a cycle. 16770 if (!Target || !Target->isDelegatingConstructor() || 16771 Target->isInvalidDecl() || Valid.count(TCanonical)) { 16772 Valid.insert(Current.begin(), Current.end()); 16773 Current.clear(); 16774 // We've hit a cycle. 16775 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 16776 Current.count(TCanonical)) { 16777 // If we haven't diagnosed this cycle yet, do so now. 16778 if (!Invalid.count(TCanonical)) { 16779 S.Diag((*Ctor->init_begin())->getSourceLocation(), 16780 diag::warn_delegating_ctor_cycle) 16781 << Ctor; 16782 16783 // Don't add a note for a function delegating directly to itself. 16784 if (TCanonical != Canonical) 16785 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 16786 16787 CXXConstructorDecl *C = Target; 16788 while (C->getCanonicalDecl() != Canonical) { 16789 const FunctionDecl *FNTarget = nullptr; 16790 (void)C->getTargetConstructor()->hasBody(FNTarget); 16791 assert(FNTarget && "Ctor cycle through bodiless function"); 16792 16793 C = const_cast<CXXConstructorDecl*>( 16794 cast<CXXConstructorDecl>(FNTarget)); 16795 S.Diag(C->getLocation(), diag::note_which_delegates_to); 16796 } 16797 } 16798 16799 Invalid.insert(Current.begin(), Current.end()); 16800 Current.clear(); 16801 } else { 16802 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 16803 } 16804 } 16805 16806 16807 void Sema::CheckDelegatingCtorCycles() { 16808 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 16809 16810 for (DelegatingCtorDeclsType::iterator 16811 I = DelegatingCtorDecls.begin(ExternalSource), 16812 E = DelegatingCtorDecls.end(); 16813 I != E; ++I) 16814 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 16815 16816 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI) 16817 (*CI)->setInvalidDecl(); 16818 } 16819 16820 namespace { 16821 /// AST visitor that finds references to the 'this' expression. 16822 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 16823 Sema &S; 16824 16825 public: 16826 explicit FindCXXThisExpr(Sema &S) : S(S) { } 16827 16828 bool VisitCXXThisExpr(CXXThisExpr *E) { 16829 S.Diag(E->getLocation(), diag::err_this_static_member_func) 16830 << E->isImplicit(); 16831 return false; 16832 } 16833 }; 16834 } 16835 16836 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 16837 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 16838 if (!TSInfo) 16839 return false; 16840 16841 TypeLoc TL = TSInfo->getTypeLoc(); 16842 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 16843 if (!ProtoTL) 16844 return false; 16845 16846 // C++11 [expr.prim.general]p3: 16847 // [The expression this] shall not appear before the optional 16848 // cv-qualifier-seq and it shall not appear within the declaration of a 16849 // static member function (although its type and value category are defined 16850 // within a static member function as they are within a non-static member 16851 // function). [ Note: this is because declaration matching does not occur 16852 // until the complete declarator is known. - end note ] 16853 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 16854 FindCXXThisExpr Finder(*this); 16855 16856 // If the return type came after the cv-qualifier-seq, check it now. 16857 if (Proto->hasTrailingReturn() && 16858 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 16859 return true; 16860 16861 // Check the exception specification. 16862 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 16863 return true; 16864 16865 return checkThisInStaticMemberFunctionAttributes(Method); 16866 } 16867 16868 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 16869 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 16870 if (!TSInfo) 16871 return false; 16872 16873 TypeLoc TL = TSInfo->getTypeLoc(); 16874 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 16875 if (!ProtoTL) 16876 return false; 16877 16878 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 16879 FindCXXThisExpr Finder(*this); 16880 16881 switch (Proto->getExceptionSpecType()) { 16882 case EST_Unparsed: 16883 case EST_Uninstantiated: 16884 case EST_Unevaluated: 16885 case EST_BasicNoexcept: 16886 case EST_NoThrow: 16887 case EST_DynamicNone: 16888 case EST_MSAny: 16889 case EST_None: 16890 break; 16891 16892 case EST_DependentNoexcept: 16893 case EST_NoexceptFalse: 16894 case EST_NoexceptTrue: 16895 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 16896 return true; 16897 LLVM_FALLTHROUGH; 16898 16899 case EST_Dynamic: 16900 for (const auto &E : Proto->exceptions()) { 16901 if (!Finder.TraverseType(E)) 16902 return true; 16903 } 16904 break; 16905 } 16906 16907 return false; 16908 } 16909 16910 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 16911 FindCXXThisExpr Finder(*this); 16912 16913 // Check attributes. 16914 for (const auto *A : Method->attrs()) { 16915 // FIXME: This should be emitted by tblgen. 16916 Expr *Arg = nullptr; 16917 ArrayRef<Expr *> Args; 16918 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 16919 Arg = G->getArg(); 16920 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 16921 Arg = G->getArg(); 16922 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 16923 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 16924 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 16925 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 16926 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 16927 Arg = ETLF->getSuccessValue(); 16928 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 16929 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 16930 Arg = STLF->getSuccessValue(); 16931 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 16932 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 16933 Arg = LR->getArg(); 16934 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 16935 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 16936 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 16937 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 16938 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 16939 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 16940 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 16941 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 16942 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 16943 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 16944 16945 if (Arg && !Finder.TraverseStmt(Arg)) 16946 return true; 16947 16948 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 16949 if (!Finder.TraverseStmt(Args[I])) 16950 return true; 16951 } 16952 } 16953 16954 return false; 16955 } 16956 16957 void Sema::checkExceptionSpecification( 16958 bool IsTopLevel, ExceptionSpecificationType EST, 16959 ArrayRef<ParsedType> DynamicExceptions, 16960 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 16961 SmallVectorImpl<QualType> &Exceptions, 16962 FunctionProtoType::ExceptionSpecInfo &ESI) { 16963 Exceptions.clear(); 16964 ESI.Type = EST; 16965 if (EST == EST_Dynamic) { 16966 Exceptions.reserve(DynamicExceptions.size()); 16967 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 16968 // FIXME: Preserve type source info. 16969 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 16970 16971 if (IsTopLevel) { 16972 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 16973 collectUnexpandedParameterPacks(ET, Unexpanded); 16974 if (!Unexpanded.empty()) { 16975 DiagnoseUnexpandedParameterPacks( 16976 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 16977 Unexpanded); 16978 continue; 16979 } 16980 } 16981 16982 // Check that the type is valid for an exception spec, and 16983 // drop it if not. 16984 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 16985 Exceptions.push_back(ET); 16986 } 16987 ESI.Exceptions = Exceptions; 16988 return; 16989 } 16990 16991 if (isComputedNoexcept(EST)) { 16992 assert((NoexceptExpr->isTypeDependent() || 16993 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 16994 Context.BoolTy) && 16995 "Parser should have made sure that the expression is boolean"); 16996 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 16997 ESI.Type = EST_BasicNoexcept; 16998 return; 16999 } 17000 17001 ESI.NoexceptExpr = NoexceptExpr; 17002 return; 17003 } 17004 } 17005 17006 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 17007 ExceptionSpecificationType EST, 17008 SourceRange SpecificationRange, 17009 ArrayRef<ParsedType> DynamicExceptions, 17010 ArrayRef<SourceRange> DynamicExceptionRanges, 17011 Expr *NoexceptExpr) { 17012 if (!MethodD) 17013 return; 17014 17015 // Dig out the method we're referring to. 17016 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 17017 MethodD = FunTmpl->getTemplatedDecl(); 17018 17019 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 17020 if (!Method) 17021 return; 17022 17023 // Check the exception specification. 17024 llvm::SmallVector<QualType, 4> Exceptions; 17025 FunctionProtoType::ExceptionSpecInfo ESI; 17026 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 17027 DynamicExceptionRanges, NoexceptExpr, Exceptions, 17028 ESI); 17029 17030 // Update the exception specification on the function type. 17031 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 17032 17033 if (Method->isStatic()) 17034 checkThisInStaticMemberFunctionExceptionSpec(Method); 17035 17036 if (Method->isVirtual()) { 17037 // Check overrides, which we previously had to delay. 17038 for (const CXXMethodDecl *O : Method->overridden_methods()) 17039 CheckOverridingFunctionExceptionSpec(Method, O); 17040 } 17041 } 17042 17043 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 17044 /// 17045 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 17046 SourceLocation DeclStart, Declarator &D, 17047 Expr *BitWidth, 17048 InClassInitStyle InitStyle, 17049 AccessSpecifier AS, 17050 const ParsedAttr &MSPropertyAttr) { 17051 IdentifierInfo *II = D.getIdentifier(); 17052 if (!II) { 17053 Diag(DeclStart, diag::err_anonymous_property); 17054 return nullptr; 17055 } 17056 SourceLocation Loc = D.getIdentifierLoc(); 17057 17058 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 17059 QualType T = TInfo->getType(); 17060 if (getLangOpts().CPlusPlus) { 17061 CheckExtraCXXDefaultArguments(D); 17062 17063 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 17064 UPPC_DataMemberType)) { 17065 D.setInvalidType(); 17066 T = Context.IntTy; 17067 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 17068 } 17069 } 17070 17071 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 17072 17073 if (D.getDeclSpec().isInlineSpecified()) 17074 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 17075 << getLangOpts().CPlusPlus17; 17076 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 17077 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 17078 diag::err_invalid_thread) 17079 << DeclSpec::getSpecifierName(TSCS); 17080 17081 // Check to see if this name was declared as a member previously 17082 NamedDecl *PrevDecl = nullptr; 17083 LookupResult Previous(*this, II, Loc, LookupMemberName, 17084 ForVisibleRedeclaration); 17085 LookupName(Previous, S); 17086 switch (Previous.getResultKind()) { 17087 case LookupResult::Found: 17088 case LookupResult::FoundUnresolvedValue: 17089 PrevDecl = Previous.getAsSingle<NamedDecl>(); 17090 break; 17091 17092 case LookupResult::FoundOverloaded: 17093 PrevDecl = Previous.getRepresentativeDecl(); 17094 break; 17095 17096 case LookupResult::NotFound: 17097 case LookupResult::NotFoundInCurrentInstantiation: 17098 case LookupResult::Ambiguous: 17099 break; 17100 } 17101 17102 if (PrevDecl && PrevDecl->isTemplateParameter()) { 17103 // Maybe we will complain about the shadowed template parameter. 17104 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 17105 // Just pretend that we didn't see the previous declaration. 17106 PrevDecl = nullptr; 17107 } 17108 17109 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 17110 PrevDecl = nullptr; 17111 17112 SourceLocation TSSL = D.getBeginLoc(); 17113 MSPropertyDecl *NewPD = 17114 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL, 17115 MSPropertyAttr.getPropertyDataGetter(), 17116 MSPropertyAttr.getPropertyDataSetter()); 17117 ProcessDeclAttributes(TUScope, NewPD, D); 17118 NewPD->setAccess(AS); 17119 17120 if (NewPD->isInvalidDecl()) 17121 Record->setInvalidDecl(); 17122 17123 if (D.getDeclSpec().isModulePrivateSpecified()) 17124 NewPD->setModulePrivate(); 17125 17126 if (NewPD->isInvalidDecl() && PrevDecl) { 17127 // Don't introduce NewFD into scope; there's already something 17128 // with the same name in the same scope. 17129 } else if (II) { 17130 PushOnScopeChains(NewPD, S); 17131 } else 17132 Record->addDecl(NewPD); 17133 17134 return NewPD; 17135 } 17136