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 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 779 QualType R = TInfo->getType(); 780 781 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 782 UPPC_DeclarationType)) 783 D.setInvalidType(); 784 785 // The syntax only allows a single ref-qualifier prior to the decomposition 786 // declarator. No other declarator chunks are permitted. Also check the type 787 // specifier here. 788 if (DS.getTypeSpecType() != DeclSpec::TST_auto || 789 D.hasGroupingParens() || D.getNumTypeObjects() > 1 || 790 (D.getNumTypeObjects() == 1 && 791 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) { 792 Diag(Decomp.getLSquareLoc(), 793 (D.hasGroupingParens() || 794 (D.getNumTypeObjects() && 795 D.getTypeObject(0).Kind == DeclaratorChunk::Paren)) 796 ? diag::err_decomp_decl_parens 797 : diag::err_decomp_decl_type) 798 << R; 799 800 // In most cases, there's no actual problem with an explicitly-specified 801 // type, but a function type won't work here, and ActOnVariableDeclarator 802 // shouldn't be called for such a type. 803 if (R->isFunctionType()) 804 D.setInvalidType(); 805 } 806 807 // Build the BindingDecls. 808 SmallVector<BindingDecl*, 8> Bindings; 809 810 // Build the BindingDecls. 811 for (auto &B : D.getDecompositionDeclarator().bindings()) { 812 // Check for name conflicts. 813 DeclarationNameInfo NameInfo(B.Name, B.NameLoc); 814 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 815 ForVisibleRedeclaration); 816 LookupName(Previous, S, 817 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit()); 818 819 // It's not permitted to shadow a template parameter name. 820 if (Previous.isSingleResult() && 821 Previous.getFoundDecl()->isTemplateParameter()) { 822 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 823 Previous.getFoundDecl()); 824 Previous.clear(); 825 } 826 827 bool ConsiderLinkage = DC->isFunctionOrMethod() && 828 DS.getStorageClassSpec() == DeclSpec::SCS_extern; 829 FilterLookupForScope(Previous, DC, S, ConsiderLinkage, 830 /*AllowInlineNamespace*/false); 831 if (!Previous.empty()) { 832 auto *Old = Previous.getRepresentativeDecl(); 833 Diag(B.NameLoc, diag::err_redefinition) << B.Name; 834 Diag(Old->getLocation(), diag::note_previous_definition); 835 } 836 837 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name); 838 PushOnScopeChains(BD, S, true); 839 Bindings.push_back(BD); 840 ParsingInitForAutoVars.insert(BD); 841 } 842 843 // There are no prior lookup results for the variable itself, because it 844 // is unnamed. 845 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr, 846 Decomp.getLSquareLoc()); 847 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 848 ForVisibleRedeclaration); 849 850 // Build the variable that holds the non-decomposed object. 851 bool AddToScope = true; 852 NamedDecl *New = 853 ActOnVariableDeclarator(S, D, DC, TInfo, Previous, 854 MultiTemplateParamsArg(), AddToScope, Bindings); 855 if (AddToScope) { 856 S->AddDecl(New); 857 CurContext->addHiddenDecl(New); 858 } 859 860 if (isInOpenMPDeclareTargetContext()) 861 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 862 863 return New; 864 } 865 866 static bool checkSimpleDecomposition( 867 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src, 868 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType, 869 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) { 870 if ((int64_t)Bindings.size() != NumElems) { 871 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 872 << DecompType << (unsigned)Bindings.size() << NumElems.toString(10) 873 << (NumElems < Bindings.size()); 874 return true; 875 } 876 877 unsigned I = 0; 878 for (auto *B : Bindings) { 879 SourceLocation Loc = B->getLocation(); 880 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 881 if (E.isInvalid()) 882 return true; 883 E = GetInit(Loc, E.get(), I++); 884 if (E.isInvalid()) 885 return true; 886 B->setBinding(ElemType, E.get()); 887 } 888 889 return false; 890 } 891 892 static bool checkArrayLikeDecomposition(Sema &S, 893 ArrayRef<BindingDecl *> Bindings, 894 ValueDecl *Src, QualType DecompType, 895 const llvm::APSInt &NumElems, 896 QualType ElemType) { 897 return checkSimpleDecomposition( 898 S, Bindings, Src, DecompType, NumElems, ElemType, 899 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 900 ExprResult E = S.ActOnIntegerConstant(Loc, I); 901 if (E.isInvalid()) 902 return ExprError(); 903 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc); 904 }); 905 } 906 907 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 908 ValueDecl *Src, QualType DecompType, 909 const ConstantArrayType *CAT) { 910 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType, 911 llvm::APSInt(CAT->getSize()), 912 CAT->getElementType()); 913 } 914 915 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 916 ValueDecl *Src, QualType DecompType, 917 const VectorType *VT) { 918 return checkArrayLikeDecomposition( 919 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()), 920 S.Context.getQualifiedType(VT->getElementType(), 921 DecompType.getQualifiers())); 922 } 923 924 static bool checkComplexDecomposition(Sema &S, 925 ArrayRef<BindingDecl *> Bindings, 926 ValueDecl *Src, QualType DecompType, 927 const ComplexType *CT) { 928 return checkSimpleDecomposition( 929 S, Bindings, Src, DecompType, llvm::APSInt::get(2), 930 S.Context.getQualifiedType(CT->getElementType(), 931 DecompType.getQualifiers()), 932 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult { 933 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base); 934 }); 935 } 936 937 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy, 938 TemplateArgumentListInfo &Args) { 939 SmallString<128> SS; 940 llvm::raw_svector_ostream OS(SS); 941 bool First = true; 942 for (auto &Arg : Args.arguments()) { 943 if (!First) 944 OS << ", "; 945 Arg.getArgument().print(PrintingPolicy, OS); 946 First = false; 947 } 948 return OS.str(); 949 } 950 951 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup, 952 SourceLocation Loc, StringRef Trait, 953 TemplateArgumentListInfo &Args, 954 unsigned DiagID) { 955 auto DiagnoseMissing = [&] { 956 if (DiagID) 957 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(), 958 Args); 959 return true; 960 }; 961 962 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine. 963 NamespaceDecl *Std = S.getStdNamespace(); 964 if (!Std) 965 return DiagnoseMissing(); 966 967 // Look up the trait itself, within namespace std. We can diagnose various 968 // problems with this lookup even if we've been asked to not diagnose a 969 // missing specialization, because this can only fail if the user has been 970 // declaring their own names in namespace std or we don't support the 971 // standard library implementation in use. 972 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait), 973 Loc, Sema::LookupOrdinaryName); 974 if (!S.LookupQualifiedName(Result, Std)) 975 return DiagnoseMissing(); 976 if (Result.isAmbiguous()) 977 return true; 978 979 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>(); 980 if (!TraitTD) { 981 Result.suppressDiagnostics(); 982 NamedDecl *Found = *Result.begin(); 983 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait; 984 S.Diag(Found->getLocation(), diag::note_declared_at); 985 return true; 986 } 987 988 // Build the template-id. 989 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args); 990 if (TraitTy.isNull()) 991 return true; 992 if (!S.isCompleteType(Loc, TraitTy)) { 993 if (DiagID) 994 S.RequireCompleteType( 995 Loc, TraitTy, DiagID, 996 printTemplateArgs(S.Context.getPrintingPolicy(), Args)); 997 return true; 998 } 999 1000 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl(); 1001 assert(RD && "specialization of class template is not a class?"); 1002 1003 // Look up the member of the trait type. 1004 S.LookupQualifiedName(TraitMemberLookup, RD); 1005 return TraitMemberLookup.isAmbiguous(); 1006 } 1007 1008 static TemplateArgumentLoc 1009 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T, 1010 uint64_t I) { 1011 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T); 1012 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc); 1013 } 1014 1015 static TemplateArgumentLoc 1016 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) { 1017 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc); 1018 } 1019 1020 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; } 1021 1022 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T, 1023 llvm::APSInt &Size) { 1024 EnterExpressionEvaluationContext ContextRAII( 1025 S, Sema::ExpressionEvaluationContext::ConstantEvaluated); 1026 1027 DeclarationName Value = S.PP.getIdentifierInfo("value"); 1028 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName); 1029 1030 // Form template argument list for tuple_size<T>. 1031 TemplateArgumentListInfo Args(Loc, Loc); 1032 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1033 1034 // If there's no tuple_size specialization or the lookup of 'value' is empty, 1035 // it's not tuple-like. 1036 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) || 1037 R.empty()) 1038 return IsTupleLike::NotTupleLike; 1039 1040 // If we get this far, we've committed to the tuple interpretation, but 1041 // we can still fail if there actually isn't a usable ::value. 1042 1043 struct ICEDiagnoser : Sema::VerifyICEDiagnoser { 1044 LookupResult &R; 1045 TemplateArgumentListInfo &Args; 1046 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args) 1047 : R(R), Args(Args) {} 1048 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) { 1049 S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant) 1050 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1051 } 1052 } Diagnoser(R, Args); 1053 1054 ExprResult E = 1055 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false); 1056 if (E.isInvalid()) 1057 return IsTupleLike::Error; 1058 1059 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false); 1060 if (E.isInvalid()) 1061 return IsTupleLike::Error; 1062 1063 return IsTupleLike::TupleLike; 1064 } 1065 1066 /// \return std::tuple_element<I, T>::type. 1067 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc, 1068 unsigned I, QualType T) { 1069 // Form template argument list for tuple_element<I, T>. 1070 TemplateArgumentListInfo Args(Loc, Loc); 1071 Args.addArgument( 1072 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1073 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T)); 1074 1075 DeclarationName TypeDN = S.PP.getIdentifierInfo("type"); 1076 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName); 1077 if (lookupStdTypeTraitMember( 1078 S, R, Loc, "tuple_element", Args, 1079 diag::err_decomp_decl_std_tuple_element_not_specialized)) 1080 return QualType(); 1081 1082 auto *TD = R.getAsSingle<TypeDecl>(); 1083 if (!TD) { 1084 R.suppressDiagnostics(); 1085 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized) 1086 << printTemplateArgs(S.Context.getPrintingPolicy(), Args); 1087 if (!R.empty()) 1088 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at); 1089 return QualType(); 1090 } 1091 1092 return S.Context.getTypeDeclType(TD); 1093 } 1094 1095 namespace { 1096 struct BindingDiagnosticTrap { 1097 Sema &S; 1098 DiagnosticErrorTrap Trap; 1099 BindingDecl *BD; 1100 1101 BindingDiagnosticTrap(Sema &S, BindingDecl *BD) 1102 : S(S), Trap(S.Diags), BD(BD) {} 1103 ~BindingDiagnosticTrap() { 1104 if (Trap.hasErrorOccurred()) 1105 S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD; 1106 } 1107 }; 1108 } 1109 1110 static bool checkTupleLikeDecomposition(Sema &S, 1111 ArrayRef<BindingDecl *> Bindings, 1112 VarDecl *Src, QualType DecompType, 1113 const llvm::APSInt &TupleSize) { 1114 if ((int64_t)Bindings.size() != TupleSize) { 1115 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1116 << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10) 1117 << (TupleSize < Bindings.size()); 1118 return true; 1119 } 1120 1121 if (Bindings.empty()) 1122 return false; 1123 1124 DeclarationName GetDN = S.PP.getIdentifierInfo("get"); 1125 1126 // [dcl.decomp]p3: 1127 // The unqualified-id get is looked up in the scope of E by class member 1128 // access lookup ... 1129 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName); 1130 bool UseMemberGet = false; 1131 if (S.isCompleteType(Src->getLocation(), DecompType)) { 1132 if (auto *RD = DecompType->getAsCXXRecordDecl()) 1133 S.LookupQualifiedName(MemberGet, RD); 1134 if (MemberGet.isAmbiguous()) 1135 return true; 1136 // ... and if that finds at least one declaration that is a function 1137 // template whose first template parameter is a non-type parameter ... 1138 for (NamedDecl *D : MemberGet) { 1139 if (FunctionTemplateDecl *FTD = 1140 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) { 1141 TemplateParameterList *TPL = FTD->getTemplateParameters(); 1142 if (TPL->size() != 0 && 1143 isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) { 1144 // ... the initializer is e.get<i>(). 1145 UseMemberGet = true; 1146 break; 1147 } 1148 } 1149 } 1150 } 1151 1152 unsigned I = 0; 1153 for (auto *B : Bindings) { 1154 BindingDiagnosticTrap Trap(S, B); 1155 SourceLocation Loc = B->getLocation(); 1156 1157 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1158 if (E.isInvalid()) 1159 return true; 1160 1161 // e is an lvalue if the type of the entity is an lvalue reference and 1162 // an xvalue otherwise 1163 if (!Src->getType()->isLValueReferenceType()) 1164 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp, 1165 E.get(), nullptr, VK_XValue); 1166 1167 TemplateArgumentListInfo Args(Loc, Loc); 1168 Args.addArgument( 1169 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I)); 1170 1171 if (UseMemberGet) { 1172 // if [lookup of member get] finds at least one declaration, the 1173 // initializer is e.get<i-1>(). 1174 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false, 1175 CXXScopeSpec(), SourceLocation(), nullptr, 1176 MemberGet, &Args, nullptr); 1177 if (E.isInvalid()) 1178 return true; 1179 1180 E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc); 1181 } else { 1182 // Otherwise, the initializer is get<i-1>(e), where get is looked up 1183 // in the associated namespaces. 1184 Expr *Get = UnresolvedLookupExpr::Create( 1185 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(), 1186 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args, 1187 UnresolvedSetIterator(), UnresolvedSetIterator()); 1188 1189 Expr *Arg = E.get(); 1190 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc); 1191 } 1192 if (E.isInvalid()) 1193 return true; 1194 Expr *Init = E.get(); 1195 1196 // Given the type T designated by std::tuple_element<i - 1, E>::type, 1197 QualType T = getTupleLikeElementType(S, Loc, I, DecompType); 1198 if (T.isNull()) 1199 return true; 1200 1201 // each vi is a variable of type "reference to T" initialized with the 1202 // initializer, where the reference is an lvalue reference if the 1203 // initializer is an lvalue and an rvalue reference otherwise 1204 QualType RefType = 1205 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName()); 1206 if (RefType.isNull()) 1207 return true; 1208 auto *RefVD = VarDecl::Create( 1209 S.Context, Src->getDeclContext(), Loc, Loc, 1210 B->getDeclName().getAsIdentifierInfo(), RefType, 1211 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass()); 1212 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext()); 1213 RefVD->setTSCSpec(Src->getTSCSpec()); 1214 RefVD->setImplicit(); 1215 if (Src->isInlineSpecified()) 1216 RefVD->setInlineSpecified(); 1217 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD); 1218 1219 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD); 1220 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc); 1221 InitializationSequence Seq(S, Entity, Kind, Init); 1222 E = Seq.Perform(S, Entity, Kind, Init); 1223 if (E.isInvalid()) 1224 return true; 1225 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false); 1226 if (E.isInvalid()) 1227 return true; 1228 RefVD->setInit(E.get()); 1229 if (!E.get()->isValueDependent()) 1230 RefVD->checkInitIsICE(); 1231 1232 E = S.BuildDeclarationNameExpr(CXXScopeSpec(), 1233 DeclarationNameInfo(B->getDeclName(), Loc), 1234 RefVD); 1235 if (E.isInvalid()) 1236 return true; 1237 1238 B->setBinding(T, E.get()); 1239 I++; 1240 } 1241 1242 return false; 1243 } 1244 1245 /// Find the base class to decompose in a built-in decomposition of a class type. 1246 /// This base class search is, unfortunately, not quite like any other that we 1247 /// perform anywhere else in C++. 1248 static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc, 1249 const CXXRecordDecl *RD, 1250 CXXCastPath &BasePath) { 1251 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier, 1252 CXXBasePath &Path) { 1253 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields(); 1254 }; 1255 1256 const CXXRecordDecl *ClassWithFields = nullptr; 1257 AccessSpecifier AS = AS_public; 1258 if (RD->hasDirectFields()) 1259 // [dcl.decomp]p4: 1260 // Otherwise, all of E's non-static data members shall be public direct 1261 // members of E ... 1262 ClassWithFields = RD; 1263 else { 1264 // ... or of ... 1265 CXXBasePaths Paths; 1266 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD)); 1267 if (!RD->lookupInBases(BaseHasFields, Paths)) { 1268 // If no classes have fields, just decompose RD itself. (This will work 1269 // if and only if zero bindings were provided.) 1270 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public); 1271 } 1272 1273 CXXBasePath *BestPath = nullptr; 1274 for (auto &P : Paths) { 1275 if (!BestPath) 1276 BestPath = &P; 1277 else if (!S.Context.hasSameType(P.back().Base->getType(), 1278 BestPath->back().Base->getType())) { 1279 // ... the same ... 1280 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1281 << false << RD << BestPath->back().Base->getType() 1282 << P.back().Base->getType(); 1283 return DeclAccessPair(); 1284 } else if (P.Access < BestPath->Access) { 1285 BestPath = &P; 1286 } 1287 } 1288 1289 // ... unambiguous ... 1290 QualType BaseType = BestPath->back().Base->getType(); 1291 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) { 1292 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base) 1293 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths); 1294 return DeclAccessPair(); 1295 } 1296 1297 // ... [accessible, implied by other rules] base class of E. 1298 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD), 1299 *BestPath, diag::err_decomp_decl_inaccessible_base); 1300 AS = BestPath->Access; 1301 1302 ClassWithFields = BaseType->getAsCXXRecordDecl(); 1303 S.BuildBasePathArray(Paths, BasePath); 1304 } 1305 1306 // The above search did not check whether the selected class itself has base 1307 // classes with fields, so check that now. 1308 CXXBasePaths Paths; 1309 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) { 1310 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members) 1311 << (ClassWithFields == RD) << RD << ClassWithFields 1312 << Paths.front().back().Base->getType(); 1313 return DeclAccessPair(); 1314 } 1315 1316 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS); 1317 } 1318 1319 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings, 1320 ValueDecl *Src, QualType DecompType, 1321 const CXXRecordDecl *OrigRD) { 1322 if (S.RequireCompleteType(Src->getLocation(), DecompType, 1323 diag::err_incomplete_type)) 1324 return true; 1325 1326 CXXCastPath BasePath; 1327 DeclAccessPair BasePair = 1328 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath); 1329 const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl()); 1330 if (!RD) 1331 return true; 1332 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD), 1333 DecompType.getQualifiers()); 1334 1335 auto DiagnoseBadNumberOfBindings = [&]() -> bool { 1336 unsigned NumFields = 1337 std::count_if(RD->field_begin(), RD->field_end(), 1338 [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); }); 1339 assert(Bindings.size() != NumFields); 1340 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings) 1341 << DecompType << (unsigned)Bindings.size() << NumFields 1342 << (NumFields < Bindings.size()); 1343 return true; 1344 }; 1345 1346 // all of E's non-static data members shall be [...] well-formed 1347 // when named as e.name in the context of the structured binding, 1348 // E shall not have an anonymous union member, ... 1349 unsigned I = 0; 1350 for (auto *FD : RD->fields()) { 1351 if (FD->isUnnamedBitfield()) 1352 continue; 1353 1354 if (FD->isAnonymousStructOrUnion()) { 1355 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member) 1356 << DecompType << FD->getType()->isUnionType(); 1357 S.Diag(FD->getLocation(), diag::note_declared_at); 1358 return true; 1359 } 1360 1361 // We have a real field to bind. 1362 if (I >= Bindings.size()) 1363 return DiagnoseBadNumberOfBindings(); 1364 auto *B = Bindings[I++]; 1365 SourceLocation Loc = B->getLocation(); 1366 1367 // The field must be accessible in the context of the structured binding. 1368 // We already checked that the base class is accessible. 1369 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the 1370 // const_cast here. 1371 S.CheckStructuredBindingMemberAccess( 1372 Loc, const_cast<CXXRecordDecl *>(OrigRD), 1373 DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess( 1374 BasePair.getAccess(), FD->getAccess()))); 1375 1376 // Initialize the binding to Src.FD. 1377 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc); 1378 if (E.isInvalid()) 1379 return true; 1380 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase, 1381 VK_LValue, &BasePath); 1382 if (E.isInvalid()) 1383 return true; 1384 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc, 1385 CXXScopeSpec(), FD, 1386 DeclAccessPair::make(FD, FD->getAccess()), 1387 DeclarationNameInfo(FD->getDeclName(), Loc)); 1388 if (E.isInvalid()) 1389 return true; 1390 1391 // If the type of the member is T, the referenced type is cv T, where cv is 1392 // the cv-qualification of the decomposition expression. 1393 // 1394 // FIXME: We resolve a defect here: if the field is mutable, we do not add 1395 // 'const' to the type of the field. 1396 Qualifiers Q = DecompType.getQualifiers(); 1397 if (FD->isMutable()) 1398 Q.removeConst(); 1399 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get()); 1400 } 1401 1402 if (I != Bindings.size()) 1403 return DiagnoseBadNumberOfBindings(); 1404 1405 return false; 1406 } 1407 1408 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) { 1409 QualType DecompType = DD->getType(); 1410 1411 // If the type of the decomposition is dependent, then so is the type of 1412 // each binding. 1413 if (DecompType->isDependentType()) { 1414 for (auto *B : DD->bindings()) 1415 B->setType(Context.DependentTy); 1416 return; 1417 } 1418 1419 DecompType = DecompType.getNonReferenceType(); 1420 ArrayRef<BindingDecl*> Bindings = DD->bindings(); 1421 1422 // C++1z [dcl.decomp]/2: 1423 // If E is an array type [...] 1424 // As an extension, we also support decomposition of built-in complex and 1425 // vector types. 1426 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) { 1427 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT)) 1428 DD->setInvalidDecl(); 1429 return; 1430 } 1431 if (auto *VT = DecompType->getAs<VectorType>()) { 1432 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT)) 1433 DD->setInvalidDecl(); 1434 return; 1435 } 1436 if (auto *CT = DecompType->getAs<ComplexType>()) { 1437 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT)) 1438 DD->setInvalidDecl(); 1439 return; 1440 } 1441 1442 // C++1z [dcl.decomp]/3: 1443 // if the expression std::tuple_size<E>::value is a well-formed integral 1444 // constant expression, [...] 1445 llvm::APSInt TupleSize(32); 1446 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) { 1447 case IsTupleLike::Error: 1448 DD->setInvalidDecl(); 1449 return; 1450 1451 case IsTupleLike::TupleLike: 1452 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize)) 1453 DD->setInvalidDecl(); 1454 return; 1455 1456 case IsTupleLike::NotTupleLike: 1457 break; 1458 } 1459 1460 // C++1z [dcl.dcl]/8: 1461 // [E shall be of array or non-union class type] 1462 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl(); 1463 if (!RD || RD->isUnion()) { 1464 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type) 1465 << DD << !RD << DecompType; 1466 DD->setInvalidDecl(); 1467 return; 1468 } 1469 1470 // C++1z [dcl.decomp]/4: 1471 // all of E's non-static data members shall be [...] direct members of 1472 // E or of the same unambiguous public base class of E, ... 1473 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD)) 1474 DD->setInvalidDecl(); 1475 } 1476 1477 /// Merge the exception specifications of two variable declarations. 1478 /// 1479 /// This is called when there's a redeclaration of a VarDecl. The function 1480 /// checks if the redeclaration might have an exception specification and 1481 /// validates compatibility and merges the specs if necessary. 1482 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) { 1483 // Shortcut if exceptions are disabled. 1484 if (!getLangOpts().CXXExceptions) 1485 return; 1486 1487 assert(Context.hasSameType(New->getType(), Old->getType()) && 1488 "Should only be called if types are otherwise the same."); 1489 1490 QualType NewType = New->getType(); 1491 QualType OldType = Old->getType(); 1492 1493 // We're only interested in pointers and references to functions, as well 1494 // as pointers to member functions. 1495 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) { 1496 NewType = R->getPointeeType(); 1497 OldType = OldType->getAs<ReferenceType>()->getPointeeType(); 1498 } else if (const PointerType *P = NewType->getAs<PointerType>()) { 1499 NewType = P->getPointeeType(); 1500 OldType = OldType->getAs<PointerType>()->getPointeeType(); 1501 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) { 1502 NewType = M->getPointeeType(); 1503 OldType = OldType->getAs<MemberPointerType>()->getPointeeType(); 1504 } 1505 1506 if (!NewType->isFunctionProtoType()) 1507 return; 1508 1509 // There's lots of special cases for functions. For function pointers, system 1510 // libraries are hopefully not as broken so that we don't need these 1511 // workarounds. 1512 if (CheckEquivalentExceptionSpec( 1513 OldType->getAs<FunctionProtoType>(), Old->getLocation(), 1514 NewType->getAs<FunctionProtoType>(), New->getLocation())) { 1515 New->setInvalidDecl(); 1516 } 1517 } 1518 1519 /// CheckCXXDefaultArguments - Verify that the default arguments for a 1520 /// function declaration are well-formed according to C++ 1521 /// [dcl.fct.default]. 1522 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) { 1523 unsigned NumParams = FD->getNumParams(); 1524 unsigned p; 1525 1526 // Find first parameter with a default argument 1527 for (p = 0; p < NumParams; ++p) { 1528 ParmVarDecl *Param = FD->getParamDecl(p); 1529 if (Param->hasDefaultArg()) 1530 break; 1531 } 1532 1533 // C++11 [dcl.fct.default]p4: 1534 // In a given function declaration, each parameter subsequent to a parameter 1535 // with a default argument shall have a default argument supplied in this or 1536 // a previous declaration or shall be a function parameter pack. A default 1537 // argument shall not be redefined by a later declaration (not even to the 1538 // same value). 1539 unsigned LastMissingDefaultArg = 0; 1540 for (; p < NumParams; ++p) { 1541 ParmVarDecl *Param = FD->getParamDecl(p); 1542 if (!Param->hasDefaultArg() && !Param->isParameterPack()) { 1543 if (Param->isInvalidDecl()) 1544 /* We already complained about this parameter. */; 1545 else if (Param->getIdentifier()) 1546 Diag(Param->getLocation(), 1547 diag::err_param_default_argument_missing_name) 1548 << Param->getIdentifier(); 1549 else 1550 Diag(Param->getLocation(), 1551 diag::err_param_default_argument_missing); 1552 1553 LastMissingDefaultArg = p; 1554 } 1555 } 1556 1557 if (LastMissingDefaultArg > 0) { 1558 // Some default arguments were missing. Clear out all of the 1559 // default arguments up to (and including) the last missing 1560 // default argument, so that we leave the function parameters 1561 // in a semantically valid state. 1562 for (p = 0; p <= LastMissingDefaultArg; ++p) { 1563 ParmVarDecl *Param = FD->getParamDecl(p); 1564 if (Param->hasDefaultArg()) { 1565 Param->setDefaultArg(nullptr); 1566 } 1567 } 1568 } 1569 } 1570 1571 /// Check that the given type is a literal type. Issue a diagnostic if not, 1572 /// if Kind is Diagnose. 1573 /// \return \c true if a problem has been found (and optionally diagnosed). 1574 template <typename... Ts> 1575 static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind, 1576 SourceLocation Loc, QualType T, unsigned DiagID, 1577 Ts &&...DiagArgs) { 1578 if (T->isDependentType()) 1579 return false; 1580 1581 switch (Kind) { 1582 case Sema::CheckConstexprKind::Diagnose: 1583 return SemaRef.RequireLiteralType(Loc, T, DiagID, 1584 std::forward<Ts>(DiagArgs)...); 1585 1586 case Sema::CheckConstexprKind::CheckValid: 1587 return !T->isLiteralType(SemaRef.Context); 1588 } 1589 1590 llvm_unreachable("unknown CheckConstexprKind"); 1591 } 1592 1593 /// Determine whether a destructor cannot be constexpr due to 1594 static bool CheckConstexprDestructorSubobjects(Sema &SemaRef, 1595 const CXXDestructorDecl *DD, 1596 Sema::CheckConstexprKind Kind) { 1597 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) { 1598 const CXXRecordDecl *RD = 1599 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 1600 if (!RD || RD->hasConstexprDestructor()) 1601 return true; 1602 1603 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1604 SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject) 1605 << DD->getConstexprKind() << !FD 1606 << (FD ? FD->getDeclName() : DeclarationName()) << T; 1607 SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject) 1608 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T; 1609 } 1610 return false; 1611 }; 1612 1613 const CXXRecordDecl *RD = DD->getParent(); 1614 for (const CXXBaseSpecifier &B : RD->bases()) 1615 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr)) 1616 return false; 1617 for (const FieldDecl *FD : RD->fields()) 1618 if (!Check(FD->getLocation(), FD->getType(), FD)) 1619 return false; 1620 return true; 1621 } 1622 1623 // CheckConstexprParameterTypes - Check whether a function's parameter types 1624 // are all literal types. If so, return true. If not, produce a suitable 1625 // diagnostic and return false. 1626 static bool CheckConstexprParameterTypes(Sema &SemaRef, 1627 const FunctionDecl *FD, 1628 Sema::CheckConstexprKind Kind) { 1629 unsigned ArgIndex = 0; 1630 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>(); 1631 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(), 1632 e = FT->param_type_end(); 1633 i != e; ++i, ++ArgIndex) { 1634 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex); 1635 SourceLocation ParamLoc = PD->getLocation(); 1636 if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i, 1637 diag::err_constexpr_non_literal_param, ArgIndex + 1, 1638 PD->getSourceRange(), isa<CXXConstructorDecl>(FD), 1639 FD->isConsteval())) 1640 return false; 1641 } 1642 return true; 1643 } 1644 1645 /// Get diagnostic %select index for tag kind for 1646 /// record diagnostic message. 1647 /// WARNING: Indexes apply to particular diagnostics only! 1648 /// 1649 /// \returns diagnostic %select index. 1650 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) { 1651 switch (Tag) { 1652 case TTK_Struct: return 0; 1653 case TTK_Interface: return 1; 1654 case TTK_Class: return 2; 1655 default: llvm_unreachable("Invalid tag kind for record diagnostic!"); 1656 } 1657 } 1658 1659 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, 1660 Stmt *Body, 1661 Sema::CheckConstexprKind Kind); 1662 1663 // Check whether a function declaration satisfies the requirements of a 1664 // constexpr function definition or a constexpr constructor definition. If so, 1665 // return true. If not, produce appropriate diagnostics (unless asked not to by 1666 // Kind) and return false. 1667 // 1668 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360. 1669 bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD, 1670 CheckConstexprKind Kind) { 1671 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 1672 if (MD && MD->isInstance()) { 1673 // C++11 [dcl.constexpr]p4: 1674 // The definition of a constexpr constructor shall satisfy the following 1675 // constraints: 1676 // - the class shall not have any virtual base classes; 1677 // 1678 // FIXME: This only applies to constructors and destructors, not arbitrary 1679 // member functions. 1680 const CXXRecordDecl *RD = MD->getParent(); 1681 if (RD->getNumVBases()) { 1682 if (Kind == CheckConstexprKind::CheckValid) 1683 return false; 1684 1685 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base) 1686 << isa<CXXConstructorDecl>(NewFD) 1687 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases(); 1688 for (const auto &I : RD->vbases()) 1689 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here) 1690 << I.getSourceRange(); 1691 return false; 1692 } 1693 } 1694 1695 if (!isa<CXXConstructorDecl>(NewFD)) { 1696 // C++11 [dcl.constexpr]p3: 1697 // The definition of a constexpr function shall satisfy the following 1698 // constraints: 1699 // - it shall not be virtual; (removed in C++20) 1700 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD); 1701 if (Method && Method->isVirtual()) { 1702 if (getLangOpts().CPlusPlus2a) { 1703 if (Kind == CheckConstexprKind::Diagnose) 1704 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual); 1705 } else { 1706 if (Kind == CheckConstexprKind::CheckValid) 1707 return false; 1708 1709 Method = Method->getCanonicalDecl(); 1710 Diag(Method->getLocation(), diag::err_constexpr_virtual); 1711 1712 // If it's not obvious why this function is virtual, find an overridden 1713 // function which uses the 'virtual' keyword. 1714 const CXXMethodDecl *WrittenVirtual = Method; 1715 while (!WrittenVirtual->isVirtualAsWritten()) 1716 WrittenVirtual = *WrittenVirtual->begin_overridden_methods(); 1717 if (WrittenVirtual != Method) 1718 Diag(WrittenVirtual->getLocation(), 1719 diag::note_overridden_virtual_function); 1720 return false; 1721 } 1722 } 1723 1724 // - its return type shall be a literal type; 1725 QualType RT = NewFD->getReturnType(); 1726 if (CheckLiteralType(*this, Kind, NewFD->getLocation(), RT, 1727 diag::err_constexpr_non_literal_return, 1728 NewFD->isConsteval())) 1729 return false; 1730 } 1731 1732 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) { 1733 // A destructor can be constexpr only if the defaulted destructor could be; 1734 // we don't need to check the members and bases if we already know they all 1735 // have constexpr destructors. 1736 if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) { 1737 if (Kind == CheckConstexprKind::CheckValid) 1738 return false; 1739 if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind)) 1740 return false; 1741 } 1742 } 1743 1744 // - each of its parameter types shall be a literal type; 1745 if (!CheckConstexprParameterTypes(*this, NewFD, Kind)) 1746 return false; 1747 1748 Stmt *Body = NewFD->getBody(); 1749 assert(Body && 1750 "CheckConstexprFunctionDefinition called on function with no body"); 1751 return CheckConstexprFunctionBody(*this, NewFD, Body, Kind); 1752 } 1753 1754 /// Check the given declaration statement is legal within a constexpr function 1755 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3. 1756 /// 1757 /// \return true if the body is OK (maybe only as an extension), false if we 1758 /// have diagnosed a problem. 1759 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl, 1760 DeclStmt *DS, SourceLocation &Cxx1yLoc, 1761 Sema::CheckConstexprKind Kind) { 1762 // C++11 [dcl.constexpr]p3 and p4: 1763 // The definition of a constexpr function(p3) or constructor(p4) [...] shall 1764 // contain only 1765 for (const auto *DclIt : DS->decls()) { 1766 switch (DclIt->getKind()) { 1767 case Decl::StaticAssert: 1768 case Decl::Using: 1769 case Decl::UsingShadow: 1770 case Decl::UsingDirective: 1771 case Decl::UnresolvedUsingTypename: 1772 case Decl::UnresolvedUsingValue: 1773 // - static_assert-declarations 1774 // - using-declarations, 1775 // - using-directives, 1776 continue; 1777 1778 case Decl::Typedef: 1779 case Decl::TypeAlias: { 1780 // - typedef declarations and alias-declarations that do not define 1781 // classes or enumerations, 1782 const auto *TN = cast<TypedefNameDecl>(DclIt); 1783 if (TN->getUnderlyingType()->isVariablyModifiedType()) { 1784 // Don't allow variably-modified types in constexpr functions. 1785 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1786 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc(); 1787 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla) 1788 << TL.getSourceRange() << TL.getType() 1789 << isa<CXXConstructorDecl>(Dcl); 1790 } 1791 return false; 1792 } 1793 continue; 1794 } 1795 1796 case Decl::Enum: 1797 case Decl::CXXRecord: 1798 // C++1y allows types to be defined, not just declared. 1799 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) { 1800 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1801 SemaRef.Diag(DS->getBeginLoc(), 1802 SemaRef.getLangOpts().CPlusPlus14 1803 ? diag::warn_cxx11_compat_constexpr_type_definition 1804 : diag::ext_constexpr_type_definition) 1805 << isa<CXXConstructorDecl>(Dcl); 1806 } else if (!SemaRef.getLangOpts().CPlusPlus14) { 1807 return false; 1808 } 1809 } 1810 continue; 1811 1812 case Decl::EnumConstant: 1813 case Decl::IndirectField: 1814 case Decl::ParmVar: 1815 // These can only appear with other declarations which are banned in 1816 // C++11 and permitted in C++1y, so ignore them. 1817 continue; 1818 1819 case Decl::Var: 1820 case Decl::Decomposition: { 1821 // C++1y [dcl.constexpr]p3 allows anything except: 1822 // a definition of a variable of non-literal type or of static or 1823 // thread storage duration or [before C++2a] for which no 1824 // initialization is performed. 1825 const auto *VD = cast<VarDecl>(DclIt); 1826 if (VD->isThisDeclarationADefinition()) { 1827 if (VD->isStaticLocal()) { 1828 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1829 SemaRef.Diag(VD->getLocation(), 1830 diag::err_constexpr_local_var_static) 1831 << isa<CXXConstructorDecl>(Dcl) 1832 << (VD->getTLSKind() == VarDecl::TLS_Dynamic); 1833 } 1834 return false; 1835 } 1836 if (CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(), 1837 diag::err_constexpr_local_var_non_literal_type, 1838 isa<CXXConstructorDecl>(Dcl))) 1839 return false; 1840 if (!VD->getType()->isDependentType() && 1841 !VD->hasInit() && !VD->isCXXForRangeDecl()) { 1842 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1843 SemaRef.Diag( 1844 VD->getLocation(), 1845 SemaRef.getLangOpts().CPlusPlus2a 1846 ? diag::warn_cxx17_compat_constexpr_local_var_no_init 1847 : diag::ext_constexpr_local_var_no_init) 1848 << isa<CXXConstructorDecl>(Dcl); 1849 } else if (!SemaRef.getLangOpts().CPlusPlus2a) { 1850 return false; 1851 } 1852 continue; 1853 } 1854 } 1855 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1856 SemaRef.Diag(VD->getLocation(), 1857 SemaRef.getLangOpts().CPlusPlus14 1858 ? diag::warn_cxx11_compat_constexpr_local_var 1859 : diag::ext_constexpr_local_var) 1860 << isa<CXXConstructorDecl>(Dcl); 1861 } else if (!SemaRef.getLangOpts().CPlusPlus14) { 1862 return false; 1863 } 1864 continue; 1865 } 1866 1867 case Decl::NamespaceAlias: 1868 case Decl::Function: 1869 // These are disallowed in C++11 and permitted in C++1y. Allow them 1870 // everywhere as an extension. 1871 if (!Cxx1yLoc.isValid()) 1872 Cxx1yLoc = DS->getBeginLoc(); 1873 continue; 1874 1875 default: 1876 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1877 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 1878 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 1879 } 1880 return false; 1881 } 1882 } 1883 1884 return true; 1885 } 1886 1887 /// Check that the given field is initialized within a constexpr constructor. 1888 /// 1889 /// \param Dcl The constexpr constructor being checked. 1890 /// \param Field The field being checked. This may be a member of an anonymous 1891 /// struct or union nested within the class being checked. 1892 /// \param Inits All declarations, including anonymous struct/union members and 1893 /// indirect members, for which any initialization was provided. 1894 /// \param Diagnosed Whether we've emitted the error message yet. Used to attach 1895 /// multiple notes for different members to the same error. 1896 /// \param Kind Whether we're diagnosing a constructor as written or determining 1897 /// whether the formal requirements are satisfied. 1898 /// \return \c false if we're checking for validity and the constructor does 1899 /// not satisfy the requirements on a constexpr constructor. 1900 static bool CheckConstexprCtorInitializer(Sema &SemaRef, 1901 const FunctionDecl *Dcl, 1902 FieldDecl *Field, 1903 llvm::SmallSet<Decl*, 16> &Inits, 1904 bool &Diagnosed, 1905 Sema::CheckConstexprKind Kind) { 1906 // In C++20 onwards, there's nothing to check for validity. 1907 if (Kind == Sema::CheckConstexprKind::CheckValid && 1908 SemaRef.getLangOpts().CPlusPlus2a) 1909 return true; 1910 1911 if (Field->isInvalidDecl()) 1912 return true; 1913 1914 if (Field->isUnnamedBitfield()) 1915 return true; 1916 1917 // Anonymous unions with no variant members and empty anonymous structs do not 1918 // need to be explicitly initialized. FIXME: Anonymous structs that contain no 1919 // indirect fields don't need initializing. 1920 if (Field->isAnonymousStructOrUnion() && 1921 (Field->getType()->isUnionType() 1922 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers() 1923 : Field->getType()->getAsCXXRecordDecl()->isEmpty())) 1924 return true; 1925 1926 if (!Inits.count(Field)) { 1927 if (Kind == Sema::CheckConstexprKind::Diagnose) { 1928 if (!Diagnosed) { 1929 SemaRef.Diag(Dcl->getLocation(), 1930 SemaRef.getLangOpts().CPlusPlus2a 1931 ? diag::warn_cxx17_compat_constexpr_ctor_missing_init 1932 : diag::ext_constexpr_ctor_missing_init); 1933 Diagnosed = true; 1934 } 1935 SemaRef.Diag(Field->getLocation(), 1936 diag::note_constexpr_ctor_missing_init); 1937 } else if (!SemaRef.getLangOpts().CPlusPlus2a) { 1938 return false; 1939 } 1940 } else if (Field->isAnonymousStructOrUnion()) { 1941 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl(); 1942 for (auto *I : RD->fields()) 1943 // If an anonymous union contains an anonymous struct of which any member 1944 // is initialized, all members must be initialized. 1945 if (!RD->isUnion() || Inits.count(I)) 1946 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, 1947 Kind)) 1948 return false; 1949 } 1950 return true; 1951 } 1952 1953 /// Check the provided statement is allowed in a constexpr function 1954 /// definition. 1955 static bool 1956 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S, 1957 SmallVectorImpl<SourceLocation> &ReturnStmts, 1958 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc, 1959 Sema::CheckConstexprKind Kind) { 1960 // - its function-body shall be [...] a compound-statement that contains only 1961 switch (S->getStmtClass()) { 1962 case Stmt::NullStmtClass: 1963 // - null statements, 1964 return true; 1965 1966 case Stmt::DeclStmtClass: 1967 // - static_assert-declarations 1968 // - using-declarations, 1969 // - using-directives, 1970 // - typedef declarations and alias-declarations that do not define 1971 // classes or enumerations, 1972 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind)) 1973 return false; 1974 return true; 1975 1976 case Stmt::ReturnStmtClass: 1977 // - and exactly one return statement; 1978 if (isa<CXXConstructorDecl>(Dcl)) { 1979 // C++1y allows return statements in constexpr constructors. 1980 if (!Cxx1yLoc.isValid()) 1981 Cxx1yLoc = S->getBeginLoc(); 1982 return true; 1983 } 1984 1985 ReturnStmts.push_back(S->getBeginLoc()); 1986 return true; 1987 1988 case Stmt::CompoundStmtClass: { 1989 // C++1y allows compound-statements. 1990 if (!Cxx1yLoc.isValid()) 1991 Cxx1yLoc = S->getBeginLoc(); 1992 1993 CompoundStmt *CompStmt = cast<CompoundStmt>(S); 1994 for (auto *BodyIt : CompStmt->body()) { 1995 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts, 1996 Cxx1yLoc, Cxx2aLoc, Kind)) 1997 return false; 1998 } 1999 return true; 2000 } 2001 2002 case Stmt::AttributedStmtClass: 2003 if (!Cxx1yLoc.isValid()) 2004 Cxx1yLoc = S->getBeginLoc(); 2005 return true; 2006 2007 case Stmt::IfStmtClass: { 2008 // C++1y allows if-statements. 2009 if (!Cxx1yLoc.isValid()) 2010 Cxx1yLoc = S->getBeginLoc(); 2011 2012 IfStmt *If = cast<IfStmt>(S); 2013 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts, 2014 Cxx1yLoc, Cxx2aLoc, Kind)) 2015 return false; 2016 if (If->getElse() && 2017 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts, 2018 Cxx1yLoc, Cxx2aLoc, Kind)) 2019 return false; 2020 return true; 2021 } 2022 2023 case Stmt::WhileStmtClass: 2024 case Stmt::DoStmtClass: 2025 case Stmt::ForStmtClass: 2026 case Stmt::CXXForRangeStmtClass: 2027 case Stmt::ContinueStmtClass: 2028 // C++1y allows all of these. We don't allow them as extensions in C++11, 2029 // because they don't make sense without variable mutation. 2030 if (!SemaRef.getLangOpts().CPlusPlus14) 2031 break; 2032 if (!Cxx1yLoc.isValid()) 2033 Cxx1yLoc = S->getBeginLoc(); 2034 for (Stmt *SubStmt : S->children()) 2035 if (SubStmt && 2036 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2037 Cxx1yLoc, Cxx2aLoc, Kind)) 2038 return false; 2039 return true; 2040 2041 case Stmt::SwitchStmtClass: 2042 case Stmt::CaseStmtClass: 2043 case Stmt::DefaultStmtClass: 2044 case Stmt::BreakStmtClass: 2045 // C++1y allows switch-statements, and since they don't need variable 2046 // mutation, we can reasonably allow them in C++11 as an extension. 2047 if (!Cxx1yLoc.isValid()) 2048 Cxx1yLoc = S->getBeginLoc(); 2049 for (Stmt *SubStmt : S->children()) 2050 if (SubStmt && 2051 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2052 Cxx1yLoc, Cxx2aLoc, Kind)) 2053 return false; 2054 return true; 2055 2056 case Stmt::GCCAsmStmtClass: 2057 case Stmt::MSAsmStmtClass: 2058 // C++2a allows inline assembly statements. 2059 case Stmt::CXXTryStmtClass: 2060 if (Cxx2aLoc.isInvalid()) 2061 Cxx2aLoc = S->getBeginLoc(); 2062 for (Stmt *SubStmt : S->children()) { 2063 if (SubStmt && 2064 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2065 Cxx1yLoc, Cxx2aLoc, Kind)) 2066 return false; 2067 } 2068 return true; 2069 2070 case Stmt::CXXCatchStmtClass: 2071 // Do not bother checking the language mode (already covered by the 2072 // try block check). 2073 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, 2074 cast<CXXCatchStmt>(S)->getHandlerBlock(), 2075 ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind)) 2076 return false; 2077 return true; 2078 2079 default: 2080 if (!isa<Expr>(S)) 2081 break; 2082 2083 // C++1y allows expression-statements. 2084 if (!Cxx1yLoc.isValid()) 2085 Cxx1yLoc = S->getBeginLoc(); 2086 return true; 2087 } 2088 2089 if (Kind == Sema::CheckConstexprKind::Diagnose) { 2090 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt) 2091 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval(); 2092 } 2093 return false; 2094 } 2095 2096 /// Check the body for the given constexpr function declaration only contains 2097 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4. 2098 /// 2099 /// \return true if the body is OK, false if we have found or diagnosed a 2100 /// problem. 2101 static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl, 2102 Stmt *Body, 2103 Sema::CheckConstexprKind Kind) { 2104 SmallVector<SourceLocation, 4> ReturnStmts; 2105 2106 if (isa<CXXTryStmt>(Body)) { 2107 // C++11 [dcl.constexpr]p3: 2108 // The definition of a constexpr function shall satisfy the following 2109 // constraints: [...] 2110 // - its function-body shall be = delete, = default, or a 2111 // compound-statement 2112 // 2113 // C++11 [dcl.constexpr]p4: 2114 // In the definition of a constexpr constructor, [...] 2115 // - its function-body shall not be a function-try-block; 2116 // 2117 // This restriction is lifted in C++2a, as long as inner statements also 2118 // apply the general constexpr rules. 2119 switch (Kind) { 2120 case Sema::CheckConstexprKind::CheckValid: 2121 if (!SemaRef.getLangOpts().CPlusPlus2a) 2122 return false; 2123 break; 2124 2125 case Sema::CheckConstexprKind::Diagnose: 2126 SemaRef.Diag(Body->getBeginLoc(), 2127 !SemaRef.getLangOpts().CPlusPlus2a 2128 ? diag::ext_constexpr_function_try_block_cxx2a 2129 : diag::warn_cxx17_compat_constexpr_function_try_block) 2130 << isa<CXXConstructorDecl>(Dcl); 2131 break; 2132 } 2133 } 2134 2135 // - its function-body shall be [...] a compound-statement that contains only 2136 // [... list of cases ...] 2137 // 2138 // Note that walking the children here is enough to properly check for 2139 // CompoundStmt and CXXTryStmt body. 2140 SourceLocation Cxx1yLoc, Cxx2aLoc; 2141 for (Stmt *SubStmt : Body->children()) { 2142 if (SubStmt && 2143 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts, 2144 Cxx1yLoc, Cxx2aLoc, Kind)) 2145 return false; 2146 } 2147 2148 if (Kind == Sema::CheckConstexprKind::CheckValid) { 2149 // If this is only valid as an extension, report that we don't satisfy the 2150 // constraints of the current language. 2151 if ((Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus2a) || 2152 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17)) 2153 return false; 2154 } else if (Cxx2aLoc.isValid()) { 2155 SemaRef.Diag(Cxx2aLoc, 2156 SemaRef.getLangOpts().CPlusPlus2a 2157 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt 2158 : diag::ext_constexpr_body_invalid_stmt_cxx2a) 2159 << isa<CXXConstructorDecl>(Dcl); 2160 } else if (Cxx1yLoc.isValid()) { 2161 SemaRef.Diag(Cxx1yLoc, 2162 SemaRef.getLangOpts().CPlusPlus14 2163 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt 2164 : diag::ext_constexpr_body_invalid_stmt) 2165 << isa<CXXConstructorDecl>(Dcl); 2166 } 2167 2168 if (const CXXConstructorDecl *Constructor 2169 = dyn_cast<CXXConstructorDecl>(Dcl)) { 2170 const CXXRecordDecl *RD = Constructor->getParent(); 2171 // DR1359: 2172 // - every non-variant non-static data member and base class sub-object 2173 // shall be initialized; 2174 // DR1460: 2175 // - if the class is a union having variant members, exactly one of them 2176 // shall be initialized; 2177 if (RD->isUnion()) { 2178 if (Constructor->getNumCtorInitializers() == 0 && 2179 RD->hasVariantMembers()) { 2180 if (Kind == Sema::CheckConstexprKind::Diagnose) { 2181 SemaRef.Diag( 2182 Dcl->getLocation(), 2183 SemaRef.getLangOpts().CPlusPlus2a 2184 ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init 2185 : diag::ext_constexpr_union_ctor_no_init); 2186 } else if (!SemaRef.getLangOpts().CPlusPlus2a) { 2187 return false; 2188 } 2189 } 2190 } else if (!Constructor->isDependentContext() && 2191 !Constructor->isDelegatingConstructor()) { 2192 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases"); 2193 2194 // Skip detailed checking if we have enough initializers, and we would 2195 // allow at most one initializer per member. 2196 bool AnyAnonStructUnionMembers = false; 2197 unsigned Fields = 0; 2198 for (CXXRecordDecl::field_iterator I = RD->field_begin(), 2199 E = RD->field_end(); I != E; ++I, ++Fields) { 2200 if (I->isAnonymousStructOrUnion()) { 2201 AnyAnonStructUnionMembers = true; 2202 break; 2203 } 2204 } 2205 // DR1460: 2206 // - if the class is a union-like class, but is not a union, for each of 2207 // its anonymous union members having variant members, exactly one of 2208 // them shall be initialized; 2209 if (AnyAnonStructUnionMembers || 2210 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) { 2211 // Check initialization of non-static data members. Base classes are 2212 // always initialized so do not need to be checked. Dependent bases 2213 // might not have initializers in the member initializer list. 2214 llvm::SmallSet<Decl*, 16> Inits; 2215 for (const auto *I: Constructor->inits()) { 2216 if (FieldDecl *FD = I->getMember()) 2217 Inits.insert(FD); 2218 else if (IndirectFieldDecl *ID = I->getIndirectMember()) 2219 Inits.insert(ID->chain_begin(), ID->chain_end()); 2220 } 2221 2222 bool Diagnosed = false; 2223 for (auto *I : RD->fields()) 2224 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed, 2225 Kind)) 2226 return false; 2227 } 2228 } 2229 } else { 2230 if (ReturnStmts.empty()) { 2231 // C++1y doesn't require constexpr functions to contain a 'return' 2232 // statement. We still do, unless the return type might be void, because 2233 // otherwise if there's no return statement, the function cannot 2234 // be used in a core constant expression. 2235 bool OK = SemaRef.getLangOpts().CPlusPlus14 && 2236 (Dcl->getReturnType()->isVoidType() || 2237 Dcl->getReturnType()->isDependentType()); 2238 switch (Kind) { 2239 case Sema::CheckConstexprKind::Diagnose: 2240 SemaRef.Diag(Dcl->getLocation(), 2241 OK ? diag::warn_cxx11_compat_constexpr_body_no_return 2242 : diag::err_constexpr_body_no_return) 2243 << Dcl->isConsteval(); 2244 if (!OK) 2245 return false; 2246 break; 2247 2248 case Sema::CheckConstexprKind::CheckValid: 2249 // The formal requirements don't include this rule in C++14, even 2250 // though the "must be able to produce a constant expression" rules 2251 // still imply it in some cases. 2252 if (!SemaRef.getLangOpts().CPlusPlus14) 2253 return false; 2254 break; 2255 } 2256 } else if (ReturnStmts.size() > 1) { 2257 switch (Kind) { 2258 case Sema::CheckConstexprKind::Diagnose: 2259 SemaRef.Diag( 2260 ReturnStmts.back(), 2261 SemaRef.getLangOpts().CPlusPlus14 2262 ? diag::warn_cxx11_compat_constexpr_body_multiple_return 2263 : diag::ext_constexpr_body_multiple_return); 2264 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I) 2265 SemaRef.Diag(ReturnStmts[I], 2266 diag::note_constexpr_body_previous_return); 2267 break; 2268 2269 case Sema::CheckConstexprKind::CheckValid: 2270 if (!SemaRef.getLangOpts().CPlusPlus14) 2271 return false; 2272 break; 2273 } 2274 } 2275 } 2276 2277 // C++11 [dcl.constexpr]p5: 2278 // if no function argument values exist such that the function invocation 2279 // substitution would produce a constant expression, the program is 2280 // ill-formed; no diagnostic required. 2281 // C++11 [dcl.constexpr]p3: 2282 // - every constructor call and implicit conversion used in initializing the 2283 // return value shall be one of those allowed in a constant expression. 2284 // C++11 [dcl.constexpr]p4: 2285 // - every constructor involved in initializing non-static data members and 2286 // base class sub-objects shall be a constexpr constructor. 2287 // 2288 // Note that this rule is distinct from the "requirements for a constexpr 2289 // function", so is not checked in CheckValid mode. 2290 SmallVector<PartialDiagnosticAt, 8> Diags; 2291 if (Kind == Sema::CheckConstexprKind::Diagnose && 2292 !Expr::isPotentialConstantExpr(Dcl, Diags)) { 2293 SemaRef.Diag(Dcl->getLocation(), 2294 diag::ext_constexpr_function_never_constant_expr) 2295 << isa<CXXConstructorDecl>(Dcl); 2296 for (size_t I = 0, N = Diags.size(); I != N; ++I) 2297 SemaRef.Diag(Diags[I].first, Diags[I].second); 2298 // Don't return false here: we allow this for compatibility in 2299 // system headers. 2300 } 2301 2302 return true; 2303 } 2304 2305 /// Get the class that is directly named by the current context. This is the 2306 /// class for which an unqualified-id in this scope could name a constructor 2307 /// or destructor. 2308 /// 2309 /// If the scope specifier denotes a class, this will be that class. 2310 /// If the scope specifier is empty, this will be the class whose 2311 /// member-specification we are currently within. Otherwise, there 2312 /// is no such class. 2313 CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) { 2314 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2315 2316 if (SS && SS->isInvalid()) 2317 return nullptr; 2318 2319 if (SS && SS->isNotEmpty()) { 2320 DeclContext *DC = computeDeclContext(*SS, true); 2321 return dyn_cast_or_null<CXXRecordDecl>(DC); 2322 } 2323 2324 return dyn_cast_or_null<CXXRecordDecl>(CurContext); 2325 } 2326 2327 /// isCurrentClassName - Determine whether the identifier II is the 2328 /// name of the class type currently being defined. In the case of 2329 /// nested classes, this will only return true if II is the name of 2330 /// the innermost class. 2331 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S, 2332 const CXXScopeSpec *SS) { 2333 CXXRecordDecl *CurDecl = getCurrentClass(S, SS); 2334 return CurDecl && &II == CurDecl->getIdentifier(); 2335 } 2336 2337 /// Determine whether the identifier II is a typo for the name of 2338 /// the class type currently being defined. If so, update it to the identifier 2339 /// that should have been used. 2340 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) { 2341 assert(getLangOpts().CPlusPlus && "No class names in C!"); 2342 2343 if (!getLangOpts().SpellChecking) 2344 return false; 2345 2346 CXXRecordDecl *CurDecl; 2347 if (SS && SS->isSet() && !SS->isInvalid()) { 2348 DeclContext *DC = computeDeclContext(*SS, true); 2349 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC); 2350 } else 2351 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext); 2352 2353 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() && 2354 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName()) 2355 < II->getLength()) { 2356 II = CurDecl->getIdentifier(); 2357 return true; 2358 } 2359 2360 return false; 2361 } 2362 2363 /// Determine whether the given class is a base class of the given 2364 /// class, including looking at dependent bases. 2365 static bool findCircularInheritance(const CXXRecordDecl *Class, 2366 const CXXRecordDecl *Current) { 2367 SmallVector<const CXXRecordDecl*, 8> Queue; 2368 2369 Class = Class->getCanonicalDecl(); 2370 while (true) { 2371 for (const auto &I : Current->bases()) { 2372 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl(); 2373 if (!Base) 2374 continue; 2375 2376 Base = Base->getDefinition(); 2377 if (!Base) 2378 continue; 2379 2380 if (Base->getCanonicalDecl() == Class) 2381 return true; 2382 2383 Queue.push_back(Base); 2384 } 2385 2386 if (Queue.empty()) 2387 return false; 2388 2389 Current = Queue.pop_back_val(); 2390 } 2391 2392 return false; 2393 } 2394 2395 /// Check the validity of a C++ base class specifier. 2396 /// 2397 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics 2398 /// and returns NULL otherwise. 2399 CXXBaseSpecifier * 2400 Sema::CheckBaseSpecifier(CXXRecordDecl *Class, 2401 SourceRange SpecifierRange, 2402 bool Virtual, AccessSpecifier Access, 2403 TypeSourceInfo *TInfo, 2404 SourceLocation EllipsisLoc) { 2405 QualType BaseType = TInfo->getType(); 2406 2407 // C++ [class.union]p1: 2408 // A union shall not have base classes. 2409 if (Class->isUnion()) { 2410 Diag(Class->getLocation(), diag::err_base_clause_on_union) 2411 << SpecifierRange; 2412 return nullptr; 2413 } 2414 2415 if (EllipsisLoc.isValid() && 2416 !TInfo->getType()->containsUnexpandedParameterPack()) { 2417 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 2418 << TInfo->getTypeLoc().getSourceRange(); 2419 EllipsisLoc = SourceLocation(); 2420 } 2421 2422 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc(); 2423 2424 if (BaseType->isDependentType()) { 2425 // Make sure that we don't have circular inheritance among our dependent 2426 // bases. For non-dependent bases, the check for completeness below handles 2427 // this. 2428 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) { 2429 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() || 2430 ((BaseDecl = BaseDecl->getDefinition()) && 2431 findCircularInheritance(Class, BaseDecl))) { 2432 Diag(BaseLoc, diag::err_circular_inheritance) 2433 << BaseType << Context.getTypeDeclType(Class); 2434 2435 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl()) 2436 Diag(BaseDecl->getLocation(), diag::note_previous_decl) 2437 << BaseType; 2438 2439 return nullptr; 2440 } 2441 } 2442 2443 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2444 Class->getTagKind() == TTK_Class, 2445 Access, TInfo, EllipsisLoc); 2446 } 2447 2448 // Base specifiers must be record types. 2449 if (!BaseType->isRecordType()) { 2450 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange; 2451 return nullptr; 2452 } 2453 2454 // C++ [class.union]p1: 2455 // A union shall not be used as a base class. 2456 if (BaseType->isUnionType()) { 2457 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange; 2458 return nullptr; 2459 } 2460 2461 // For the MS ABI, propagate DLL attributes to base class templates. 2462 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 2463 if (Attr *ClassAttr = getDLLAttr(Class)) { 2464 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 2465 BaseType->getAsCXXRecordDecl())) { 2466 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate, 2467 BaseLoc); 2468 } 2469 } 2470 } 2471 2472 // C++ [class.derived]p2: 2473 // The class-name in a base-specifier shall not be an incompletely 2474 // defined class. 2475 if (RequireCompleteType(BaseLoc, BaseType, 2476 diag::err_incomplete_base_class, SpecifierRange)) { 2477 Class->setInvalidDecl(); 2478 return nullptr; 2479 } 2480 2481 // If the base class is polymorphic or isn't empty, the new one is/isn't, too. 2482 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl(); 2483 assert(BaseDecl && "Record type has no declaration"); 2484 BaseDecl = BaseDecl->getDefinition(); 2485 assert(BaseDecl && "Base type is not incomplete, but has no definition"); 2486 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl); 2487 assert(CXXBaseDecl && "Base type is not a C++ type"); 2488 2489 // Microsoft docs say: 2490 // "If a base-class has a code_seg attribute, derived classes must have the 2491 // same attribute." 2492 const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>(); 2493 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>(); 2494 if ((DerivedCSA || BaseCSA) && 2495 (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) { 2496 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base); 2497 Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here) 2498 << CXXBaseDecl; 2499 return nullptr; 2500 } 2501 2502 // A class which contains a flexible array member is not suitable for use as a 2503 // base class: 2504 // - If the layout determines that a base comes before another base, 2505 // the flexible array member would index into the subsequent base. 2506 // - If the layout determines that base comes before the derived class, 2507 // the flexible array member would index into the derived class. 2508 if (CXXBaseDecl->hasFlexibleArrayMember()) { 2509 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member) 2510 << CXXBaseDecl->getDeclName(); 2511 return nullptr; 2512 } 2513 2514 // C++ [class]p3: 2515 // If a class is marked final and it appears as a base-type-specifier in 2516 // base-clause, the program is ill-formed. 2517 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) { 2518 Diag(BaseLoc, diag::err_class_marked_final_used_as_base) 2519 << CXXBaseDecl->getDeclName() 2520 << FA->isSpelledAsSealed(); 2521 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at) 2522 << CXXBaseDecl->getDeclName() << FA->getRange(); 2523 return nullptr; 2524 } 2525 2526 if (BaseDecl->isInvalidDecl()) 2527 Class->setInvalidDecl(); 2528 2529 // Create the base specifier. 2530 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual, 2531 Class->getTagKind() == TTK_Class, 2532 Access, TInfo, EllipsisLoc); 2533 } 2534 2535 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is 2536 /// one entry in the base class list of a class specifier, for 2537 /// example: 2538 /// class foo : public bar, virtual private baz { 2539 /// 'public bar' and 'virtual private baz' are each base-specifiers. 2540 BaseResult 2541 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, 2542 ParsedAttributes &Attributes, 2543 bool Virtual, AccessSpecifier Access, 2544 ParsedType basetype, SourceLocation BaseLoc, 2545 SourceLocation EllipsisLoc) { 2546 if (!classdecl) 2547 return true; 2548 2549 AdjustDeclIfTemplate(classdecl); 2550 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl); 2551 if (!Class) 2552 return true; 2553 2554 // We haven't yet attached the base specifiers. 2555 Class->setIsParsingBaseSpecifiers(); 2556 2557 // We do not support any C++11 attributes on base-specifiers yet. 2558 // Diagnose any attributes we see. 2559 for (const ParsedAttr &AL : Attributes) { 2560 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute) 2561 continue; 2562 Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute 2563 ? (unsigned)diag::warn_unknown_attribute_ignored 2564 : (unsigned)diag::err_base_specifier_attribute) 2565 << AL; 2566 } 2567 2568 TypeSourceInfo *TInfo = nullptr; 2569 GetTypeFromParser(basetype, &TInfo); 2570 2571 if (EllipsisLoc.isInvalid() && 2572 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo, 2573 UPPC_BaseType)) 2574 return true; 2575 2576 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange, 2577 Virtual, Access, TInfo, 2578 EllipsisLoc)) 2579 return BaseSpec; 2580 else 2581 Class->setInvalidDecl(); 2582 2583 return true; 2584 } 2585 2586 /// Use small set to collect indirect bases. As this is only used 2587 /// locally, there's no need to abstract the small size parameter. 2588 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet; 2589 2590 /// Recursively add the bases of Type. Don't add Type itself. 2591 static void 2592 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set, 2593 const QualType &Type) 2594 { 2595 // Even though the incoming type is a base, it might not be 2596 // a class -- it could be a template parm, for instance. 2597 if (auto Rec = Type->getAs<RecordType>()) { 2598 auto Decl = Rec->getAsCXXRecordDecl(); 2599 2600 // Iterate over its bases. 2601 for (const auto &BaseSpec : Decl->bases()) { 2602 QualType Base = Context.getCanonicalType(BaseSpec.getType()) 2603 .getUnqualifiedType(); 2604 if (Set.insert(Base).second) 2605 // If we've not already seen it, recurse. 2606 NoteIndirectBases(Context, Set, Base); 2607 } 2608 } 2609 } 2610 2611 /// Performs the actual work of attaching the given base class 2612 /// specifiers to a C++ class. 2613 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, 2614 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2615 if (Bases.empty()) 2616 return false; 2617 2618 // Used to keep track of which base types we have already seen, so 2619 // that we can properly diagnose redundant direct base types. Note 2620 // that the key is always the unqualified canonical type of the base 2621 // class. 2622 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes; 2623 2624 // Used to track indirect bases so we can see if a direct base is 2625 // ambiguous. 2626 IndirectBaseSet IndirectBaseTypes; 2627 2628 // Copy non-redundant base specifiers into permanent storage. 2629 unsigned NumGoodBases = 0; 2630 bool Invalid = false; 2631 for (unsigned idx = 0; idx < Bases.size(); ++idx) { 2632 QualType NewBaseType 2633 = Context.getCanonicalType(Bases[idx]->getType()); 2634 NewBaseType = NewBaseType.getLocalUnqualifiedType(); 2635 2636 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType]; 2637 if (KnownBase) { 2638 // C++ [class.mi]p3: 2639 // A class shall not be specified as a direct base class of a 2640 // derived class more than once. 2641 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class) 2642 << KnownBase->getType() << Bases[idx]->getSourceRange(); 2643 2644 // Delete the duplicate base class specifier; we're going to 2645 // overwrite its pointer later. 2646 Context.Deallocate(Bases[idx]); 2647 2648 Invalid = true; 2649 } else { 2650 // Okay, add this new base class. 2651 KnownBase = Bases[idx]; 2652 Bases[NumGoodBases++] = Bases[idx]; 2653 2654 // Note this base's direct & indirect bases, if there could be ambiguity. 2655 if (Bases.size() > 1) 2656 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType); 2657 2658 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) { 2659 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()); 2660 if (Class->isInterface() && 2661 (!RD->isInterfaceLike() || 2662 KnownBase->getAccessSpecifier() != AS_public)) { 2663 // The Microsoft extension __interface does not permit bases that 2664 // are not themselves public interfaces. 2665 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface) 2666 << getRecordDiagFromTagKind(RD->getTagKind()) << RD 2667 << RD->getSourceRange(); 2668 Invalid = true; 2669 } 2670 if (RD->hasAttr<WeakAttr>()) 2671 Class->addAttr(WeakAttr::CreateImplicit(Context)); 2672 } 2673 } 2674 } 2675 2676 // Attach the remaining base class specifiers to the derived class. 2677 Class->setBases(Bases.data(), NumGoodBases); 2678 2679 // Check that the only base classes that are duplicate are virtual. 2680 for (unsigned idx = 0; idx < NumGoodBases; ++idx) { 2681 // Check whether this direct base is inaccessible due to ambiguity. 2682 QualType BaseType = Bases[idx]->getType(); 2683 2684 // Skip all dependent types in templates being used as base specifiers. 2685 // Checks below assume that the base specifier is a CXXRecord. 2686 if (BaseType->isDependentType()) 2687 continue; 2688 2689 CanQualType CanonicalBase = Context.getCanonicalType(BaseType) 2690 .getUnqualifiedType(); 2691 2692 if (IndirectBaseTypes.count(CanonicalBase)) { 2693 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2694 /*DetectVirtual=*/true); 2695 bool found 2696 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths); 2697 assert(found); 2698 (void)found; 2699 2700 if (Paths.isAmbiguous(CanonicalBase)) 2701 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class) 2702 << BaseType << getAmbiguousPathsDisplayString(Paths) 2703 << Bases[idx]->getSourceRange(); 2704 else 2705 assert(Bases[idx]->isVirtual()); 2706 } 2707 2708 // Delete the base class specifier, since its data has been copied 2709 // into the CXXRecordDecl. 2710 Context.Deallocate(Bases[idx]); 2711 } 2712 2713 return Invalid; 2714 } 2715 2716 /// ActOnBaseSpecifiers - Attach the given base specifiers to the 2717 /// class, after checking whether there are any duplicate base 2718 /// classes. 2719 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, 2720 MutableArrayRef<CXXBaseSpecifier *> Bases) { 2721 if (!ClassDecl || Bases.empty()) 2722 return; 2723 2724 AdjustDeclIfTemplate(ClassDecl); 2725 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases); 2726 } 2727 2728 /// Determine whether the type \p Derived is a C++ class that is 2729 /// derived from the type \p Base. 2730 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) { 2731 if (!getLangOpts().CPlusPlus) 2732 return false; 2733 2734 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2735 if (!DerivedRD) 2736 return false; 2737 2738 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2739 if (!BaseRD) 2740 return false; 2741 2742 // If either the base or the derived type is invalid, don't try to 2743 // check whether one is derived from the other. 2744 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl()) 2745 return false; 2746 2747 // FIXME: In a modules build, do we need the entire path to be visible for us 2748 // to be able to use the inheritance relationship? 2749 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2750 return false; 2751 2752 return DerivedRD->isDerivedFrom(BaseRD); 2753 } 2754 2755 /// Determine whether the type \p Derived is a C++ class that is 2756 /// derived from the type \p Base. 2757 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, 2758 CXXBasePaths &Paths) { 2759 if (!getLangOpts().CPlusPlus) 2760 return false; 2761 2762 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl(); 2763 if (!DerivedRD) 2764 return false; 2765 2766 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl(); 2767 if (!BaseRD) 2768 return false; 2769 2770 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined()) 2771 return false; 2772 2773 return DerivedRD->isDerivedFrom(BaseRD, Paths); 2774 } 2775 2776 static void BuildBasePathArray(const CXXBasePath &Path, 2777 CXXCastPath &BasePathArray) { 2778 // We first go backward and check if we have a virtual base. 2779 // FIXME: It would be better if CXXBasePath had the base specifier for 2780 // the nearest virtual base. 2781 unsigned Start = 0; 2782 for (unsigned I = Path.size(); I != 0; --I) { 2783 if (Path[I - 1].Base->isVirtual()) { 2784 Start = I - 1; 2785 break; 2786 } 2787 } 2788 2789 // Now add all bases. 2790 for (unsigned I = Start, E = Path.size(); I != E; ++I) 2791 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base)); 2792 } 2793 2794 2795 void Sema::BuildBasePathArray(const CXXBasePaths &Paths, 2796 CXXCastPath &BasePathArray) { 2797 assert(BasePathArray.empty() && "Base path array must be empty!"); 2798 assert(Paths.isRecordingPaths() && "Must record paths!"); 2799 return ::BuildBasePathArray(Paths.front(), BasePathArray); 2800 } 2801 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base 2802 /// conversion (where Derived and Base are class types) is 2803 /// well-formed, meaning that the conversion is unambiguous (and 2804 /// that all of the base classes are accessible). Returns true 2805 /// and emits a diagnostic if the code is ill-formed, returns false 2806 /// otherwise. Loc is the location where this routine should point to 2807 /// if there is an error, and Range is the source range to highlight 2808 /// if there is an error. 2809 /// 2810 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the 2811 /// diagnostic for the respective type of error will be suppressed, but the 2812 /// check for ill-formed code will still be performed. 2813 bool 2814 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2815 unsigned InaccessibleBaseID, 2816 unsigned AmbigiousBaseConvID, 2817 SourceLocation Loc, SourceRange Range, 2818 DeclarationName Name, 2819 CXXCastPath *BasePath, 2820 bool IgnoreAccess) { 2821 // First, determine whether the path from Derived to Base is 2822 // ambiguous. This is slightly more expensive than checking whether 2823 // the Derived to Base conversion exists, because here we need to 2824 // explore multiple paths to determine if there is an ambiguity. 2825 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2826 /*DetectVirtual=*/false); 2827 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2828 if (!DerivationOkay) 2829 return true; 2830 2831 const CXXBasePath *Path = nullptr; 2832 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) 2833 Path = &Paths.front(); 2834 2835 // For MSVC compatibility, check if Derived directly inherits from Base. Clang 2836 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the 2837 // user to access such bases. 2838 if (!Path && getLangOpts().MSVCCompat) { 2839 for (const CXXBasePath &PossiblePath : Paths) { 2840 if (PossiblePath.size() == 1) { 2841 Path = &PossiblePath; 2842 if (AmbigiousBaseConvID) 2843 Diag(Loc, diag::ext_ms_ambiguous_direct_base) 2844 << Base << Derived << Range; 2845 break; 2846 } 2847 } 2848 } 2849 2850 if (Path) { 2851 if (!IgnoreAccess) { 2852 // Check that the base class can be accessed. 2853 switch ( 2854 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) { 2855 case AR_inaccessible: 2856 return true; 2857 case AR_accessible: 2858 case AR_dependent: 2859 case AR_delayed: 2860 break; 2861 } 2862 } 2863 2864 // Build a base path if necessary. 2865 if (BasePath) 2866 ::BuildBasePathArray(*Path, *BasePath); 2867 return false; 2868 } 2869 2870 if (AmbigiousBaseConvID) { 2871 // We know that the derived-to-base conversion is ambiguous, and 2872 // we're going to produce a diagnostic. Perform the derived-to-base 2873 // search just one more time to compute all of the possible paths so 2874 // that we can print them out. This is more expensive than any of 2875 // the previous derived-to-base checks we've done, but at this point 2876 // performance isn't as much of an issue. 2877 Paths.clear(); 2878 Paths.setRecordingPaths(true); 2879 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths); 2880 assert(StillOkay && "Can only be used with a derived-to-base conversion"); 2881 (void)StillOkay; 2882 2883 // Build up a textual representation of the ambiguous paths, e.g., 2884 // D -> B -> A, that will be used to illustrate the ambiguous 2885 // conversions in the diagnostic. We only print one of the paths 2886 // to each base class subobject. 2887 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2888 2889 Diag(Loc, AmbigiousBaseConvID) 2890 << Derived << Base << PathDisplayStr << Range << Name; 2891 } 2892 return true; 2893 } 2894 2895 bool 2896 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base, 2897 SourceLocation Loc, SourceRange Range, 2898 CXXCastPath *BasePath, 2899 bool IgnoreAccess) { 2900 return CheckDerivedToBaseConversion( 2901 Derived, Base, diag::err_upcast_to_inaccessible_base, 2902 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(), 2903 BasePath, IgnoreAccess); 2904 } 2905 2906 2907 /// Builds a string representing ambiguous paths from a 2908 /// specific derived class to different subobjects of the same base 2909 /// class. 2910 /// 2911 /// This function builds a string that can be used in error messages 2912 /// to show the different paths that one can take through the 2913 /// inheritance hierarchy to go from the derived class to different 2914 /// subobjects of a base class. The result looks something like this: 2915 /// @code 2916 /// struct D -> struct B -> struct A 2917 /// struct D -> struct C -> struct A 2918 /// @endcode 2919 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) { 2920 std::string PathDisplayStr; 2921 std::set<unsigned> DisplayedPaths; 2922 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 2923 Path != Paths.end(); ++Path) { 2924 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) { 2925 // We haven't displayed a path to this particular base 2926 // class subobject yet. 2927 PathDisplayStr += "\n "; 2928 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString(); 2929 for (CXXBasePath::const_iterator Element = Path->begin(); 2930 Element != Path->end(); ++Element) 2931 PathDisplayStr += " -> " + Element->Base->getType().getAsString(); 2932 } 2933 } 2934 2935 return PathDisplayStr; 2936 } 2937 2938 //===----------------------------------------------------------------------===// 2939 // C++ class member Handling 2940 //===----------------------------------------------------------------------===// 2941 2942 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon. 2943 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, 2944 SourceLocation ColonLoc, 2945 const ParsedAttributesView &Attrs) { 2946 assert(Access != AS_none && "Invalid kind for syntactic access specifier!"); 2947 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext, 2948 ASLoc, ColonLoc); 2949 CurContext->addHiddenDecl(ASDecl); 2950 return ProcessAccessDeclAttributeList(ASDecl, Attrs); 2951 } 2952 2953 /// CheckOverrideControl - Check C++11 override control semantics. 2954 void Sema::CheckOverrideControl(NamedDecl *D) { 2955 if (D->isInvalidDecl()) 2956 return; 2957 2958 // We only care about "override" and "final" declarations. 2959 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>()) 2960 return; 2961 2962 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 2963 2964 // We can't check dependent instance methods. 2965 if (MD && MD->isInstance() && 2966 (MD->getParent()->hasAnyDependentBases() || 2967 MD->getType()->isDependentType())) 2968 return; 2969 2970 if (MD && !MD->isVirtual()) { 2971 // If we have a non-virtual method, check if if hides a virtual method. 2972 // (In that case, it's most likely the method has the wrong type.) 2973 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 2974 FindHiddenVirtualMethods(MD, OverloadedMethods); 2975 2976 if (!OverloadedMethods.empty()) { 2977 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 2978 Diag(OA->getLocation(), 2979 diag::override_keyword_hides_virtual_member_function) 2980 << "override" << (OverloadedMethods.size() > 1); 2981 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 2982 Diag(FA->getLocation(), 2983 diag::override_keyword_hides_virtual_member_function) 2984 << (FA->isSpelledAsSealed() ? "sealed" : "final") 2985 << (OverloadedMethods.size() > 1); 2986 } 2987 NoteHiddenVirtualMethods(MD, OverloadedMethods); 2988 MD->setInvalidDecl(); 2989 return; 2990 } 2991 // Fall through into the general case diagnostic. 2992 // FIXME: We might want to attempt typo correction here. 2993 } 2994 2995 if (!MD || !MD->isVirtual()) { 2996 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) { 2997 Diag(OA->getLocation(), 2998 diag::override_keyword_only_allowed_on_virtual_member_functions) 2999 << "override" << FixItHint::CreateRemoval(OA->getLocation()); 3000 D->dropAttr<OverrideAttr>(); 3001 } 3002 if (FinalAttr *FA = D->getAttr<FinalAttr>()) { 3003 Diag(FA->getLocation(), 3004 diag::override_keyword_only_allowed_on_virtual_member_functions) 3005 << (FA->isSpelledAsSealed() ? "sealed" : "final") 3006 << FixItHint::CreateRemoval(FA->getLocation()); 3007 D->dropAttr<FinalAttr>(); 3008 } 3009 return; 3010 } 3011 3012 // C++11 [class.virtual]p5: 3013 // If a function is marked with the virt-specifier override and 3014 // does not override a member function of a base class, the program is 3015 // ill-formed. 3016 bool HasOverriddenMethods = MD->size_overridden_methods() != 0; 3017 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) 3018 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding) 3019 << MD->getDeclName(); 3020 } 3021 3022 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) { 3023 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>()) 3024 return; 3025 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D); 3026 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>()) 3027 return; 3028 3029 SourceLocation Loc = MD->getLocation(); 3030 SourceLocation SpellingLoc = Loc; 3031 if (getSourceManager().isMacroArgExpansion(Loc)) 3032 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin(); 3033 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc); 3034 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc)) 3035 return; 3036 3037 if (MD->size_overridden_methods() > 0) { 3038 unsigned DiagID = isa<CXXDestructorDecl>(MD) 3039 ? diag::warn_destructor_marked_not_override_overriding 3040 : diag::warn_function_marked_not_override_overriding; 3041 Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 3042 const CXXMethodDecl *OMD = *MD->begin_overridden_methods(); 3043 Diag(OMD->getLocation(), diag::note_overridden_virtual_function); 3044 } 3045 } 3046 3047 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member 3048 /// function overrides a virtual member function marked 'final', according to 3049 /// C++11 [class.virtual]p4. 3050 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 3051 const CXXMethodDecl *Old) { 3052 FinalAttr *FA = Old->getAttr<FinalAttr>(); 3053 if (!FA) 3054 return false; 3055 3056 Diag(New->getLocation(), diag::err_final_function_overridden) 3057 << New->getDeclName() 3058 << FA->isSpelledAsSealed(); 3059 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 3060 return true; 3061 } 3062 3063 static bool InitializationHasSideEffects(const FieldDecl &FD) { 3064 const Type *T = FD.getType()->getBaseElementTypeUnsafe(); 3065 // FIXME: Destruction of ObjC lifetime types has side-effects. 3066 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 3067 return !RD->isCompleteDefinition() || 3068 !RD->hasTrivialDefaultConstructor() || 3069 !RD->hasTrivialDestructor(); 3070 return false; 3071 } 3072 3073 static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) { 3074 ParsedAttributesView::const_iterator Itr = 3075 llvm::find_if(list, [](const ParsedAttr &AL) { 3076 return AL.isDeclspecPropertyAttribute(); 3077 }); 3078 if (Itr != list.end()) 3079 return &*Itr; 3080 return nullptr; 3081 } 3082 3083 // Check if there is a field shadowing. 3084 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc, 3085 DeclarationName FieldName, 3086 const CXXRecordDecl *RD, 3087 bool DeclIsField) { 3088 if (Diags.isIgnored(diag::warn_shadow_field, Loc)) 3089 return; 3090 3091 // To record a shadowed field in a base 3092 std::map<CXXRecordDecl*, NamedDecl*> Bases; 3093 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier, 3094 CXXBasePath &Path) { 3095 const auto Base = Specifier->getType()->getAsCXXRecordDecl(); 3096 // Record an ambiguous path directly 3097 if (Bases.find(Base) != Bases.end()) 3098 return true; 3099 for (const auto Field : Base->lookup(FieldName)) { 3100 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) && 3101 Field->getAccess() != AS_private) { 3102 assert(Field->getAccess() != AS_none); 3103 assert(Bases.find(Base) == Bases.end()); 3104 Bases[Base] = Field; 3105 return true; 3106 } 3107 } 3108 return false; 3109 }; 3110 3111 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3112 /*DetectVirtual=*/true); 3113 if (!RD->lookupInBases(FieldShadowed, Paths)) 3114 return; 3115 3116 for (const auto &P : Paths) { 3117 auto Base = P.back().Base->getType()->getAsCXXRecordDecl(); 3118 auto It = Bases.find(Base); 3119 // Skip duplicated bases 3120 if (It == Bases.end()) 3121 continue; 3122 auto BaseField = It->second; 3123 assert(BaseField->getAccess() != AS_private); 3124 if (AS_none != 3125 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) { 3126 Diag(Loc, diag::warn_shadow_field) 3127 << FieldName << RD << Base << DeclIsField; 3128 Diag(BaseField->getLocation(), diag::note_shadow_field); 3129 Bases.erase(It); 3130 } 3131 } 3132 } 3133 3134 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member 3135 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the 3136 /// bitfield width if there is one, 'InitExpr' specifies the initializer if 3137 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is 3138 /// present (but parsing it has been deferred). 3139 NamedDecl * 3140 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, 3141 MultiTemplateParamsArg TemplateParameterLists, 3142 Expr *BW, const VirtSpecifiers &VS, 3143 InClassInitStyle InitStyle) { 3144 const DeclSpec &DS = D.getDeclSpec(); 3145 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 3146 DeclarationName Name = NameInfo.getName(); 3147 SourceLocation Loc = NameInfo.getLoc(); 3148 3149 // For anonymous bitfields, the location should point to the type. 3150 if (Loc.isInvalid()) 3151 Loc = D.getBeginLoc(); 3152 3153 Expr *BitWidth = static_cast<Expr*>(BW); 3154 3155 assert(isa<CXXRecordDecl>(CurContext)); 3156 assert(!DS.isFriendSpecified()); 3157 3158 bool isFunc = D.isDeclarationOfFunction(); 3159 const ParsedAttr *MSPropertyAttr = 3160 getMSPropertyAttr(D.getDeclSpec().getAttributes()); 3161 3162 if (cast<CXXRecordDecl>(CurContext)->isInterface()) { 3163 // The Microsoft extension __interface only permits public member functions 3164 // and prohibits constructors, destructors, operators, non-public member 3165 // functions, static methods and data members. 3166 unsigned InvalidDecl; 3167 bool ShowDeclName = true; 3168 if (!isFunc && 3169 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr)) 3170 InvalidDecl = 0; 3171 else if (!isFunc) 3172 InvalidDecl = 1; 3173 else if (AS != AS_public) 3174 InvalidDecl = 2; 3175 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static) 3176 InvalidDecl = 3; 3177 else switch (Name.getNameKind()) { 3178 case DeclarationName::CXXConstructorName: 3179 InvalidDecl = 4; 3180 ShowDeclName = false; 3181 break; 3182 3183 case DeclarationName::CXXDestructorName: 3184 InvalidDecl = 5; 3185 ShowDeclName = false; 3186 break; 3187 3188 case DeclarationName::CXXOperatorName: 3189 case DeclarationName::CXXConversionFunctionName: 3190 InvalidDecl = 6; 3191 break; 3192 3193 default: 3194 InvalidDecl = 0; 3195 break; 3196 } 3197 3198 if (InvalidDecl) { 3199 if (ShowDeclName) 3200 Diag(Loc, diag::err_invalid_member_in_interface) 3201 << (InvalidDecl-1) << Name; 3202 else 3203 Diag(Loc, diag::err_invalid_member_in_interface) 3204 << (InvalidDecl-1) << ""; 3205 return nullptr; 3206 } 3207 } 3208 3209 // C++ 9.2p6: A member shall not be declared to have automatic storage 3210 // duration (auto, register) or with the extern storage-class-specifier. 3211 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class 3212 // data members and cannot be applied to names declared const or static, 3213 // and cannot be applied to reference members. 3214 switch (DS.getStorageClassSpec()) { 3215 case DeclSpec::SCS_unspecified: 3216 case DeclSpec::SCS_typedef: 3217 case DeclSpec::SCS_static: 3218 break; 3219 case DeclSpec::SCS_mutable: 3220 if (isFunc) { 3221 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function); 3222 3223 // FIXME: It would be nicer if the keyword was ignored only for this 3224 // declarator. Otherwise we could get follow-up errors. 3225 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3226 } 3227 break; 3228 default: 3229 Diag(DS.getStorageClassSpecLoc(), 3230 diag::err_storageclass_invalid_for_member); 3231 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3232 break; 3233 } 3234 3235 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified || 3236 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) && 3237 !isFunc); 3238 3239 if (DS.hasConstexprSpecifier() && isInstField) { 3240 SemaDiagnosticBuilder B = 3241 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member); 3242 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc(); 3243 if (InitStyle == ICIS_NoInit) { 3244 B << 0 << 0; 3245 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const) 3246 B << FixItHint::CreateRemoval(ConstexprLoc); 3247 else { 3248 B << FixItHint::CreateReplacement(ConstexprLoc, "const"); 3249 D.getMutableDeclSpec().ClearConstexprSpec(); 3250 const char *PrevSpec; 3251 unsigned DiagID; 3252 bool Failed = D.getMutableDeclSpec().SetTypeQual( 3253 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts()); 3254 (void)Failed; 3255 assert(!Failed && "Making a constexpr member const shouldn't fail"); 3256 } 3257 } else { 3258 B << 1; 3259 const char *PrevSpec; 3260 unsigned DiagID; 3261 if (D.getMutableDeclSpec().SetStorageClassSpec( 3262 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID, 3263 Context.getPrintingPolicy())) { 3264 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable && 3265 "This is the only DeclSpec that should fail to be applied"); 3266 B << 1; 3267 } else { 3268 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static "); 3269 isInstField = false; 3270 } 3271 } 3272 } 3273 3274 NamedDecl *Member; 3275 if (isInstField) { 3276 CXXScopeSpec &SS = D.getCXXScopeSpec(); 3277 3278 // Data members must have identifiers for names. 3279 if (!Name.isIdentifier()) { 3280 Diag(Loc, diag::err_bad_variable_name) 3281 << Name; 3282 return nullptr; 3283 } 3284 3285 IdentifierInfo *II = Name.getAsIdentifierInfo(); 3286 3287 // Member field could not be with "template" keyword. 3288 // So TemplateParameterLists should be empty in this case. 3289 if (TemplateParameterLists.size()) { 3290 TemplateParameterList* TemplateParams = TemplateParameterLists[0]; 3291 if (TemplateParams->size()) { 3292 // There is no such thing as a member field template. 3293 Diag(D.getIdentifierLoc(), diag::err_template_member) 3294 << II 3295 << SourceRange(TemplateParams->getTemplateLoc(), 3296 TemplateParams->getRAngleLoc()); 3297 } else { 3298 // There is an extraneous 'template<>' for this member. 3299 Diag(TemplateParams->getTemplateLoc(), 3300 diag::err_template_member_noparams) 3301 << II 3302 << SourceRange(TemplateParams->getTemplateLoc(), 3303 TemplateParams->getRAngleLoc()); 3304 } 3305 return nullptr; 3306 } 3307 3308 if (SS.isSet() && !SS.isInvalid()) { 3309 // The user provided a superfluous scope specifier inside a class 3310 // definition: 3311 // 3312 // class X { 3313 // int X::member; 3314 // }; 3315 if (DeclContext *DC = computeDeclContext(SS, false)) 3316 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(), 3317 D.getName().getKind() == 3318 UnqualifiedIdKind::IK_TemplateId); 3319 else 3320 Diag(D.getIdentifierLoc(), diag::err_member_qualification) 3321 << Name << SS.getRange(); 3322 3323 SS.clear(); 3324 } 3325 3326 if (MSPropertyAttr) { 3327 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3328 BitWidth, InitStyle, AS, *MSPropertyAttr); 3329 if (!Member) 3330 return nullptr; 3331 isInstField = false; 3332 } else { 3333 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, 3334 BitWidth, InitStyle, AS); 3335 if (!Member) 3336 return nullptr; 3337 } 3338 3339 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext)); 3340 } else { 3341 Member = HandleDeclarator(S, D, TemplateParameterLists); 3342 if (!Member) 3343 return nullptr; 3344 3345 // Non-instance-fields can't have a bitfield. 3346 if (BitWidth) { 3347 if (Member->isInvalidDecl()) { 3348 // don't emit another diagnostic. 3349 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) { 3350 // C++ 9.6p3: A bit-field shall not be a static member. 3351 // "static member 'A' cannot be a bit-field" 3352 Diag(Loc, diag::err_static_not_bitfield) 3353 << Name << BitWidth->getSourceRange(); 3354 } else if (isa<TypedefDecl>(Member)) { 3355 // "typedef member 'x' cannot be a bit-field" 3356 Diag(Loc, diag::err_typedef_not_bitfield) 3357 << Name << BitWidth->getSourceRange(); 3358 } else { 3359 // A function typedef ("typedef int f(); f a;"). 3360 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 3361 Diag(Loc, diag::err_not_integral_type_bitfield) 3362 << Name << cast<ValueDecl>(Member)->getType() 3363 << BitWidth->getSourceRange(); 3364 } 3365 3366 BitWidth = nullptr; 3367 Member->setInvalidDecl(); 3368 } 3369 3370 NamedDecl *NonTemplateMember = Member; 3371 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member)) 3372 NonTemplateMember = FunTmpl->getTemplatedDecl(); 3373 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member)) 3374 NonTemplateMember = VarTmpl->getTemplatedDecl(); 3375 3376 Member->setAccess(AS); 3377 3378 // If we have declared a member function template or static data member 3379 // template, set the access of the templated declaration as well. 3380 if (NonTemplateMember != Member) 3381 NonTemplateMember->setAccess(AS); 3382 3383 // C++ [temp.deduct.guide]p3: 3384 // A deduction guide [...] for a member class template [shall be 3385 // declared] with the same access [as the template]. 3386 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) { 3387 auto *TD = DG->getDeducedTemplate(); 3388 // Access specifiers are only meaningful if both the template and the 3389 // deduction guide are from the same scope. 3390 if (AS != TD->getAccess() && 3391 TD->getDeclContext()->getRedeclContext()->Equals( 3392 DG->getDeclContext()->getRedeclContext())) { 3393 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access); 3394 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access) 3395 << TD->getAccess(); 3396 const AccessSpecDecl *LastAccessSpec = nullptr; 3397 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) { 3398 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D)) 3399 LastAccessSpec = AccessSpec; 3400 } 3401 assert(LastAccessSpec && "differing access with no access specifier"); 3402 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access) 3403 << AS; 3404 } 3405 } 3406 } 3407 3408 if (VS.isOverrideSpecified()) 3409 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(), 3410 AttributeCommonInfo::AS_Keyword)); 3411 if (VS.isFinalSpecified()) 3412 Member->addAttr(FinalAttr::Create( 3413 Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword, 3414 static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed()))); 3415 3416 if (VS.getLastLocation().isValid()) { 3417 // Update the end location of a method that has a virt-specifiers. 3418 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member)) 3419 MD->setRangeEnd(VS.getLastLocation()); 3420 } 3421 3422 CheckOverrideControl(Member); 3423 3424 assert((Name || isInstField) && "No identifier for non-field ?"); 3425 3426 if (isInstField) { 3427 FieldDecl *FD = cast<FieldDecl>(Member); 3428 FieldCollector->Add(FD); 3429 3430 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) { 3431 // Remember all explicit private FieldDecls that have a name, no side 3432 // effects and are not part of a dependent type declaration. 3433 if (!FD->isImplicit() && FD->getDeclName() && 3434 FD->getAccess() == AS_private && 3435 !FD->hasAttr<UnusedAttr>() && 3436 !FD->getParent()->isDependentContext() && 3437 !InitializationHasSideEffects(*FD)) 3438 UnusedPrivateFields.insert(FD); 3439 } 3440 } 3441 3442 return Member; 3443 } 3444 3445 namespace { 3446 class UninitializedFieldVisitor 3447 : public EvaluatedExprVisitor<UninitializedFieldVisitor> { 3448 Sema &S; 3449 // List of Decls to generate a warning on. Also remove Decls that become 3450 // initialized. 3451 llvm::SmallPtrSetImpl<ValueDecl*> &Decls; 3452 // List of base classes of the record. Classes are removed after their 3453 // initializers. 3454 llvm::SmallPtrSetImpl<QualType> &BaseClasses; 3455 // Vector of decls to be removed from the Decl set prior to visiting the 3456 // nodes. These Decls may have been initialized in the prior initializer. 3457 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove; 3458 // If non-null, add a note to the warning pointing back to the constructor. 3459 const CXXConstructorDecl *Constructor; 3460 // Variables to hold state when processing an initializer list. When 3461 // InitList is true, special case initialization of FieldDecls matching 3462 // InitListFieldDecl. 3463 bool InitList; 3464 FieldDecl *InitListFieldDecl; 3465 llvm::SmallVector<unsigned, 4> InitFieldIndex; 3466 3467 public: 3468 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited; 3469 UninitializedFieldVisitor(Sema &S, 3470 llvm::SmallPtrSetImpl<ValueDecl*> &Decls, 3471 llvm::SmallPtrSetImpl<QualType> &BaseClasses) 3472 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses), 3473 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {} 3474 3475 // Returns true if the use of ME is not an uninitialized use. 3476 bool IsInitListMemberExprInitialized(MemberExpr *ME, 3477 bool CheckReferenceOnly) { 3478 llvm::SmallVector<FieldDecl*, 4> Fields; 3479 bool ReferenceField = false; 3480 while (ME) { 3481 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 3482 if (!FD) 3483 return false; 3484 Fields.push_back(FD); 3485 if (FD->getType()->isReferenceType()) 3486 ReferenceField = true; 3487 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts()); 3488 } 3489 3490 // Binding a reference to an uninitialized field is not an 3491 // uninitialized use. 3492 if (CheckReferenceOnly && !ReferenceField) 3493 return true; 3494 3495 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 3496 // Discard the first field since it is the field decl that is being 3497 // initialized. 3498 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) { 3499 UsedFieldIndex.push_back((*I)->getFieldIndex()); 3500 } 3501 3502 for (auto UsedIter = UsedFieldIndex.begin(), 3503 UsedEnd = UsedFieldIndex.end(), 3504 OrigIter = InitFieldIndex.begin(), 3505 OrigEnd = InitFieldIndex.end(); 3506 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 3507 if (*UsedIter < *OrigIter) 3508 return true; 3509 if (*UsedIter > *OrigIter) 3510 break; 3511 } 3512 3513 return false; 3514 } 3515 3516 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly, 3517 bool AddressOf) { 3518 if (isa<EnumConstantDecl>(ME->getMemberDecl())) 3519 return; 3520 3521 // FieldME is the inner-most MemberExpr that is not an anonymous struct 3522 // or union. 3523 MemberExpr *FieldME = ME; 3524 3525 bool AllPODFields = FieldME->getType().isPODType(S.Context); 3526 3527 Expr *Base = ME; 3528 while (MemberExpr *SubME = 3529 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) { 3530 3531 if (isa<VarDecl>(SubME->getMemberDecl())) 3532 return; 3533 3534 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl())) 3535 if (!FD->isAnonymousStructOrUnion()) 3536 FieldME = SubME; 3537 3538 if (!FieldME->getType().isPODType(S.Context)) 3539 AllPODFields = false; 3540 3541 Base = SubME->getBase(); 3542 } 3543 3544 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) 3545 return; 3546 3547 if (AddressOf && AllPODFields) 3548 return; 3549 3550 ValueDecl* FoundVD = FieldME->getMemberDecl(); 3551 3552 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) { 3553 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) { 3554 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr()); 3555 } 3556 3557 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) { 3558 QualType T = BaseCast->getType(); 3559 if (T->isPointerType() && 3560 BaseClasses.count(T->getPointeeType())) { 3561 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit) 3562 << T->getPointeeType() << FoundVD; 3563 } 3564 } 3565 } 3566 3567 if (!Decls.count(FoundVD)) 3568 return; 3569 3570 const bool IsReference = FoundVD->getType()->isReferenceType(); 3571 3572 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) { 3573 // Special checking for initializer lists. 3574 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) { 3575 return; 3576 } 3577 } else { 3578 // Prevent double warnings on use of unbounded references. 3579 if (CheckReferenceOnly && !IsReference) 3580 return; 3581 } 3582 3583 unsigned diag = IsReference 3584 ? diag::warn_reference_field_is_uninit 3585 : diag::warn_field_is_uninit; 3586 S.Diag(FieldME->getExprLoc(), diag) << FoundVD; 3587 if (Constructor) 3588 S.Diag(Constructor->getLocation(), 3589 diag::note_uninit_in_this_constructor) 3590 << (Constructor->isDefaultConstructor() && Constructor->isImplicit()); 3591 3592 } 3593 3594 void HandleValue(Expr *E, bool AddressOf) { 3595 E = E->IgnoreParens(); 3596 3597 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 3598 HandleMemberExpr(ME, false /*CheckReferenceOnly*/, 3599 AddressOf /*AddressOf*/); 3600 return; 3601 } 3602 3603 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 3604 Visit(CO->getCond()); 3605 HandleValue(CO->getTrueExpr(), AddressOf); 3606 HandleValue(CO->getFalseExpr(), AddressOf); 3607 return; 3608 } 3609 3610 if (BinaryConditionalOperator *BCO = 3611 dyn_cast<BinaryConditionalOperator>(E)) { 3612 Visit(BCO->getCond()); 3613 HandleValue(BCO->getFalseExpr(), AddressOf); 3614 return; 3615 } 3616 3617 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 3618 HandleValue(OVE->getSourceExpr(), AddressOf); 3619 return; 3620 } 3621 3622 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 3623 switch (BO->getOpcode()) { 3624 default: 3625 break; 3626 case(BO_PtrMemD): 3627 case(BO_PtrMemI): 3628 HandleValue(BO->getLHS(), AddressOf); 3629 Visit(BO->getRHS()); 3630 return; 3631 case(BO_Comma): 3632 Visit(BO->getLHS()); 3633 HandleValue(BO->getRHS(), AddressOf); 3634 return; 3635 } 3636 } 3637 3638 Visit(E); 3639 } 3640 3641 void CheckInitListExpr(InitListExpr *ILE) { 3642 InitFieldIndex.push_back(0); 3643 for (auto Child : ILE->children()) { 3644 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) { 3645 CheckInitListExpr(SubList); 3646 } else { 3647 Visit(Child); 3648 } 3649 ++InitFieldIndex.back(); 3650 } 3651 InitFieldIndex.pop_back(); 3652 } 3653 3654 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor, 3655 FieldDecl *Field, const Type *BaseClass) { 3656 // Remove Decls that may have been initialized in the previous 3657 // initializer. 3658 for (ValueDecl* VD : DeclsToRemove) 3659 Decls.erase(VD); 3660 DeclsToRemove.clear(); 3661 3662 Constructor = FieldConstructor; 3663 InitListExpr *ILE = dyn_cast<InitListExpr>(E); 3664 3665 if (ILE && Field) { 3666 InitList = true; 3667 InitListFieldDecl = Field; 3668 InitFieldIndex.clear(); 3669 CheckInitListExpr(ILE); 3670 } else { 3671 InitList = false; 3672 Visit(E); 3673 } 3674 3675 if (Field) 3676 Decls.erase(Field); 3677 if (BaseClass) 3678 BaseClasses.erase(BaseClass->getCanonicalTypeInternal()); 3679 } 3680 3681 void VisitMemberExpr(MemberExpr *ME) { 3682 // All uses of unbounded reference fields will warn. 3683 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/); 3684 } 3685 3686 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 3687 if (E->getCastKind() == CK_LValueToRValue) { 3688 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3689 return; 3690 } 3691 3692 Inherited::VisitImplicitCastExpr(E); 3693 } 3694 3695 void VisitCXXConstructExpr(CXXConstructExpr *E) { 3696 if (E->getConstructor()->isCopyConstructor()) { 3697 Expr *ArgExpr = E->getArg(0); 3698 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 3699 if (ILE->getNumInits() == 1) 3700 ArgExpr = ILE->getInit(0); 3701 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 3702 if (ICE->getCastKind() == CK_NoOp) 3703 ArgExpr = ICE->getSubExpr(); 3704 HandleValue(ArgExpr, false /*AddressOf*/); 3705 return; 3706 } 3707 Inherited::VisitCXXConstructExpr(E); 3708 } 3709 3710 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 3711 Expr *Callee = E->getCallee(); 3712 if (isa<MemberExpr>(Callee)) { 3713 HandleValue(Callee, false /*AddressOf*/); 3714 for (auto Arg : E->arguments()) 3715 Visit(Arg); 3716 return; 3717 } 3718 3719 Inherited::VisitCXXMemberCallExpr(E); 3720 } 3721 3722 void VisitCallExpr(CallExpr *E) { 3723 // Treat std::move as a use. 3724 if (E->isCallToStdMove()) { 3725 HandleValue(E->getArg(0), /*AddressOf=*/false); 3726 return; 3727 } 3728 3729 Inherited::VisitCallExpr(E); 3730 } 3731 3732 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 3733 Expr *Callee = E->getCallee(); 3734 3735 if (isa<UnresolvedLookupExpr>(Callee)) 3736 return Inherited::VisitCXXOperatorCallExpr(E); 3737 3738 Visit(Callee); 3739 for (auto Arg : E->arguments()) 3740 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/); 3741 } 3742 3743 void VisitBinaryOperator(BinaryOperator *E) { 3744 // If a field assignment is detected, remove the field from the 3745 // uninitiailized field set. 3746 if (E->getOpcode() == BO_Assign) 3747 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS())) 3748 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 3749 if (!FD->getType()->isReferenceType()) 3750 DeclsToRemove.push_back(FD); 3751 3752 if (E->isCompoundAssignmentOp()) { 3753 HandleValue(E->getLHS(), false /*AddressOf*/); 3754 Visit(E->getRHS()); 3755 return; 3756 } 3757 3758 Inherited::VisitBinaryOperator(E); 3759 } 3760 3761 void VisitUnaryOperator(UnaryOperator *E) { 3762 if (E->isIncrementDecrementOp()) { 3763 HandleValue(E->getSubExpr(), false /*AddressOf*/); 3764 return; 3765 } 3766 if (E->getOpcode() == UO_AddrOf) { 3767 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) { 3768 HandleValue(ME->getBase(), true /*AddressOf*/); 3769 return; 3770 } 3771 } 3772 3773 Inherited::VisitUnaryOperator(E); 3774 } 3775 }; 3776 3777 // Diagnose value-uses of fields to initialize themselves, e.g. 3778 // foo(foo) 3779 // where foo is not also a parameter to the constructor. 3780 // Also diagnose across field uninitialized use such as 3781 // x(y), y(x) 3782 // TODO: implement -Wuninitialized and fold this into that framework. 3783 static void DiagnoseUninitializedFields( 3784 Sema &SemaRef, const CXXConstructorDecl *Constructor) { 3785 3786 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit, 3787 Constructor->getLocation())) { 3788 return; 3789 } 3790 3791 if (Constructor->isInvalidDecl()) 3792 return; 3793 3794 const CXXRecordDecl *RD = Constructor->getParent(); 3795 3796 if (RD->getDescribedClassTemplate()) 3797 return; 3798 3799 // Holds fields that are uninitialized. 3800 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields; 3801 3802 // At the beginning, all fields are uninitialized. 3803 for (auto *I : RD->decls()) { 3804 if (auto *FD = dyn_cast<FieldDecl>(I)) { 3805 UninitializedFields.insert(FD); 3806 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) { 3807 UninitializedFields.insert(IFD->getAnonField()); 3808 } 3809 } 3810 3811 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses; 3812 for (auto I : RD->bases()) 3813 UninitializedBaseClasses.insert(I.getType().getCanonicalType()); 3814 3815 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3816 return; 3817 3818 UninitializedFieldVisitor UninitializedChecker(SemaRef, 3819 UninitializedFields, 3820 UninitializedBaseClasses); 3821 3822 for (const auto *FieldInit : Constructor->inits()) { 3823 if (UninitializedFields.empty() && UninitializedBaseClasses.empty()) 3824 break; 3825 3826 Expr *InitExpr = FieldInit->getInit(); 3827 if (!InitExpr) 3828 continue; 3829 3830 if (CXXDefaultInitExpr *Default = 3831 dyn_cast<CXXDefaultInitExpr>(InitExpr)) { 3832 InitExpr = Default->getExpr(); 3833 if (!InitExpr) 3834 continue; 3835 // In class initializers will point to the constructor. 3836 UninitializedChecker.CheckInitializer(InitExpr, Constructor, 3837 FieldInit->getAnyMember(), 3838 FieldInit->getBaseClass()); 3839 } else { 3840 UninitializedChecker.CheckInitializer(InitExpr, nullptr, 3841 FieldInit->getAnyMember(), 3842 FieldInit->getBaseClass()); 3843 } 3844 } 3845 } 3846 } // namespace 3847 3848 /// Enter a new C++ default initializer scope. After calling this, the 3849 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if 3850 /// parsing or instantiating the initializer failed. 3851 void Sema::ActOnStartCXXInClassMemberInitializer() { 3852 // Create a synthetic function scope to represent the call to the constructor 3853 // that notionally surrounds a use of this initializer. 3854 PushFunctionScope(); 3855 } 3856 3857 /// This is invoked after parsing an in-class initializer for a 3858 /// non-static C++ class member, and after instantiating an in-class initializer 3859 /// in a class template. Such actions are deferred until the class is complete. 3860 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D, 3861 SourceLocation InitLoc, 3862 Expr *InitExpr) { 3863 // Pop the notional constructor scope we created earlier. 3864 PopFunctionScopeInfo(nullptr, D); 3865 3866 FieldDecl *FD = dyn_cast<FieldDecl>(D); 3867 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) && 3868 "must set init style when field is created"); 3869 3870 if (!InitExpr) { 3871 D->setInvalidDecl(); 3872 if (FD) 3873 FD->removeInClassInitializer(); 3874 return; 3875 } 3876 3877 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) { 3878 FD->setInvalidDecl(); 3879 FD->removeInClassInitializer(); 3880 return; 3881 } 3882 3883 ExprResult Init = InitExpr; 3884 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) { 3885 InitializedEntity Entity = 3886 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD); 3887 InitializationKind Kind = 3888 FD->getInClassInitStyle() == ICIS_ListInit 3889 ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(), 3890 InitExpr->getBeginLoc(), 3891 InitExpr->getEndLoc()) 3892 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc); 3893 InitializationSequence Seq(*this, Entity, Kind, InitExpr); 3894 Init = Seq.Perform(*this, Entity, Kind, InitExpr); 3895 if (Init.isInvalid()) { 3896 FD->setInvalidDecl(); 3897 return; 3898 } 3899 } 3900 3901 // C++11 [class.base.init]p7: 3902 // The initialization of each base and member constitutes a 3903 // full-expression. 3904 Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false); 3905 if (Init.isInvalid()) { 3906 FD->setInvalidDecl(); 3907 return; 3908 } 3909 3910 InitExpr = Init.get(); 3911 3912 FD->setInClassInitializer(InitExpr); 3913 } 3914 3915 /// Find the direct and/or virtual base specifiers that 3916 /// correspond to the given base type, for use in base initialization 3917 /// within a constructor. 3918 static bool FindBaseInitializer(Sema &SemaRef, 3919 CXXRecordDecl *ClassDecl, 3920 QualType BaseType, 3921 const CXXBaseSpecifier *&DirectBaseSpec, 3922 const CXXBaseSpecifier *&VirtualBaseSpec) { 3923 // First, check for a direct base class. 3924 DirectBaseSpec = nullptr; 3925 for (const auto &Base : ClassDecl->bases()) { 3926 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) { 3927 // We found a direct base of this type. That's what we're 3928 // initializing. 3929 DirectBaseSpec = &Base; 3930 break; 3931 } 3932 } 3933 3934 // Check for a virtual base class. 3935 // FIXME: We might be able to short-circuit this if we know in advance that 3936 // there are no virtual bases. 3937 VirtualBaseSpec = nullptr; 3938 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) { 3939 // We haven't found a base yet; search the class hierarchy for a 3940 // virtual base class. 3941 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3942 /*DetectVirtual=*/false); 3943 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(), 3944 SemaRef.Context.getTypeDeclType(ClassDecl), 3945 BaseType, Paths)) { 3946 for (CXXBasePaths::paths_iterator Path = Paths.begin(); 3947 Path != Paths.end(); ++Path) { 3948 if (Path->back().Base->isVirtual()) { 3949 VirtualBaseSpec = Path->back().Base; 3950 break; 3951 } 3952 } 3953 } 3954 } 3955 3956 return DirectBaseSpec || VirtualBaseSpec; 3957 } 3958 3959 /// Handle a C++ member initializer using braced-init-list syntax. 3960 MemInitResult 3961 Sema::ActOnMemInitializer(Decl *ConstructorD, 3962 Scope *S, 3963 CXXScopeSpec &SS, 3964 IdentifierInfo *MemberOrBase, 3965 ParsedType TemplateTypeTy, 3966 const DeclSpec &DS, 3967 SourceLocation IdLoc, 3968 Expr *InitList, 3969 SourceLocation EllipsisLoc) { 3970 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 3971 DS, IdLoc, InitList, 3972 EllipsisLoc); 3973 } 3974 3975 /// Handle a C++ member initializer using parentheses syntax. 3976 MemInitResult 3977 Sema::ActOnMemInitializer(Decl *ConstructorD, 3978 Scope *S, 3979 CXXScopeSpec &SS, 3980 IdentifierInfo *MemberOrBase, 3981 ParsedType TemplateTypeTy, 3982 const DeclSpec &DS, 3983 SourceLocation IdLoc, 3984 SourceLocation LParenLoc, 3985 ArrayRef<Expr *> Args, 3986 SourceLocation RParenLoc, 3987 SourceLocation EllipsisLoc) { 3988 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc); 3989 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy, 3990 DS, IdLoc, List, EllipsisLoc); 3991 } 3992 3993 namespace { 3994 3995 // Callback to only accept typo corrections that can be a valid C++ member 3996 // intializer: either a non-static field member or a base class. 3997 class MemInitializerValidatorCCC final : public CorrectionCandidateCallback { 3998 public: 3999 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl) 4000 : ClassDecl(ClassDecl) {} 4001 4002 bool ValidateCandidate(const TypoCorrection &candidate) override { 4003 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 4004 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND)) 4005 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl); 4006 return isa<TypeDecl>(ND); 4007 } 4008 return false; 4009 } 4010 4011 std::unique_ptr<CorrectionCandidateCallback> clone() override { 4012 return std::make_unique<MemInitializerValidatorCCC>(*this); 4013 } 4014 4015 private: 4016 CXXRecordDecl *ClassDecl; 4017 }; 4018 4019 } 4020 4021 ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, 4022 CXXScopeSpec &SS, 4023 ParsedType TemplateTypeTy, 4024 IdentifierInfo *MemberOrBase) { 4025 if (SS.getScopeRep() || TemplateTypeTy) 4026 return nullptr; 4027 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase); 4028 if (Result.empty()) 4029 return nullptr; 4030 ValueDecl *Member; 4031 if ((Member = dyn_cast<FieldDecl>(Result.front())) || 4032 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) 4033 return Member; 4034 return nullptr; 4035 } 4036 4037 /// Handle a C++ member initializer. 4038 MemInitResult 4039 Sema::BuildMemInitializer(Decl *ConstructorD, 4040 Scope *S, 4041 CXXScopeSpec &SS, 4042 IdentifierInfo *MemberOrBase, 4043 ParsedType TemplateTypeTy, 4044 const DeclSpec &DS, 4045 SourceLocation IdLoc, 4046 Expr *Init, 4047 SourceLocation EllipsisLoc) { 4048 ExprResult Res = CorrectDelayedTyposInExpr(Init); 4049 if (!Res.isUsable()) 4050 return true; 4051 Init = Res.get(); 4052 4053 if (!ConstructorD) 4054 return true; 4055 4056 AdjustDeclIfTemplate(ConstructorD); 4057 4058 CXXConstructorDecl *Constructor 4059 = dyn_cast<CXXConstructorDecl>(ConstructorD); 4060 if (!Constructor) { 4061 // The user wrote a constructor initializer on a function that is 4062 // not a C++ constructor. Ignore the error for now, because we may 4063 // have more member initializers coming; we'll diagnose it just 4064 // once in ActOnMemInitializers. 4065 return true; 4066 } 4067 4068 CXXRecordDecl *ClassDecl = Constructor->getParent(); 4069 4070 // C++ [class.base.init]p2: 4071 // Names in a mem-initializer-id are looked up in the scope of the 4072 // constructor's class and, if not found in that scope, are looked 4073 // up in the scope containing the constructor's definition. 4074 // [Note: if the constructor's class contains a member with the 4075 // same name as a direct or virtual base class of the class, a 4076 // mem-initializer-id naming the member or base class and composed 4077 // of a single identifier refers to the class member. A 4078 // mem-initializer-id for the hidden base class may be specified 4079 // using a qualified name. ] 4080 4081 // Look for a member, first. 4082 if (ValueDecl *Member = tryLookupCtorInitMemberDecl( 4083 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) { 4084 if (EllipsisLoc.isValid()) 4085 Diag(EllipsisLoc, diag::err_pack_expansion_member_init) 4086 << MemberOrBase 4087 << SourceRange(IdLoc, Init->getSourceRange().getEnd()); 4088 4089 return BuildMemberInitializer(Member, Init, IdLoc); 4090 } 4091 // It didn't name a member, so see if it names a class. 4092 QualType BaseType; 4093 TypeSourceInfo *TInfo = nullptr; 4094 4095 if (TemplateTypeTy) { 4096 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo); 4097 if (BaseType.isNull()) 4098 return true; 4099 } else if (DS.getTypeSpecType() == TST_decltype) { 4100 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 4101 } else if (DS.getTypeSpecType() == TST_decltype_auto) { 4102 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); 4103 return true; 4104 } else { 4105 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName); 4106 LookupParsedName(R, S, &SS); 4107 4108 TypeDecl *TyD = R.getAsSingle<TypeDecl>(); 4109 if (!TyD) { 4110 if (R.isAmbiguous()) return true; 4111 4112 // We don't want access-control diagnostics here. 4113 R.suppressDiagnostics(); 4114 4115 if (SS.isSet() && isDependentScopeSpecifier(SS)) { 4116 bool NotUnknownSpecialization = false; 4117 DeclContext *DC = computeDeclContext(SS, false); 4118 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC)) 4119 NotUnknownSpecialization = !Record->hasAnyDependentBases(); 4120 4121 if (!NotUnknownSpecialization) { 4122 // When the scope specifier can refer to a member of an unknown 4123 // specialization, we take it as a type name. 4124 BaseType = CheckTypenameType(ETK_None, SourceLocation(), 4125 SS.getWithLocInContext(Context), 4126 *MemberOrBase, IdLoc); 4127 if (BaseType.isNull()) 4128 return true; 4129 4130 TInfo = Context.CreateTypeSourceInfo(BaseType); 4131 DependentNameTypeLoc TL = 4132 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>(); 4133 if (!TL.isNull()) { 4134 TL.setNameLoc(IdLoc); 4135 TL.setElaboratedKeywordLoc(SourceLocation()); 4136 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4137 } 4138 4139 R.clear(); 4140 R.setLookupName(MemberOrBase); 4141 } 4142 } 4143 4144 // If no results were found, try to correct typos. 4145 TypoCorrection Corr; 4146 MemInitializerValidatorCCC CCC(ClassDecl); 4147 if (R.empty() && BaseType.isNull() && 4148 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, 4149 CCC, CTK_ErrorRecovery, ClassDecl))) { 4150 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) { 4151 // We have found a non-static data member with a similar 4152 // name to what was typed; complain and initialize that 4153 // member. 4154 diagnoseTypo(Corr, 4155 PDiag(diag::err_mem_init_not_member_or_class_suggest) 4156 << MemberOrBase << true); 4157 return BuildMemberInitializer(Member, Init, IdLoc); 4158 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) { 4159 const CXXBaseSpecifier *DirectBaseSpec; 4160 const CXXBaseSpecifier *VirtualBaseSpec; 4161 if (FindBaseInitializer(*this, ClassDecl, 4162 Context.getTypeDeclType(Type), 4163 DirectBaseSpec, VirtualBaseSpec)) { 4164 // We have found a direct or virtual base class with a 4165 // similar name to what was typed; complain and initialize 4166 // that base class. 4167 diagnoseTypo(Corr, 4168 PDiag(diag::err_mem_init_not_member_or_class_suggest) 4169 << MemberOrBase << false, 4170 PDiag() /*Suppress note, we provide our own.*/); 4171 4172 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec 4173 : VirtualBaseSpec; 4174 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here) 4175 << BaseSpec->getType() << BaseSpec->getSourceRange(); 4176 4177 TyD = Type; 4178 } 4179 } 4180 } 4181 4182 if (!TyD && BaseType.isNull()) { 4183 Diag(IdLoc, diag::err_mem_init_not_member_or_class) 4184 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd()); 4185 return true; 4186 } 4187 } 4188 4189 if (BaseType.isNull()) { 4190 BaseType = Context.getTypeDeclType(TyD); 4191 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false); 4192 if (SS.isSet()) { 4193 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(), 4194 BaseType); 4195 TInfo = Context.CreateTypeSourceInfo(BaseType); 4196 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>(); 4197 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc); 4198 TL.setElaboratedKeywordLoc(SourceLocation()); 4199 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 4200 } 4201 } 4202 } 4203 4204 if (!TInfo) 4205 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc); 4206 4207 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc); 4208 } 4209 4210 MemInitResult 4211 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init, 4212 SourceLocation IdLoc) { 4213 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member); 4214 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member); 4215 assert((DirectMember || IndirectMember) && 4216 "Member must be a FieldDecl or IndirectFieldDecl"); 4217 4218 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4219 return true; 4220 4221 if (Member->isInvalidDecl()) 4222 return true; 4223 4224 MultiExprArg Args; 4225 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4226 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4227 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 4228 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); 4229 } else { 4230 // Template instantiation doesn't reconstruct ParenListExprs for us. 4231 Args = Init; 4232 } 4233 4234 SourceRange InitRange = Init->getSourceRange(); 4235 4236 if (Member->getType()->isDependentType() || Init->isTypeDependent()) { 4237 // Can't check initialization for a member of dependent type or when 4238 // any of the arguments are type-dependent expressions. 4239 DiscardCleanupsInEvaluationContext(); 4240 } else { 4241 bool InitList = false; 4242 if (isa<InitListExpr>(Init)) { 4243 InitList = true; 4244 Args = Init; 4245 } 4246 4247 // Initialize the member. 4248 InitializedEntity MemberEntity = 4249 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr) 4250 : InitializedEntity::InitializeMember(IndirectMember, 4251 nullptr); 4252 InitializationKind Kind = 4253 InitList ? InitializationKind::CreateDirectList( 4254 IdLoc, Init->getBeginLoc(), Init->getEndLoc()) 4255 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(), 4256 InitRange.getEnd()); 4257 4258 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args); 4259 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args, 4260 nullptr); 4261 if (MemberInit.isInvalid()) 4262 return true; 4263 4264 // C++11 [class.base.init]p7: 4265 // The initialization of each base and member constitutes a 4266 // full-expression. 4267 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(), 4268 /*DiscardedValue*/ false); 4269 if (MemberInit.isInvalid()) 4270 return true; 4271 4272 Init = MemberInit.get(); 4273 } 4274 4275 if (DirectMember) { 4276 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc, 4277 InitRange.getBegin(), Init, 4278 InitRange.getEnd()); 4279 } else { 4280 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc, 4281 InitRange.getBegin(), Init, 4282 InitRange.getEnd()); 4283 } 4284 } 4285 4286 MemInitResult 4287 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, 4288 CXXRecordDecl *ClassDecl) { 4289 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4290 if (!LangOpts.CPlusPlus11) 4291 return Diag(NameLoc, diag::err_delegating_ctor) 4292 << TInfo->getTypeLoc().getLocalSourceRange(); 4293 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor); 4294 4295 bool InitList = true; 4296 MultiExprArg Args = Init; 4297 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4298 InitList = false; 4299 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4300 } 4301 4302 SourceRange InitRange = Init->getSourceRange(); 4303 // Initialize the object. 4304 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation( 4305 QualType(ClassDecl->getTypeForDecl(), 0)); 4306 InitializationKind Kind = 4307 InitList ? InitializationKind::CreateDirectList( 4308 NameLoc, Init->getBeginLoc(), Init->getEndLoc()) 4309 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(), 4310 InitRange.getEnd()); 4311 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args); 4312 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind, 4313 Args, nullptr); 4314 if (DelegationInit.isInvalid()) 4315 return true; 4316 4317 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() && 4318 "Delegating constructor with no target?"); 4319 4320 // C++11 [class.base.init]p7: 4321 // The initialization of each base and member constitutes a 4322 // full-expression. 4323 DelegationInit = ActOnFinishFullExpr( 4324 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false); 4325 if (DelegationInit.isInvalid()) 4326 return true; 4327 4328 // If we are in a dependent context, template instantiation will 4329 // perform this type-checking again. Just save the arguments that we 4330 // received in a ParenListExpr. 4331 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4332 // of the information that we have about the base 4333 // initializer. However, deconstructing the ASTs is a dicey process, 4334 // and this approach is far more likely to get the corner cases right. 4335 if (CurContext->isDependentContext()) 4336 DelegationInit = Init; 4337 4338 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(), 4339 DelegationInit.getAs<Expr>(), 4340 InitRange.getEnd()); 4341 } 4342 4343 MemInitResult 4344 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, 4345 Expr *Init, CXXRecordDecl *ClassDecl, 4346 SourceLocation EllipsisLoc) { 4347 SourceLocation BaseLoc 4348 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin(); 4349 4350 if (!BaseType->isDependentType() && !BaseType->isRecordType()) 4351 return Diag(BaseLoc, diag::err_base_init_does_not_name_class) 4352 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4353 4354 // C++ [class.base.init]p2: 4355 // [...] Unless the mem-initializer-id names a nonstatic data 4356 // member of the constructor's class or a direct or virtual base 4357 // of that class, the mem-initializer is ill-formed. A 4358 // mem-initializer-list can initialize a base class using any 4359 // name that denotes that base class type. 4360 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent(); 4361 4362 SourceRange InitRange = Init->getSourceRange(); 4363 if (EllipsisLoc.isValid()) { 4364 // This is a pack expansion. 4365 if (!BaseType->containsUnexpandedParameterPack()) { 4366 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 4367 << SourceRange(BaseLoc, InitRange.getEnd()); 4368 4369 EllipsisLoc = SourceLocation(); 4370 } 4371 } else { 4372 // Check for any unexpanded parameter packs. 4373 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer)) 4374 return true; 4375 4376 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) 4377 return true; 4378 } 4379 4380 // Check for direct and virtual base classes. 4381 const CXXBaseSpecifier *DirectBaseSpec = nullptr; 4382 const CXXBaseSpecifier *VirtualBaseSpec = nullptr; 4383 if (!Dependent) { 4384 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0), 4385 BaseType)) 4386 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl); 4387 4388 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec, 4389 VirtualBaseSpec); 4390 4391 // C++ [base.class.init]p2: 4392 // Unless the mem-initializer-id names a nonstatic data member of the 4393 // constructor's class or a direct or virtual base of that class, the 4394 // mem-initializer is ill-formed. 4395 if (!DirectBaseSpec && !VirtualBaseSpec) { 4396 // If the class has any dependent bases, then it's possible that 4397 // one of those types will resolve to the same type as 4398 // BaseType. Therefore, just treat this as a dependent base 4399 // class initialization. FIXME: Should we try to check the 4400 // initialization anyway? It seems odd. 4401 if (ClassDecl->hasAnyDependentBases()) 4402 Dependent = true; 4403 else 4404 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual) 4405 << BaseType << Context.getTypeDeclType(ClassDecl) 4406 << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4407 } 4408 } 4409 4410 if (Dependent) { 4411 DiscardCleanupsInEvaluationContext(); 4412 4413 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4414 /*IsVirtual=*/false, 4415 InitRange.getBegin(), Init, 4416 InitRange.getEnd(), EllipsisLoc); 4417 } 4418 4419 // C++ [base.class.init]p2: 4420 // If a mem-initializer-id is ambiguous because it designates both 4421 // a direct non-virtual base class and an inherited virtual base 4422 // class, the mem-initializer is ill-formed. 4423 if (DirectBaseSpec && VirtualBaseSpec) 4424 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual) 4425 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange(); 4426 4427 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec; 4428 if (!BaseSpec) 4429 BaseSpec = VirtualBaseSpec; 4430 4431 // Initialize the base. 4432 bool InitList = true; 4433 MultiExprArg Args = Init; 4434 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) { 4435 InitList = false; 4436 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs()); 4437 } 4438 4439 InitializedEntity BaseEntity = 4440 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec); 4441 InitializationKind Kind = 4442 InitList ? InitializationKind::CreateDirectList(BaseLoc) 4443 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(), 4444 InitRange.getEnd()); 4445 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args); 4446 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr); 4447 if (BaseInit.isInvalid()) 4448 return true; 4449 4450 // C++11 [class.base.init]p7: 4451 // The initialization of each base and member constitutes a 4452 // full-expression. 4453 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(), 4454 /*DiscardedValue*/ false); 4455 if (BaseInit.isInvalid()) 4456 return true; 4457 4458 // If we are in a dependent context, template instantiation will 4459 // perform this type-checking again. Just save the arguments that we 4460 // received in a ParenListExpr. 4461 // FIXME: This isn't quite ideal, since our ASTs don't capture all 4462 // of the information that we have about the base 4463 // initializer. However, deconstructing the ASTs is a dicey process, 4464 // and this approach is far more likely to get the corner cases right. 4465 if (CurContext->isDependentContext()) 4466 BaseInit = Init; 4467 4468 return new (Context) CXXCtorInitializer(Context, BaseTInfo, 4469 BaseSpec->isVirtual(), 4470 InitRange.getBegin(), 4471 BaseInit.getAs<Expr>(), 4472 InitRange.getEnd(), EllipsisLoc); 4473 } 4474 4475 // Create a static_cast\<T&&>(expr). 4476 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) { 4477 if (T.isNull()) T = E->getType(); 4478 QualType TargetType = SemaRef.BuildReferenceType( 4479 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName()); 4480 SourceLocation ExprLoc = E->getBeginLoc(); 4481 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo( 4482 TargetType, ExprLoc); 4483 4484 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 4485 SourceRange(ExprLoc, ExprLoc), 4486 E->getSourceRange()).get(); 4487 } 4488 4489 /// ImplicitInitializerKind - How an implicit base or member initializer should 4490 /// initialize its base or member. 4491 enum ImplicitInitializerKind { 4492 IIK_Default, 4493 IIK_Copy, 4494 IIK_Move, 4495 IIK_Inherit 4496 }; 4497 4498 static bool 4499 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4500 ImplicitInitializerKind ImplicitInitKind, 4501 CXXBaseSpecifier *BaseSpec, 4502 bool IsInheritedVirtualBase, 4503 CXXCtorInitializer *&CXXBaseInit) { 4504 InitializedEntity InitEntity 4505 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec, 4506 IsInheritedVirtualBase); 4507 4508 ExprResult BaseInit; 4509 4510 switch (ImplicitInitKind) { 4511 case IIK_Inherit: 4512 case IIK_Default: { 4513 InitializationKind InitKind 4514 = InitializationKind::CreateDefault(Constructor->getLocation()); 4515 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4516 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4517 break; 4518 } 4519 4520 case IIK_Move: 4521 case IIK_Copy: { 4522 bool Moving = ImplicitInitKind == IIK_Move; 4523 ParmVarDecl *Param = Constructor->getParamDecl(0); 4524 QualType ParamType = Param->getType().getNonReferenceType(); 4525 4526 Expr *CopyCtorArg = 4527 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4528 SourceLocation(), Param, false, 4529 Constructor->getLocation(), ParamType, 4530 VK_LValue, nullptr); 4531 4532 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg)); 4533 4534 // Cast to the base class to avoid ambiguities. 4535 QualType ArgTy = 4536 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(), 4537 ParamType.getQualifiers()); 4538 4539 if (Moving) { 4540 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg); 4541 } 4542 4543 CXXCastPath BasePath; 4544 BasePath.push_back(BaseSpec); 4545 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy, 4546 CK_UncheckedDerivedToBase, 4547 Moving ? VK_XValue : VK_LValue, 4548 &BasePath).get(); 4549 4550 InitializationKind InitKind 4551 = InitializationKind::CreateDirect(Constructor->getLocation(), 4552 SourceLocation(), SourceLocation()); 4553 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg); 4554 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg); 4555 break; 4556 } 4557 } 4558 4559 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit); 4560 if (BaseInit.isInvalid()) 4561 return true; 4562 4563 CXXBaseInit = 4564 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4565 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(), 4566 SourceLocation()), 4567 BaseSpec->isVirtual(), 4568 SourceLocation(), 4569 BaseInit.getAs<Expr>(), 4570 SourceLocation(), 4571 SourceLocation()); 4572 4573 return false; 4574 } 4575 4576 static bool RefersToRValueRef(Expr *MemRef) { 4577 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl(); 4578 return Referenced->getType()->isRValueReferenceType(); 4579 } 4580 4581 static bool 4582 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor, 4583 ImplicitInitializerKind ImplicitInitKind, 4584 FieldDecl *Field, IndirectFieldDecl *Indirect, 4585 CXXCtorInitializer *&CXXMemberInit) { 4586 if (Field->isInvalidDecl()) 4587 return true; 4588 4589 SourceLocation Loc = Constructor->getLocation(); 4590 4591 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) { 4592 bool Moving = ImplicitInitKind == IIK_Move; 4593 ParmVarDecl *Param = Constructor->getParamDecl(0); 4594 QualType ParamType = Param->getType().getNonReferenceType(); 4595 4596 // Suppress copying zero-width bitfields. 4597 if (Field->isZeroLengthBitField(SemaRef.Context)) 4598 return false; 4599 4600 Expr *MemberExprBase = 4601 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), 4602 SourceLocation(), Param, false, 4603 Loc, ParamType, VK_LValue, nullptr); 4604 4605 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase)); 4606 4607 if (Moving) { 4608 MemberExprBase = CastForMoving(SemaRef, MemberExprBase); 4609 } 4610 4611 // Build a reference to this field within the parameter. 4612 CXXScopeSpec SS; 4613 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc, 4614 Sema::LookupMemberName); 4615 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect) 4616 : cast<ValueDecl>(Field), AS_public); 4617 MemberLookup.resolveKind(); 4618 ExprResult CtorArg 4619 = SemaRef.BuildMemberReferenceExpr(MemberExprBase, 4620 ParamType, Loc, 4621 /*IsArrow=*/false, 4622 SS, 4623 /*TemplateKWLoc=*/SourceLocation(), 4624 /*FirstQualifierInScope=*/nullptr, 4625 MemberLookup, 4626 /*TemplateArgs=*/nullptr, 4627 /*S*/nullptr); 4628 if (CtorArg.isInvalid()) 4629 return true; 4630 4631 // C++11 [class.copy]p15: 4632 // - if a member m has rvalue reference type T&&, it is direct-initialized 4633 // with static_cast<T&&>(x.m); 4634 if (RefersToRValueRef(CtorArg.get())) { 4635 CtorArg = CastForMoving(SemaRef, CtorArg.get()); 4636 } 4637 4638 InitializedEntity Entity = 4639 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4640 /*Implicit*/ true) 4641 : InitializedEntity::InitializeMember(Field, nullptr, 4642 /*Implicit*/ true); 4643 4644 // Direct-initialize to use the copy constructor. 4645 InitializationKind InitKind = 4646 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation()); 4647 4648 Expr *CtorArgE = CtorArg.getAs<Expr>(); 4649 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE); 4650 ExprResult MemberInit = 4651 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1)); 4652 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4653 if (MemberInit.isInvalid()) 4654 return true; 4655 4656 if (Indirect) 4657 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4658 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4659 else 4660 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer( 4661 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc); 4662 return false; 4663 } 4664 4665 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) && 4666 "Unhandled implicit init kind!"); 4667 4668 QualType FieldBaseElementType = 4669 SemaRef.Context.getBaseElementType(Field->getType()); 4670 4671 if (FieldBaseElementType->isRecordType()) { 4672 InitializedEntity InitEntity = 4673 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr, 4674 /*Implicit*/ true) 4675 : InitializedEntity::InitializeMember(Field, nullptr, 4676 /*Implicit*/ true); 4677 InitializationKind InitKind = 4678 InitializationKind::CreateDefault(Loc); 4679 4680 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None); 4681 ExprResult MemberInit = 4682 InitSeq.Perform(SemaRef, InitEntity, InitKind, None); 4683 4684 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit); 4685 if (MemberInit.isInvalid()) 4686 return true; 4687 4688 if (Indirect) 4689 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4690 Indirect, Loc, 4691 Loc, 4692 MemberInit.get(), 4693 Loc); 4694 else 4695 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, 4696 Field, Loc, Loc, 4697 MemberInit.get(), 4698 Loc); 4699 return false; 4700 } 4701 4702 if (!Field->getParent()->isUnion()) { 4703 if (FieldBaseElementType->isReferenceType()) { 4704 SemaRef.Diag(Constructor->getLocation(), 4705 diag::err_uninitialized_member_in_ctor) 4706 << (int)Constructor->isImplicit() 4707 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4708 << 0 << Field->getDeclName(); 4709 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4710 return true; 4711 } 4712 4713 if (FieldBaseElementType.isConstQualified()) { 4714 SemaRef.Diag(Constructor->getLocation(), 4715 diag::err_uninitialized_member_in_ctor) 4716 << (int)Constructor->isImplicit() 4717 << SemaRef.Context.getTagDeclType(Constructor->getParent()) 4718 << 1 << Field->getDeclName(); 4719 SemaRef.Diag(Field->getLocation(), diag::note_declared_at); 4720 return true; 4721 } 4722 } 4723 4724 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) { 4725 // ARC and Weak: 4726 // Default-initialize Objective-C pointers to NULL. 4727 CXXMemberInit 4728 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field, 4729 Loc, Loc, 4730 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()), 4731 Loc); 4732 return false; 4733 } 4734 4735 // Nothing to initialize. 4736 CXXMemberInit = nullptr; 4737 return false; 4738 } 4739 4740 namespace { 4741 struct BaseAndFieldInfo { 4742 Sema &S; 4743 CXXConstructorDecl *Ctor; 4744 bool AnyErrorsInInits; 4745 ImplicitInitializerKind IIK; 4746 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields; 4747 SmallVector<CXXCtorInitializer*, 8> AllToInit; 4748 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember; 4749 4750 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits) 4751 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) { 4752 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted(); 4753 if (Ctor->getInheritedConstructor()) 4754 IIK = IIK_Inherit; 4755 else if (Generated && Ctor->isCopyConstructor()) 4756 IIK = IIK_Copy; 4757 else if (Generated && Ctor->isMoveConstructor()) 4758 IIK = IIK_Move; 4759 else 4760 IIK = IIK_Default; 4761 } 4762 4763 bool isImplicitCopyOrMove() const { 4764 switch (IIK) { 4765 case IIK_Copy: 4766 case IIK_Move: 4767 return true; 4768 4769 case IIK_Default: 4770 case IIK_Inherit: 4771 return false; 4772 } 4773 4774 llvm_unreachable("Invalid ImplicitInitializerKind!"); 4775 } 4776 4777 bool addFieldInitializer(CXXCtorInitializer *Init) { 4778 AllToInit.push_back(Init); 4779 4780 // Check whether this initializer makes the field "used". 4781 if (Init->getInit()->HasSideEffects(S.Context)) 4782 S.UnusedPrivateFields.remove(Init->getAnyMember()); 4783 4784 return false; 4785 } 4786 4787 bool isInactiveUnionMember(FieldDecl *Field) { 4788 RecordDecl *Record = Field->getParent(); 4789 if (!Record->isUnion()) 4790 return false; 4791 4792 if (FieldDecl *Active = 4793 ActiveUnionMember.lookup(Record->getCanonicalDecl())) 4794 return Active != Field->getCanonicalDecl(); 4795 4796 // In an implicit copy or move constructor, ignore any in-class initializer. 4797 if (isImplicitCopyOrMove()) 4798 return true; 4799 4800 // If there's no explicit initialization, the field is active only if it 4801 // has an in-class initializer... 4802 if (Field->hasInClassInitializer()) 4803 return false; 4804 // ... or it's an anonymous struct or union whose class has an in-class 4805 // initializer. 4806 if (!Field->isAnonymousStructOrUnion()) 4807 return true; 4808 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl(); 4809 return !FieldRD->hasInClassInitializer(); 4810 } 4811 4812 /// Determine whether the given field is, or is within, a union member 4813 /// that is inactive (because there was an initializer given for a different 4814 /// member of the union, or because the union was not initialized at all). 4815 bool isWithinInactiveUnionMember(FieldDecl *Field, 4816 IndirectFieldDecl *Indirect) { 4817 if (!Indirect) 4818 return isInactiveUnionMember(Field); 4819 4820 for (auto *C : Indirect->chain()) { 4821 FieldDecl *Field = dyn_cast<FieldDecl>(C); 4822 if (Field && isInactiveUnionMember(Field)) 4823 return true; 4824 } 4825 return false; 4826 } 4827 }; 4828 } 4829 4830 /// Determine whether the given type is an incomplete or zero-lenfgth 4831 /// array type. 4832 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) { 4833 if (T->isIncompleteArrayType()) 4834 return true; 4835 4836 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) { 4837 if (!ArrayT->getSize()) 4838 return true; 4839 4840 T = ArrayT->getElementType(); 4841 } 4842 4843 return false; 4844 } 4845 4846 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info, 4847 FieldDecl *Field, 4848 IndirectFieldDecl *Indirect = nullptr) { 4849 if (Field->isInvalidDecl()) 4850 return false; 4851 4852 // Overwhelmingly common case: we have a direct initializer for this field. 4853 if (CXXCtorInitializer *Init = 4854 Info.AllBaseFields.lookup(Field->getCanonicalDecl())) 4855 return Info.addFieldInitializer(Init); 4856 4857 // C++11 [class.base.init]p8: 4858 // if the entity is a non-static data member that has a 4859 // brace-or-equal-initializer and either 4860 // -- the constructor's class is a union and no other variant member of that 4861 // union is designated by a mem-initializer-id or 4862 // -- the constructor's class is not a union, and, if the entity is a member 4863 // of an anonymous union, no other member of that union is designated by 4864 // a mem-initializer-id, 4865 // the entity is initialized as specified in [dcl.init]. 4866 // 4867 // We also apply the same rules to handle anonymous structs within anonymous 4868 // unions. 4869 if (Info.isWithinInactiveUnionMember(Field, Indirect)) 4870 return false; 4871 4872 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) { 4873 ExprResult DIE = 4874 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field); 4875 if (DIE.isInvalid()) 4876 return true; 4877 4878 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true); 4879 SemaRef.checkInitializerLifetime(Entity, DIE.get()); 4880 4881 CXXCtorInitializer *Init; 4882 if (Indirect) 4883 Init = new (SemaRef.Context) 4884 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(), 4885 SourceLocation(), DIE.get(), SourceLocation()); 4886 else 4887 Init = new (SemaRef.Context) 4888 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(), 4889 SourceLocation(), DIE.get(), SourceLocation()); 4890 return Info.addFieldInitializer(Init); 4891 } 4892 4893 // Don't initialize incomplete or zero-length arrays. 4894 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType())) 4895 return false; 4896 4897 // Don't try to build an implicit initializer if there were semantic 4898 // errors in any of the initializers (and therefore we might be 4899 // missing some that the user actually wrote). 4900 if (Info.AnyErrorsInInits) 4901 return false; 4902 4903 CXXCtorInitializer *Init = nullptr; 4904 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, 4905 Indirect, Init)) 4906 return true; 4907 4908 if (!Init) 4909 return false; 4910 4911 return Info.addFieldInitializer(Init); 4912 } 4913 4914 bool 4915 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor, 4916 CXXCtorInitializer *Initializer) { 4917 assert(Initializer->isDelegatingInitializer()); 4918 Constructor->setNumCtorInitializers(1); 4919 CXXCtorInitializer **initializer = 4920 new (Context) CXXCtorInitializer*[1]; 4921 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*)); 4922 Constructor->setCtorInitializers(initializer); 4923 4924 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) { 4925 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor); 4926 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation()); 4927 } 4928 4929 DelegatingCtorDecls.push_back(Constructor); 4930 4931 DiagnoseUninitializedFields(*this, Constructor); 4932 4933 return false; 4934 } 4935 4936 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 4937 ArrayRef<CXXCtorInitializer *> Initializers) { 4938 if (Constructor->isDependentContext()) { 4939 // Just store the initializers as written, they will be checked during 4940 // instantiation. 4941 if (!Initializers.empty()) { 4942 Constructor->setNumCtorInitializers(Initializers.size()); 4943 CXXCtorInitializer **baseOrMemberInitializers = 4944 new (Context) CXXCtorInitializer*[Initializers.size()]; 4945 memcpy(baseOrMemberInitializers, Initializers.data(), 4946 Initializers.size() * sizeof(CXXCtorInitializer*)); 4947 Constructor->setCtorInitializers(baseOrMemberInitializers); 4948 } 4949 4950 // Let template instantiation know whether we had errors. 4951 if (AnyErrors) 4952 Constructor->setInvalidDecl(); 4953 4954 return false; 4955 } 4956 4957 BaseAndFieldInfo Info(*this, Constructor, AnyErrors); 4958 4959 // We need to build the initializer AST according to order of construction 4960 // and not what user specified in the Initializers list. 4961 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition(); 4962 if (!ClassDecl) 4963 return true; 4964 4965 bool HadError = false; 4966 4967 for (unsigned i = 0; i < Initializers.size(); i++) { 4968 CXXCtorInitializer *Member = Initializers[i]; 4969 4970 if (Member->isBaseInitializer()) 4971 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member; 4972 else { 4973 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member; 4974 4975 if (IndirectFieldDecl *F = Member->getIndirectMember()) { 4976 for (auto *C : F->chain()) { 4977 FieldDecl *FD = dyn_cast<FieldDecl>(C); 4978 if (FD && FD->getParent()->isUnion()) 4979 Info.ActiveUnionMember.insert(std::make_pair( 4980 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 4981 } 4982 } else if (FieldDecl *FD = Member->getMember()) { 4983 if (FD->getParent()->isUnion()) 4984 Info.ActiveUnionMember.insert(std::make_pair( 4985 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl())); 4986 } 4987 } 4988 } 4989 4990 // Keep track of the direct virtual bases. 4991 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases; 4992 for (auto &I : ClassDecl->bases()) { 4993 if (I.isVirtual()) 4994 DirectVBases.insert(&I); 4995 } 4996 4997 // Push virtual bases before others. 4998 for (auto &VBase : ClassDecl->vbases()) { 4999 if (CXXCtorInitializer *Value 5000 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) { 5001 // [class.base.init]p7, per DR257: 5002 // A mem-initializer where the mem-initializer-id names a virtual base 5003 // class is ignored during execution of a constructor of any class that 5004 // is not the most derived class. 5005 if (ClassDecl->isAbstract()) { 5006 // FIXME: Provide a fixit to remove the base specifier. This requires 5007 // tracking the location of the associated comma for a base specifier. 5008 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored) 5009 << VBase.getType() << ClassDecl; 5010 DiagnoseAbstractType(ClassDecl); 5011 } 5012 5013 Info.AllToInit.push_back(Value); 5014 } else if (!AnyErrors && !ClassDecl->isAbstract()) { 5015 // [class.base.init]p8, per DR257: 5016 // If a given [...] base class is not named by a mem-initializer-id 5017 // [...] and the entity is not a virtual base class of an abstract 5018 // class, then [...] the entity is default-initialized. 5019 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase); 5020 CXXCtorInitializer *CXXBaseInit; 5021 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 5022 &VBase, IsInheritedVirtualBase, 5023 CXXBaseInit)) { 5024 HadError = true; 5025 continue; 5026 } 5027 5028 Info.AllToInit.push_back(CXXBaseInit); 5029 } 5030 } 5031 5032 // Non-virtual bases. 5033 for (auto &Base : ClassDecl->bases()) { 5034 // Virtuals are in the virtual base list and already constructed. 5035 if (Base.isVirtual()) 5036 continue; 5037 5038 if (CXXCtorInitializer *Value 5039 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) { 5040 Info.AllToInit.push_back(Value); 5041 } else if (!AnyErrors) { 5042 CXXCtorInitializer *CXXBaseInit; 5043 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK, 5044 &Base, /*IsInheritedVirtualBase=*/false, 5045 CXXBaseInit)) { 5046 HadError = true; 5047 continue; 5048 } 5049 5050 Info.AllToInit.push_back(CXXBaseInit); 5051 } 5052 } 5053 5054 // Fields. 5055 for (auto *Mem : ClassDecl->decls()) { 5056 if (auto *F = dyn_cast<FieldDecl>(Mem)) { 5057 // C++ [class.bit]p2: 5058 // A declaration for a bit-field that omits the identifier declares an 5059 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 5060 // initialized. 5061 if (F->isUnnamedBitfield()) 5062 continue; 5063 5064 // If we're not generating the implicit copy/move constructor, then we'll 5065 // handle anonymous struct/union fields based on their individual 5066 // indirect fields. 5067 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove()) 5068 continue; 5069 5070 if (CollectFieldInitializer(*this, Info, F)) 5071 HadError = true; 5072 continue; 5073 } 5074 5075 // Beyond this point, we only consider default initialization. 5076 if (Info.isImplicitCopyOrMove()) 5077 continue; 5078 5079 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) { 5080 if (F->getType()->isIncompleteArrayType()) { 5081 assert(ClassDecl->hasFlexibleArrayMember() && 5082 "Incomplete array type is not valid"); 5083 continue; 5084 } 5085 5086 // Initialize each field of an anonymous struct individually. 5087 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F)) 5088 HadError = true; 5089 5090 continue; 5091 } 5092 } 5093 5094 unsigned NumInitializers = Info.AllToInit.size(); 5095 if (NumInitializers > 0) { 5096 Constructor->setNumCtorInitializers(NumInitializers); 5097 CXXCtorInitializer **baseOrMemberInitializers = 5098 new (Context) CXXCtorInitializer*[NumInitializers]; 5099 memcpy(baseOrMemberInitializers, Info.AllToInit.data(), 5100 NumInitializers * sizeof(CXXCtorInitializer*)); 5101 Constructor->setCtorInitializers(baseOrMemberInitializers); 5102 5103 // Constructors implicitly reference the base and member 5104 // destructors. 5105 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(), 5106 Constructor->getParent()); 5107 } 5108 5109 return HadError; 5110 } 5111 5112 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) { 5113 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) { 5114 const RecordDecl *RD = RT->getDecl(); 5115 if (RD->isAnonymousStructOrUnion()) { 5116 for (auto *Field : RD->fields()) 5117 PopulateKeysForFields(Field, IdealInits); 5118 return; 5119 } 5120 } 5121 IdealInits.push_back(Field->getCanonicalDecl()); 5122 } 5123 5124 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) { 5125 return Context.getCanonicalType(BaseType).getTypePtr(); 5126 } 5127 5128 static const void *GetKeyForMember(ASTContext &Context, 5129 CXXCtorInitializer *Member) { 5130 if (!Member->isAnyMemberInitializer()) 5131 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0)); 5132 5133 return Member->getAnyMember()->getCanonicalDecl(); 5134 } 5135 5136 static void DiagnoseBaseOrMemInitializerOrder( 5137 Sema &SemaRef, const CXXConstructorDecl *Constructor, 5138 ArrayRef<CXXCtorInitializer *> Inits) { 5139 if (Constructor->getDeclContext()->isDependentContext()) 5140 return; 5141 5142 // Don't check initializers order unless the warning is enabled at the 5143 // location of at least one initializer. 5144 bool ShouldCheckOrder = false; 5145 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 5146 CXXCtorInitializer *Init = Inits[InitIndex]; 5147 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order, 5148 Init->getSourceLocation())) { 5149 ShouldCheckOrder = true; 5150 break; 5151 } 5152 } 5153 if (!ShouldCheckOrder) 5154 return; 5155 5156 // Build the list of bases and members in the order that they'll 5157 // actually be initialized. The explicit initializers should be in 5158 // this same order but may be missing things. 5159 SmallVector<const void*, 32> IdealInitKeys; 5160 5161 const CXXRecordDecl *ClassDecl = Constructor->getParent(); 5162 5163 // 1. Virtual bases. 5164 for (const auto &VBase : ClassDecl->vbases()) 5165 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType())); 5166 5167 // 2. Non-virtual bases. 5168 for (const auto &Base : ClassDecl->bases()) { 5169 if (Base.isVirtual()) 5170 continue; 5171 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType())); 5172 } 5173 5174 // 3. Direct fields. 5175 for (auto *Field : ClassDecl->fields()) { 5176 if (Field->isUnnamedBitfield()) 5177 continue; 5178 5179 PopulateKeysForFields(Field, IdealInitKeys); 5180 } 5181 5182 unsigned NumIdealInits = IdealInitKeys.size(); 5183 unsigned IdealIndex = 0; 5184 5185 CXXCtorInitializer *PrevInit = nullptr; 5186 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) { 5187 CXXCtorInitializer *Init = Inits[InitIndex]; 5188 const void *InitKey = GetKeyForMember(SemaRef.Context, Init); 5189 5190 // Scan forward to try to find this initializer in the idealized 5191 // initializers list. 5192 for (; IdealIndex != NumIdealInits; ++IdealIndex) 5193 if (InitKey == IdealInitKeys[IdealIndex]) 5194 break; 5195 5196 // If we didn't find this initializer, it must be because we 5197 // scanned past it on a previous iteration. That can only 5198 // happen if we're out of order; emit a warning. 5199 if (IdealIndex == NumIdealInits && PrevInit) { 5200 Sema::SemaDiagnosticBuilder D = 5201 SemaRef.Diag(PrevInit->getSourceLocation(), 5202 diag::warn_initializer_out_of_order); 5203 5204 if (PrevInit->isAnyMemberInitializer()) 5205 D << 0 << PrevInit->getAnyMember()->getDeclName(); 5206 else 5207 D << 1 << PrevInit->getTypeSourceInfo()->getType(); 5208 5209 if (Init->isAnyMemberInitializer()) 5210 D << 0 << Init->getAnyMember()->getDeclName(); 5211 else 5212 D << 1 << Init->getTypeSourceInfo()->getType(); 5213 5214 // Move back to the initializer's location in the ideal list. 5215 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex) 5216 if (InitKey == IdealInitKeys[IdealIndex]) 5217 break; 5218 5219 assert(IdealIndex < NumIdealInits && 5220 "initializer not found in initializer list"); 5221 } 5222 5223 PrevInit = Init; 5224 } 5225 } 5226 5227 namespace { 5228 bool CheckRedundantInit(Sema &S, 5229 CXXCtorInitializer *Init, 5230 CXXCtorInitializer *&PrevInit) { 5231 if (!PrevInit) { 5232 PrevInit = Init; 5233 return false; 5234 } 5235 5236 if (FieldDecl *Field = Init->getAnyMember()) 5237 S.Diag(Init->getSourceLocation(), 5238 diag::err_multiple_mem_initialization) 5239 << Field->getDeclName() 5240 << Init->getSourceRange(); 5241 else { 5242 const Type *BaseClass = Init->getBaseClass(); 5243 assert(BaseClass && "neither field nor base"); 5244 S.Diag(Init->getSourceLocation(), 5245 diag::err_multiple_base_initialization) 5246 << QualType(BaseClass, 0) 5247 << Init->getSourceRange(); 5248 } 5249 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer) 5250 << 0 << PrevInit->getSourceRange(); 5251 5252 return true; 5253 } 5254 5255 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry; 5256 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap; 5257 5258 bool CheckRedundantUnionInit(Sema &S, 5259 CXXCtorInitializer *Init, 5260 RedundantUnionMap &Unions) { 5261 FieldDecl *Field = Init->getAnyMember(); 5262 RecordDecl *Parent = Field->getParent(); 5263 NamedDecl *Child = Field; 5264 5265 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) { 5266 if (Parent->isUnion()) { 5267 UnionEntry &En = Unions[Parent]; 5268 if (En.first && En.first != Child) { 5269 S.Diag(Init->getSourceLocation(), 5270 diag::err_multiple_mem_union_initialization) 5271 << Field->getDeclName() 5272 << Init->getSourceRange(); 5273 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer) 5274 << 0 << En.second->getSourceRange(); 5275 return true; 5276 } 5277 if (!En.first) { 5278 En.first = Child; 5279 En.second = Init; 5280 } 5281 if (!Parent->isAnonymousStructOrUnion()) 5282 return false; 5283 } 5284 5285 Child = Parent; 5286 Parent = cast<RecordDecl>(Parent->getDeclContext()); 5287 } 5288 5289 return false; 5290 } 5291 } 5292 5293 /// ActOnMemInitializers - Handle the member initializers for a constructor. 5294 void Sema::ActOnMemInitializers(Decl *ConstructorDecl, 5295 SourceLocation ColonLoc, 5296 ArrayRef<CXXCtorInitializer*> MemInits, 5297 bool AnyErrors) { 5298 if (!ConstructorDecl) 5299 return; 5300 5301 AdjustDeclIfTemplate(ConstructorDecl); 5302 5303 CXXConstructorDecl *Constructor 5304 = dyn_cast<CXXConstructorDecl>(ConstructorDecl); 5305 5306 if (!Constructor) { 5307 Diag(ColonLoc, diag::err_only_constructors_take_base_inits); 5308 return; 5309 } 5310 5311 // Mapping for the duplicate initializers check. 5312 // For member initializers, this is keyed with a FieldDecl*. 5313 // For base initializers, this is keyed with a Type*. 5314 llvm::DenseMap<const void *, CXXCtorInitializer *> Members; 5315 5316 // Mapping for the inconsistent anonymous-union initializers check. 5317 RedundantUnionMap MemberUnions; 5318 5319 bool HadError = false; 5320 for (unsigned i = 0; i < MemInits.size(); i++) { 5321 CXXCtorInitializer *Init = MemInits[i]; 5322 5323 // Set the source order index. 5324 Init->setSourceOrder(i); 5325 5326 if (Init->isAnyMemberInitializer()) { 5327 const void *Key = GetKeyForMember(Context, Init); 5328 if (CheckRedundantInit(*this, Init, Members[Key]) || 5329 CheckRedundantUnionInit(*this, Init, MemberUnions)) 5330 HadError = true; 5331 } else if (Init->isBaseInitializer()) { 5332 const void *Key = GetKeyForMember(Context, Init); 5333 if (CheckRedundantInit(*this, Init, Members[Key])) 5334 HadError = true; 5335 } else { 5336 assert(Init->isDelegatingInitializer()); 5337 // This must be the only initializer 5338 if (MemInits.size() != 1) { 5339 Diag(Init->getSourceLocation(), 5340 diag::err_delegating_initializer_alone) 5341 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange(); 5342 // We will treat this as being the only initializer. 5343 } 5344 SetDelegatingInitializer(Constructor, MemInits[i]); 5345 // Return immediately as the initializer is set. 5346 return; 5347 } 5348 } 5349 5350 if (HadError) 5351 return; 5352 5353 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits); 5354 5355 SetCtorInitializers(Constructor, AnyErrors, MemInits); 5356 5357 DiagnoseUninitializedFields(*this, Constructor); 5358 } 5359 5360 void 5361 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location, 5362 CXXRecordDecl *ClassDecl) { 5363 // Ignore dependent contexts. Also ignore unions, since their members never 5364 // have destructors implicitly called. 5365 if (ClassDecl->isDependentContext() || ClassDecl->isUnion()) 5366 return; 5367 5368 // FIXME: all the access-control diagnostics are positioned on the 5369 // field/base declaration. That's probably good; that said, the 5370 // user might reasonably want to know why the destructor is being 5371 // emitted, and we currently don't say. 5372 5373 // Non-static data members. 5374 for (auto *Field : ClassDecl->fields()) { 5375 if (Field->isInvalidDecl()) 5376 continue; 5377 5378 // Don't destroy incomplete or zero-length arrays. 5379 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType())) 5380 continue; 5381 5382 QualType FieldType = Context.getBaseElementType(Field->getType()); 5383 5384 const RecordType* RT = FieldType->getAs<RecordType>(); 5385 if (!RT) 5386 continue; 5387 5388 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5389 if (FieldClassDecl->isInvalidDecl()) 5390 continue; 5391 if (FieldClassDecl->hasIrrelevantDestructor()) 5392 continue; 5393 // The destructor for an implicit anonymous union member is never invoked. 5394 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 5395 continue; 5396 5397 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl); 5398 assert(Dtor && "No dtor found for FieldClassDecl!"); 5399 CheckDestructorAccess(Field->getLocation(), Dtor, 5400 PDiag(diag::err_access_dtor_field) 5401 << Field->getDeclName() 5402 << FieldType); 5403 5404 MarkFunctionReferenced(Location, Dtor); 5405 DiagnoseUseOfDecl(Dtor, Location); 5406 } 5407 5408 // We only potentially invoke the destructors of potentially constructed 5409 // subobjects. 5410 bool VisitVirtualBases = !ClassDecl->isAbstract(); 5411 5412 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases; 5413 5414 // Bases. 5415 for (const auto &Base : ClassDecl->bases()) { 5416 // Bases are always records in a well-formed non-dependent class. 5417 const RecordType *RT = Base.getType()->getAs<RecordType>(); 5418 5419 // Remember direct virtual bases. 5420 if (Base.isVirtual()) { 5421 if (!VisitVirtualBases) 5422 continue; 5423 DirectVirtualBases.insert(RT); 5424 } 5425 5426 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5427 // If our base class is invalid, we probably can't get its dtor anyway. 5428 if (BaseClassDecl->isInvalidDecl()) 5429 continue; 5430 if (BaseClassDecl->hasIrrelevantDestructor()) 5431 continue; 5432 5433 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5434 assert(Dtor && "No dtor found for BaseClassDecl!"); 5435 5436 // FIXME: caret should be on the start of the class name 5437 CheckDestructorAccess(Base.getBeginLoc(), Dtor, 5438 PDiag(diag::err_access_dtor_base) 5439 << Base.getType() << Base.getSourceRange(), 5440 Context.getTypeDeclType(ClassDecl)); 5441 5442 MarkFunctionReferenced(Location, Dtor); 5443 DiagnoseUseOfDecl(Dtor, Location); 5444 } 5445 5446 if (!VisitVirtualBases) 5447 return; 5448 5449 // Virtual bases. 5450 for (const auto &VBase : ClassDecl->vbases()) { 5451 // Bases are always records in a well-formed non-dependent class. 5452 const RecordType *RT = VBase.getType()->castAs<RecordType>(); 5453 5454 // Ignore direct virtual bases. 5455 if (DirectVirtualBases.count(RT)) 5456 continue; 5457 5458 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 5459 // If our base class is invalid, we probably can't get its dtor anyway. 5460 if (BaseClassDecl->isInvalidDecl()) 5461 continue; 5462 if (BaseClassDecl->hasIrrelevantDestructor()) 5463 continue; 5464 5465 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl); 5466 assert(Dtor && "No dtor found for BaseClassDecl!"); 5467 if (CheckDestructorAccess( 5468 ClassDecl->getLocation(), Dtor, 5469 PDiag(diag::err_access_dtor_vbase) 5470 << Context.getTypeDeclType(ClassDecl) << VBase.getType(), 5471 Context.getTypeDeclType(ClassDecl)) == 5472 AR_accessible) { 5473 CheckDerivedToBaseConversion( 5474 Context.getTypeDeclType(ClassDecl), VBase.getType(), 5475 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(), 5476 SourceRange(), DeclarationName(), nullptr); 5477 } 5478 5479 MarkFunctionReferenced(Location, Dtor); 5480 DiagnoseUseOfDecl(Dtor, Location); 5481 } 5482 } 5483 5484 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) { 5485 if (!CDtorDecl) 5486 return; 5487 5488 if (CXXConstructorDecl *Constructor 5489 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) { 5490 SetCtorInitializers(Constructor, /*AnyErrors=*/false); 5491 DiagnoseUninitializedFields(*this, Constructor); 5492 } 5493 } 5494 5495 bool Sema::isAbstractType(SourceLocation Loc, QualType T) { 5496 if (!getLangOpts().CPlusPlus) 5497 return false; 5498 5499 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl(); 5500 if (!RD) 5501 return false; 5502 5503 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a 5504 // class template specialization here, but doing so breaks a lot of code. 5505 5506 // We can't answer whether something is abstract until it has a 5507 // definition. If it's currently being defined, we'll walk back 5508 // over all the declarations when we have a full definition. 5509 const CXXRecordDecl *Def = RD->getDefinition(); 5510 if (!Def || Def->isBeingDefined()) 5511 return false; 5512 5513 return RD->isAbstract(); 5514 } 5515 5516 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T, 5517 TypeDiagnoser &Diagnoser) { 5518 if (!isAbstractType(Loc, T)) 5519 return false; 5520 5521 T = Context.getBaseElementType(T); 5522 Diagnoser.diagnose(*this, Loc, T); 5523 DiagnoseAbstractType(T->getAsCXXRecordDecl()); 5524 return true; 5525 } 5526 5527 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) { 5528 // Check if we've already emitted the list of pure virtual functions 5529 // for this class. 5530 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD)) 5531 return; 5532 5533 // If the diagnostic is suppressed, don't emit the notes. We're only 5534 // going to emit them once, so try to attach them to a diagnostic we're 5535 // actually going to show. 5536 if (Diags.isLastDiagnosticIgnored()) 5537 return; 5538 5539 CXXFinalOverriderMap FinalOverriders; 5540 RD->getFinalOverriders(FinalOverriders); 5541 5542 // Keep a set of seen pure methods so we won't diagnose the same method 5543 // more than once. 5544 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods; 5545 5546 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 5547 MEnd = FinalOverriders.end(); 5548 M != MEnd; 5549 ++M) { 5550 for (OverridingMethods::iterator SO = M->second.begin(), 5551 SOEnd = M->second.end(); 5552 SO != SOEnd; ++SO) { 5553 // C++ [class.abstract]p4: 5554 // A class is abstract if it contains or inherits at least one 5555 // pure virtual function for which the final overrider is pure 5556 // virtual. 5557 5558 // 5559 if (SO->second.size() != 1) 5560 continue; 5561 5562 if (!SO->second.front().Method->isPure()) 5563 continue; 5564 5565 if (!SeenPureMethods.insert(SO->second.front().Method).second) 5566 continue; 5567 5568 Diag(SO->second.front().Method->getLocation(), 5569 diag::note_pure_virtual_function) 5570 << SO->second.front().Method->getDeclName() << RD->getDeclName(); 5571 } 5572 } 5573 5574 if (!PureVirtualClassDiagSet) 5575 PureVirtualClassDiagSet.reset(new RecordDeclSetTy); 5576 PureVirtualClassDiagSet->insert(RD); 5577 } 5578 5579 namespace { 5580 struct AbstractUsageInfo { 5581 Sema &S; 5582 CXXRecordDecl *Record; 5583 CanQualType AbstractType; 5584 bool Invalid; 5585 5586 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record) 5587 : S(S), Record(Record), 5588 AbstractType(S.Context.getCanonicalType( 5589 S.Context.getTypeDeclType(Record))), 5590 Invalid(false) {} 5591 5592 void DiagnoseAbstractType() { 5593 if (Invalid) return; 5594 S.DiagnoseAbstractType(Record); 5595 Invalid = true; 5596 } 5597 5598 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel); 5599 }; 5600 5601 struct CheckAbstractUsage { 5602 AbstractUsageInfo &Info; 5603 const NamedDecl *Ctx; 5604 5605 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx) 5606 : Info(Info), Ctx(Ctx) {} 5607 5608 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5609 switch (TL.getTypeLocClass()) { 5610 #define ABSTRACT_TYPELOC(CLASS, PARENT) 5611 #define TYPELOC(CLASS, PARENT) \ 5612 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break; 5613 #include "clang/AST/TypeLocNodes.def" 5614 } 5615 } 5616 5617 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5618 Visit(TL.getReturnLoc(), Sema::AbstractReturnType); 5619 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) { 5620 if (!TL.getParam(I)) 5621 continue; 5622 5623 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo(); 5624 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType); 5625 } 5626 } 5627 5628 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5629 Visit(TL.getElementLoc(), Sema::AbstractArrayType); 5630 } 5631 5632 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) { 5633 // Visit the type parameters from a permissive context. 5634 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) { 5635 TemplateArgumentLoc TAL = TL.getArgLoc(I); 5636 if (TAL.getArgument().getKind() == TemplateArgument::Type) 5637 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo()) 5638 Visit(TSI->getTypeLoc(), Sema::AbstractNone); 5639 // TODO: other template argument types? 5640 } 5641 } 5642 5643 // Visit pointee types from a permissive context. 5644 #define CheckPolymorphic(Type) \ 5645 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \ 5646 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \ 5647 } 5648 CheckPolymorphic(PointerTypeLoc) 5649 CheckPolymorphic(ReferenceTypeLoc) 5650 CheckPolymorphic(MemberPointerTypeLoc) 5651 CheckPolymorphic(BlockPointerTypeLoc) 5652 CheckPolymorphic(AtomicTypeLoc) 5653 5654 /// Handle all the types we haven't given a more specific 5655 /// implementation for above. 5656 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) { 5657 // Every other kind of type that we haven't called out already 5658 // that has an inner type is either (1) sugar or (2) contains that 5659 // inner type in some way as a subobject. 5660 if (TypeLoc Next = TL.getNextTypeLoc()) 5661 return Visit(Next, Sel); 5662 5663 // If there's no inner type and we're in a permissive context, 5664 // don't diagnose. 5665 if (Sel == Sema::AbstractNone) return; 5666 5667 // Check whether the type matches the abstract type. 5668 QualType T = TL.getType(); 5669 if (T->isArrayType()) { 5670 Sel = Sema::AbstractArrayType; 5671 T = Info.S.Context.getBaseElementType(T); 5672 } 5673 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType(); 5674 if (CT != Info.AbstractType) return; 5675 5676 // It matched; do some magic. 5677 if (Sel == Sema::AbstractArrayType) { 5678 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type) 5679 << T << TL.getSourceRange(); 5680 } else { 5681 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl) 5682 << Sel << T << TL.getSourceRange(); 5683 } 5684 Info.DiagnoseAbstractType(); 5685 } 5686 }; 5687 5688 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL, 5689 Sema::AbstractDiagSelID Sel) { 5690 CheckAbstractUsage(*this, D).Visit(TL, Sel); 5691 } 5692 5693 } 5694 5695 /// Check for invalid uses of an abstract type in a method declaration. 5696 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5697 CXXMethodDecl *MD) { 5698 // No need to do the check on definitions, which require that 5699 // the return/param types be complete. 5700 if (MD->doesThisDeclarationHaveABody()) 5701 return; 5702 5703 // For safety's sake, just ignore it if we don't have type source 5704 // information. This should never happen for non-implicit methods, 5705 // but... 5706 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo()) 5707 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone); 5708 } 5709 5710 /// Check for invalid uses of an abstract type within a class definition. 5711 static void CheckAbstractClassUsage(AbstractUsageInfo &Info, 5712 CXXRecordDecl *RD) { 5713 for (auto *D : RD->decls()) { 5714 if (D->isImplicit()) continue; 5715 5716 // Methods and method templates. 5717 if (isa<CXXMethodDecl>(D)) { 5718 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D)); 5719 } else if (isa<FunctionTemplateDecl>(D)) { 5720 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl(); 5721 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD)); 5722 5723 // Fields and static variables. 5724 } else if (isa<FieldDecl>(D)) { 5725 FieldDecl *FD = cast<FieldDecl>(D); 5726 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo()) 5727 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType); 5728 } else if (isa<VarDecl>(D)) { 5729 VarDecl *VD = cast<VarDecl>(D); 5730 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo()) 5731 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType); 5732 5733 // Nested classes and class templates. 5734 } else if (isa<CXXRecordDecl>(D)) { 5735 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D)); 5736 } else if (isa<ClassTemplateDecl>(D)) { 5737 CheckAbstractClassUsage(Info, 5738 cast<ClassTemplateDecl>(D)->getTemplatedDecl()); 5739 } 5740 } 5741 } 5742 5743 static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) { 5744 Attr *ClassAttr = getDLLAttr(Class); 5745 if (!ClassAttr) 5746 return; 5747 5748 assert(ClassAttr->getKind() == attr::DLLExport); 5749 5750 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5751 5752 if (TSK == TSK_ExplicitInstantiationDeclaration) 5753 // Don't go any further if this is just an explicit instantiation 5754 // declaration. 5755 return; 5756 5757 if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) 5758 S.MarkVTableUsed(Class->getLocation(), Class, true); 5759 5760 for (Decl *Member : Class->decls()) { 5761 // Defined static variables that are members of an exported base 5762 // class must be marked export too. 5763 auto *VD = dyn_cast<VarDecl>(Member); 5764 if (VD && Member->getAttr<DLLExportAttr>() && 5765 VD->getStorageClass() == SC_Static && 5766 TSK == TSK_ImplicitInstantiation) 5767 S.MarkVariableReferenced(VD->getLocation(), VD); 5768 5769 auto *MD = dyn_cast<CXXMethodDecl>(Member); 5770 if (!MD) 5771 continue; 5772 5773 if (Member->getAttr<DLLExportAttr>()) { 5774 if (MD->isUserProvided()) { 5775 // Instantiate non-default class member functions ... 5776 5777 // .. except for certain kinds of template specializations. 5778 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited()) 5779 continue; 5780 5781 S.MarkFunctionReferenced(Class->getLocation(), MD); 5782 5783 // The function will be passed to the consumer when its definition is 5784 // encountered. 5785 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() || 5786 MD->isCopyAssignmentOperator() || 5787 MD->isMoveAssignmentOperator()) { 5788 // Synthesize and instantiate non-trivial implicit methods, explicitly 5789 // defaulted methods, and the copy and move assignment operators. The 5790 // latter are exported even if they are trivial, because the address of 5791 // an operator can be taken and should compare equal across libraries. 5792 DiagnosticErrorTrap Trap(S.Diags); 5793 S.MarkFunctionReferenced(Class->getLocation(), MD); 5794 if (Trap.hasErrorOccurred()) { 5795 S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class) 5796 << Class << !S.getLangOpts().CPlusPlus11; 5797 break; 5798 } 5799 5800 // There is no later point when we will see the definition of this 5801 // function, so pass it to the consumer now. 5802 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD)); 5803 } 5804 } 5805 } 5806 } 5807 5808 static void checkForMultipleExportedDefaultConstructors(Sema &S, 5809 CXXRecordDecl *Class) { 5810 // Only the MS ABI has default constructor closures, so we don't need to do 5811 // this semantic checking anywhere else. 5812 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft()) 5813 return; 5814 5815 CXXConstructorDecl *LastExportedDefaultCtor = nullptr; 5816 for (Decl *Member : Class->decls()) { 5817 // Look for exported default constructors. 5818 auto *CD = dyn_cast<CXXConstructorDecl>(Member); 5819 if (!CD || !CD->isDefaultConstructor()) 5820 continue; 5821 auto *Attr = CD->getAttr<DLLExportAttr>(); 5822 if (!Attr) 5823 continue; 5824 5825 // If the class is non-dependent, mark the default arguments as ODR-used so 5826 // that we can properly codegen the constructor closure. 5827 if (!Class->isDependentContext()) { 5828 for (ParmVarDecl *PD : CD->parameters()) { 5829 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD); 5830 S.DiscardCleanupsInEvaluationContext(); 5831 } 5832 } 5833 5834 if (LastExportedDefaultCtor) { 5835 S.Diag(LastExportedDefaultCtor->getLocation(), 5836 diag::err_attribute_dll_ambiguous_default_ctor) 5837 << Class; 5838 S.Diag(CD->getLocation(), diag::note_entity_declared_at) 5839 << CD->getDeclName(); 5840 return; 5841 } 5842 LastExportedDefaultCtor = CD; 5843 } 5844 } 5845 5846 void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) { 5847 // Mark any compiler-generated routines with the implicit code_seg attribute. 5848 for (auto *Method : Class->methods()) { 5849 if (Method->isUserProvided()) 5850 continue; 5851 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true)) 5852 Method->addAttr(A); 5853 } 5854 } 5855 5856 /// Check class-level dllimport/dllexport attribute. 5857 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) { 5858 Attr *ClassAttr = getDLLAttr(Class); 5859 5860 // MSVC inherits DLL attributes to partial class template specializations. 5861 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) { 5862 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) { 5863 if (Attr *TemplateAttr = 5864 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) { 5865 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext())); 5866 A->setInherited(true); 5867 ClassAttr = A; 5868 } 5869 } 5870 } 5871 5872 if (!ClassAttr) 5873 return; 5874 5875 if (!Class->isExternallyVisible()) { 5876 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern) 5877 << Class << ClassAttr; 5878 return; 5879 } 5880 5881 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 5882 !ClassAttr->isInherited()) { 5883 // Diagnose dll attributes on members of class with dll attribute. 5884 for (Decl *Member : Class->decls()) { 5885 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member)) 5886 continue; 5887 InheritableAttr *MemberAttr = getDLLAttr(Member); 5888 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl()) 5889 continue; 5890 5891 Diag(MemberAttr->getLocation(), 5892 diag::err_attribute_dll_member_of_dll_class) 5893 << MemberAttr << ClassAttr; 5894 Diag(ClassAttr->getLocation(), diag::note_previous_attribute); 5895 Member->setInvalidDecl(); 5896 } 5897 } 5898 5899 if (Class->getDescribedClassTemplate()) 5900 // Don't inherit dll attribute until the template is instantiated. 5901 return; 5902 5903 // The class is either imported or exported. 5904 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport; 5905 5906 // Check if this was a dllimport attribute propagated from a derived class to 5907 // a base class template specialization. We don't apply these attributes to 5908 // static data members. 5909 const bool PropagatedImport = 5910 !ClassExported && 5911 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate(); 5912 5913 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind(); 5914 5915 // Ignore explicit dllexport on explicit class template instantiation 5916 // declarations, except in MinGW mode. 5917 if (ClassExported && !ClassAttr->isInherited() && 5918 TSK == TSK_ExplicitInstantiationDeclaration && 5919 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) { 5920 Class->dropAttr<DLLExportAttr>(); 5921 return; 5922 } 5923 5924 // Force declaration of implicit members so they can inherit the attribute. 5925 ForceDeclarationOfImplicitMembers(Class); 5926 5927 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't 5928 // seem to be true in practice? 5929 5930 for (Decl *Member : Class->decls()) { 5931 VarDecl *VD = dyn_cast<VarDecl>(Member); 5932 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member); 5933 5934 // Only methods and static fields inherit the attributes. 5935 if (!VD && !MD) 5936 continue; 5937 5938 if (MD) { 5939 // Don't process deleted methods. 5940 if (MD->isDeleted()) 5941 continue; 5942 5943 if (MD->isInlined()) { 5944 // MinGW does not import or export inline methods. But do it for 5945 // template instantiations. 5946 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() && 5947 !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment() && 5948 TSK != TSK_ExplicitInstantiationDeclaration && 5949 TSK != TSK_ExplicitInstantiationDefinition) 5950 continue; 5951 5952 // MSVC versions before 2015 don't export the move assignment operators 5953 // and move constructor, so don't attempt to import/export them if 5954 // we have a definition. 5955 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD); 5956 if ((MD->isMoveAssignmentOperator() || 5957 (Ctor && Ctor->isMoveConstructor())) && 5958 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015)) 5959 continue; 5960 5961 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign 5962 // operator is exported anyway. 5963 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 5964 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial()) 5965 continue; 5966 } 5967 } 5968 5969 // Don't apply dllimport attributes to static data members of class template 5970 // instantiations when the attribute is propagated from a derived class. 5971 if (VD && PropagatedImport) 5972 continue; 5973 5974 if (!cast<NamedDecl>(Member)->isExternallyVisible()) 5975 continue; 5976 5977 if (!getDLLAttr(Member)) { 5978 InheritableAttr *NewAttr = nullptr; 5979 5980 // Do not export/import inline function when -fno-dllexport-inlines is 5981 // passed. But add attribute for later local static var check. 5982 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() && 5983 TSK != TSK_ExplicitInstantiationDeclaration && 5984 TSK != TSK_ExplicitInstantiationDefinition) { 5985 if (ClassExported) { 5986 NewAttr = ::new (getASTContext()) 5987 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr); 5988 } else { 5989 NewAttr = ::new (getASTContext()) 5990 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr); 5991 } 5992 } else { 5993 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 5994 } 5995 5996 NewAttr->setInherited(true); 5997 Member->addAttr(NewAttr); 5998 5999 if (MD) { 6000 // Propagate DLLAttr to friend re-declarations of MD that have already 6001 // been constructed. 6002 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD; 6003 FD = FD->getPreviousDecl()) { 6004 if (FD->getFriendObjectKind() == Decl::FOK_None) 6005 continue; 6006 assert(!getDLLAttr(FD) && 6007 "friend re-decl should not already have a DLLAttr"); 6008 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6009 NewAttr->setInherited(true); 6010 FD->addAttr(NewAttr); 6011 } 6012 } 6013 } 6014 } 6015 6016 if (ClassExported) 6017 DelayedDllExportClasses.push_back(Class); 6018 } 6019 6020 /// Perform propagation of DLL attributes from a derived class to a 6021 /// templated base class for MS compatibility. 6022 void Sema::propagateDLLAttrToBaseClassTemplate( 6023 CXXRecordDecl *Class, Attr *ClassAttr, 6024 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) { 6025 if (getDLLAttr( 6026 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) { 6027 // If the base class template has a DLL attribute, don't try to change it. 6028 return; 6029 } 6030 6031 auto TSK = BaseTemplateSpec->getSpecializationKind(); 6032 if (!getDLLAttr(BaseTemplateSpec) && 6033 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration || 6034 TSK == TSK_ImplicitInstantiation)) { 6035 // The template hasn't been instantiated yet (or it has, but only as an 6036 // explicit instantiation declaration or implicit instantiation, which means 6037 // we haven't codegenned any members yet), so propagate the attribute. 6038 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext())); 6039 NewAttr->setInherited(true); 6040 BaseTemplateSpec->addAttr(NewAttr); 6041 6042 // If this was an import, mark that we propagated it from a derived class to 6043 // a base class template specialization. 6044 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr)) 6045 ImportAttr->setPropagatedToBaseTemplate(); 6046 6047 // If the template is already instantiated, checkDLLAttributeRedeclaration() 6048 // needs to be run again to work see the new attribute. Otherwise this will 6049 // get run whenever the template is instantiated. 6050 if (TSK != TSK_Undeclared) 6051 checkClassLevelDLLAttribute(BaseTemplateSpec); 6052 6053 return; 6054 } 6055 6056 if (getDLLAttr(BaseTemplateSpec)) { 6057 // The template has already been specialized or instantiated with an 6058 // attribute, explicitly or through propagation. We should not try to change 6059 // it. 6060 return; 6061 } 6062 6063 // The template was previously instantiated or explicitly specialized without 6064 // a dll attribute, It's too late for us to add an attribute, so warn that 6065 // this is unsupported. 6066 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class) 6067 << BaseTemplateSpec->isExplicitSpecialization(); 6068 Diag(ClassAttr->getLocation(), diag::note_attribute); 6069 if (BaseTemplateSpec->isExplicitSpecialization()) { 6070 Diag(BaseTemplateSpec->getLocation(), 6071 diag::note_template_class_explicit_specialization_was_here) 6072 << BaseTemplateSpec; 6073 } else { 6074 Diag(BaseTemplateSpec->getPointOfInstantiation(), 6075 diag::note_template_class_instantiation_was_here) 6076 << BaseTemplateSpec; 6077 } 6078 } 6079 6080 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD, 6081 SourceLocation DefaultLoc) { 6082 switch (S.getSpecialMember(MD)) { 6083 case Sema::CXXDefaultConstructor: 6084 S.DefineImplicitDefaultConstructor(DefaultLoc, 6085 cast<CXXConstructorDecl>(MD)); 6086 break; 6087 case Sema::CXXCopyConstructor: 6088 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 6089 break; 6090 case Sema::CXXCopyAssignment: 6091 S.DefineImplicitCopyAssignment(DefaultLoc, MD); 6092 break; 6093 case Sema::CXXDestructor: 6094 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD)); 6095 break; 6096 case Sema::CXXMoveConstructor: 6097 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD)); 6098 break; 6099 case Sema::CXXMoveAssignment: 6100 S.DefineImplicitMoveAssignment(DefaultLoc, MD); 6101 break; 6102 case Sema::CXXInvalid: 6103 llvm_unreachable("Invalid special member."); 6104 } 6105 } 6106 6107 /// Determine whether a type is permitted to be passed or returned in 6108 /// registers, per C++ [class.temporary]p3. 6109 static bool canPassInRegisters(Sema &S, CXXRecordDecl *D, 6110 TargetInfo::CallingConvKind CCK) { 6111 if (D->isDependentType() || D->isInvalidDecl()) 6112 return false; 6113 6114 // Clang <= 4 used the pre-C++11 rule, which ignores move operations. 6115 // The PS4 platform ABI follows the behavior of Clang 3.2. 6116 if (CCK == TargetInfo::CCK_ClangABI4OrPS4) 6117 return !D->hasNonTrivialDestructorForCall() && 6118 !D->hasNonTrivialCopyConstructorForCall(); 6119 6120 if (CCK == TargetInfo::CCK_MicrosoftWin64) { 6121 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false; 6122 bool DtorIsTrivialForCall = false; 6123 6124 // If a class has at least one non-deleted, trivial copy constructor, it 6125 // is passed according to the C ABI. Otherwise, it is passed indirectly. 6126 // 6127 // Note: This permits classes with non-trivial copy or move ctors to be 6128 // passed in registers, so long as they *also* have a trivial copy ctor, 6129 // which is non-conforming. 6130 if (D->needsImplicitCopyConstructor()) { 6131 if (!D->defaultedCopyConstructorIsDeleted()) { 6132 if (D->hasTrivialCopyConstructor()) 6133 CopyCtorIsTrivial = true; 6134 if (D->hasTrivialCopyConstructorForCall()) 6135 CopyCtorIsTrivialForCall = true; 6136 } 6137 } else { 6138 for (const CXXConstructorDecl *CD : D->ctors()) { 6139 if (CD->isCopyConstructor() && !CD->isDeleted()) { 6140 if (CD->isTrivial()) 6141 CopyCtorIsTrivial = true; 6142 if (CD->isTrivialForCall()) 6143 CopyCtorIsTrivialForCall = true; 6144 } 6145 } 6146 } 6147 6148 if (D->needsImplicitDestructor()) { 6149 if (!D->defaultedDestructorIsDeleted() && 6150 D->hasTrivialDestructorForCall()) 6151 DtorIsTrivialForCall = true; 6152 } else if (const auto *DD = D->getDestructor()) { 6153 if (!DD->isDeleted() && DD->isTrivialForCall()) 6154 DtorIsTrivialForCall = true; 6155 } 6156 6157 // If the copy ctor and dtor are both trivial-for-calls, pass direct. 6158 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall) 6159 return true; 6160 6161 // If a class has a destructor, we'd really like to pass it indirectly 6162 // because it allows us to elide copies. Unfortunately, MSVC makes that 6163 // impossible for small types, which it will pass in a single register or 6164 // stack slot. Most objects with dtors are large-ish, so handle that early. 6165 // We can't call out all large objects as being indirect because there are 6166 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate 6167 // how we pass large POD types. 6168 6169 // Note: This permits small classes with nontrivial destructors to be 6170 // passed in registers, which is non-conforming. 6171 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64(); 6172 uint64_t TypeSize = isAArch64 ? 128 : 64; 6173 6174 if (CopyCtorIsTrivial && 6175 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize) 6176 return true; 6177 return false; 6178 } 6179 6180 // Per C++ [class.temporary]p3, the relevant condition is: 6181 // each copy constructor, move constructor, and destructor of X is 6182 // either trivial or deleted, and X has at least one non-deleted copy 6183 // or move constructor 6184 bool HasNonDeletedCopyOrMove = false; 6185 6186 if (D->needsImplicitCopyConstructor() && 6187 !D->defaultedCopyConstructorIsDeleted()) { 6188 if (!D->hasTrivialCopyConstructorForCall()) 6189 return false; 6190 HasNonDeletedCopyOrMove = true; 6191 } 6192 6193 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() && 6194 !D->defaultedMoveConstructorIsDeleted()) { 6195 if (!D->hasTrivialMoveConstructorForCall()) 6196 return false; 6197 HasNonDeletedCopyOrMove = true; 6198 } 6199 6200 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() && 6201 !D->hasTrivialDestructorForCall()) 6202 return false; 6203 6204 for (const CXXMethodDecl *MD : D->methods()) { 6205 if (MD->isDeleted()) 6206 continue; 6207 6208 auto *CD = dyn_cast<CXXConstructorDecl>(MD); 6209 if (CD && CD->isCopyOrMoveConstructor()) 6210 HasNonDeletedCopyOrMove = true; 6211 else if (!isa<CXXDestructorDecl>(MD)) 6212 continue; 6213 6214 if (!MD->isTrivialForCall()) 6215 return false; 6216 } 6217 6218 return HasNonDeletedCopyOrMove; 6219 } 6220 6221 /// Perform semantic checks on a class definition that has been 6222 /// completing, introducing implicitly-declared members, checking for 6223 /// abstract types, etc. 6224 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) { 6225 if (!Record) 6226 return; 6227 6228 if (Record->isAbstract() && !Record->isInvalidDecl()) { 6229 AbstractUsageInfo Info(*this, Record); 6230 CheckAbstractClassUsage(Info, Record); 6231 } 6232 6233 // If this is not an aggregate type and has no user-declared constructor, 6234 // complain about any non-static data members of reference or const scalar 6235 // type, since they will never get initializers. 6236 if (!Record->isInvalidDecl() && !Record->isDependentType() && 6237 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() && 6238 !Record->isLambda()) { 6239 bool Complained = false; 6240 for (const auto *F : Record->fields()) { 6241 if (F->hasInClassInitializer() || F->isUnnamedBitfield()) 6242 continue; 6243 6244 if (F->getType()->isReferenceType() || 6245 (F->getType().isConstQualified() && F->getType()->isScalarType())) { 6246 if (!Complained) { 6247 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst) 6248 << Record->getTagKind() << Record; 6249 Complained = true; 6250 } 6251 6252 Diag(F->getLocation(), diag::note_refconst_member_not_initialized) 6253 << F->getType()->isReferenceType() 6254 << F->getDeclName(); 6255 } 6256 } 6257 } 6258 6259 if (Record->getIdentifier()) { 6260 // C++ [class.mem]p13: 6261 // If T is the name of a class, then each of the following shall have a 6262 // name different from T: 6263 // - every member of every anonymous union that is a member of class T. 6264 // 6265 // C++ [class.mem]p14: 6266 // In addition, if class T has a user-declared constructor (12.1), every 6267 // non-static data member of class T shall have a name different from T. 6268 DeclContext::lookup_result R = Record->lookup(Record->getDeclName()); 6269 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 6270 ++I) { 6271 NamedDecl *D = (*I)->getUnderlyingDecl(); 6272 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) && 6273 Record->hasUserDeclaredConstructor()) || 6274 isa<IndirectFieldDecl>(D)) { 6275 Diag((*I)->getLocation(), diag::err_member_name_of_class) 6276 << D->getDeclName(); 6277 break; 6278 } 6279 } 6280 } 6281 6282 // Warn if the class has virtual methods but non-virtual public destructor. 6283 if (Record->isPolymorphic() && !Record->isDependentType()) { 6284 CXXDestructorDecl *dtor = Record->getDestructor(); 6285 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) && 6286 !Record->hasAttr<FinalAttr>()) 6287 Diag(dtor ? dtor->getLocation() : Record->getLocation(), 6288 diag::warn_non_virtual_dtor) << Context.getRecordType(Record); 6289 } 6290 6291 if (Record->isAbstract()) { 6292 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) { 6293 Diag(Record->getLocation(), diag::warn_abstract_final_class) 6294 << FA->isSpelledAsSealed(); 6295 DiagnoseAbstractType(Record); 6296 } 6297 } 6298 6299 // Warn if the class has a final destructor but is not itself marked final. 6300 if (!Record->hasAttr<FinalAttr>()) { 6301 if (const CXXDestructorDecl *dtor = Record->getDestructor()) { 6302 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) { 6303 Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class) 6304 << FA->isSpelledAsSealed() 6305 << FixItHint::CreateInsertion( 6306 getLocForEndOfToken(Record->getLocation()), 6307 (FA->isSpelledAsSealed() ? " sealed" : " final")); 6308 Diag(Record->getLocation(), 6309 diag::note_final_dtor_non_final_class_silence) 6310 << Context.getRecordType(Record) << FA->isSpelledAsSealed(); 6311 } 6312 } 6313 } 6314 6315 // See if trivial_abi has to be dropped. 6316 if (Record->hasAttr<TrivialABIAttr>()) 6317 checkIllFormedTrivialABIStruct(*Record); 6318 6319 // Set HasTrivialSpecialMemberForCall if the record has attribute 6320 // "trivial_abi". 6321 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>(); 6322 6323 if (HasTrivialABI) 6324 Record->setHasTrivialSpecialMemberForCall(); 6325 6326 auto CompleteMemberFunction = [&](CXXMethodDecl *M) { 6327 // Check whether the explicitly-defaulted special members are valid. 6328 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted()) 6329 CheckExplicitlyDefaultedSpecialMember(M); 6330 6331 // For an explicitly defaulted or deleted special member, we defer 6332 // determining triviality until the class is complete. That time is now! 6333 CXXSpecialMember CSM = getSpecialMember(M); 6334 if (!M->isImplicit() && !M->isUserProvided()) { 6335 if (CSM != CXXInvalid) { 6336 M->setTrivial(SpecialMemberIsTrivial(M, CSM)); 6337 // Inform the class that we've finished declaring this member. 6338 Record->finishedDefaultedOrDeletedMember(M); 6339 M->setTrivialForCall( 6340 HasTrivialABI || 6341 SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI)); 6342 Record->setTrivialForCallFlags(M); 6343 } 6344 } 6345 6346 // Set triviality for the purpose of calls if this is a user-provided 6347 // copy/move constructor or destructor. 6348 if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor || 6349 CSM == CXXDestructor) && M->isUserProvided()) { 6350 M->setTrivialForCall(HasTrivialABI); 6351 Record->setTrivialForCallFlags(M); 6352 } 6353 6354 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() && 6355 M->hasAttr<DLLExportAttr>()) { 6356 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 6357 M->isTrivial() && 6358 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor || 6359 CSM == CXXDestructor)) 6360 M->dropAttr<DLLExportAttr>(); 6361 6362 if (M->hasAttr<DLLExportAttr>()) { 6363 // Define after any fields with in-class initializers have been parsed. 6364 DelayedDllExportMemberFunctions.push_back(M); 6365 } 6366 } 6367 6368 // Define defaulted constexpr virtual functions that override a base class 6369 // function right away. 6370 // FIXME: We can defer doing this until the vtable is marked as used. 6371 if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods()) 6372 DefineImplicitSpecialMember(*this, M, M->getLocation()); 6373 }; 6374 6375 bool HasMethodWithOverrideControl = false, 6376 HasOverridingMethodWithoutOverrideControl = false; 6377 if (!Record->isDependentType()) { 6378 // Check the destructor before any other member function. We need to 6379 // determine whether it's trivial in order to determine whether the claas 6380 // type is a literal type, which is a prerequisite for determining whether 6381 // other special member functions are valid and whether they're implicitly 6382 // 'constexpr'. 6383 if (CXXDestructorDecl *Dtor = Record->getDestructor()) 6384 CompleteMemberFunction(Dtor); 6385 6386 for (auto *M : Record->methods()) { 6387 // See if a method overloads virtual methods in a base 6388 // class without overriding any. 6389 if (!M->isStatic()) 6390 DiagnoseHiddenVirtualMethods(M); 6391 if (M->hasAttr<OverrideAttr>()) 6392 HasMethodWithOverrideControl = true; 6393 else if (M->size_overridden_methods() > 0) 6394 HasOverridingMethodWithoutOverrideControl = true; 6395 6396 if (!isa<CXXDestructorDecl>(M)) 6397 CompleteMemberFunction(M); 6398 } 6399 } 6400 6401 if (HasMethodWithOverrideControl && 6402 HasOverridingMethodWithoutOverrideControl) { 6403 // At least one method has the 'override' control declared. 6404 // Diagnose all other overridden methods which do not have 'override' specified on them. 6405 for (auto *M : Record->methods()) 6406 DiagnoseAbsenceOfOverrideControl(M); 6407 } 6408 6409 // ms_struct is a request to use the same ABI rules as MSVC. Check 6410 // whether this class uses any C++ features that are implemented 6411 // completely differently in MSVC, and if so, emit a diagnostic. 6412 // That diagnostic defaults to an error, but we allow projects to 6413 // map it down to a warning (or ignore it). It's a fairly common 6414 // practice among users of the ms_struct pragma to mass-annotate 6415 // headers, sweeping up a bunch of types that the project doesn't 6416 // really rely on MSVC-compatible layout for. We must therefore 6417 // support "ms_struct except for C++ stuff" as a secondary ABI. 6418 if (Record->isMsStruct(Context) && 6419 (Record->isPolymorphic() || Record->getNumBases())) { 6420 Diag(Record->getLocation(), diag::warn_cxx_ms_struct); 6421 } 6422 6423 checkClassLevelDLLAttribute(Record); 6424 checkClassLevelCodeSegAttribute(Record); 6425 6426 bool ClangABICompat4 = 6427 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4; 6428 TargetInfo::CallingConvKind CCK = 6429 Context.getTargetInfo().getCallingConvKind(ClangABICompat4); 6430 bool CanPass = canPassInRegisters(*this, Record, CCK); 6431 6432 // Do not change ArgPassingRestrictions if it has already been set to 6433 // APK_CanNeverPassInRegs. 6434 if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs) 6435 Record->setArgPassingRestrictions(CanPass 6436 ? RecordDecl::APK_CanPassInRegs 6437 : RecordDecl::APK_CannotPassInRegs); 6438 6439 // If canPassInRegisters returns true despite the record having a non-trivial 6440 // destructor, the record is destructed in the callee. This happens only when 6441 // the record or one of its subobjects has a field annotated with trivial_abi 6442 // or a field qualified with ObjC __strong/__weak. 6443 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee()) 6444 Record->setParamDestroyedInCallee(true); 6445 else if (Record->hasNonTrivialDestructor()) 6446 Record->setParamDestroyedInCallee(CanPass); 6447 6448 if (getLangOpts().ForceEmitVTables) { 6449 // If we want to emit all the vtables, we need to mark it as used. This 6450 // is especially required for cases like vtable assumption loads. 6451 MarkVTableUsed(Record->getInnerLocStart(), Record); 6452 } 6453 } 6454 6455 /// Look up the special member function that would be called by a special 6456 /// member function for a subobject of class type. 6457 /// 6458 /// \param Class The class type of the subobject. 6459 /// \param CSM The kind of special member function. 6460 /// \param FieldQuals If the subobject is a field, its cv-qualifiers. 6461 /// \param ConstRHS True if this is a copy operation with a const object 6462 /// on its RHS, that is, if the argument to the outer special member 6463 /// function is 'const' and this is not a field marked 'mutable'. 6464 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember( 6465 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM, 6466 unsigned FieldQuals, bool ConstRHS) { 6467 unsigned LHSQuals = 0; 6468 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment) 6469 LHSQuals = FieldQuals; 6470 6471 unsigned RHSQuals = FieldQuals; 6472 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor) 6473 RHSQuals = 0; 6474 else if (ConstRHS) 6475 RHSQuals |= Qualifiers::Const; 6476 6477 return S.LookupSpecialMember(Class, CSM, 6478 RHSQuals & Qualifiers::Const, 6479 RHSQuals & Qualifiers::Volatile, 6480 false, 6481 LHSQuals & Qualifiers::Const, 6482 LHSQuals & Qualifiers::Volatile); 6483 } 6484 6485 class Sema::InheritedConstructorInfo { 6486 Sema &S; 6487 SourceLocation UseLoc; 6488 6489 /// A mapping from the base classes through which the constructor was 6490 /// inherited to the using shadow declaration in that base class (or a null 6491 /// pointer if the constructor was declared in that base class). 6492 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *> 6493 InheritedFromBases; 6494 6495 public: 6496 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc, 6497 ConstructorUsingShadowDecl *Shadow) 6498 : S(S), UseLoc(UseLoc) { 6499 bool DiagnosedMultipleConstructedBases = false; 6500 CXXRecordDecl *ConstructedBase = nullptr; 6501 UsingDecl *ConstructedBaseUsing = nullptr; 6502 6503 // Find the set of such base class subobjects and check that there's a 6504 // unique constructed subobject. 6505 for (auto *D : Shadow->redecls()) { 6506 auto *DShadow = cast<ConstructorUsingShadowDecl>(D); 6507 auto *DNominatedBase = DShadow->getNominatedBaseClass(); 6508 auto *DConstructedBase = DShadow->getConstructedBaseClass(); 6509 6510 InheritedFromBases.insert( 6511 std::make_pair(DNominatedBase->getCanonicalDecl(), 6512 DShadow->getNominatedBaseClassShadowDecl())); 6513 if (DShadow->constructsVirtualBase()) 6514 InheritedFromBases.insert( 6515 std::make_pair(DConstructedBase->getCanonicalDecl(), 6516 DShadow->getConstructedBaseClassShadowDecl())); 6517 else 6518 assert(DNominatedBase == DConstructedBase); 6519 6520 // [class.inhctor.init]p2: 6521 // If the constructor was inherited from multiple base class subobjects 6522 // of type B, the program is ill-formed. 6523 if (!ConstructedBase) { 6524 ConstructedBase = DConstructedBase; 6525 ConstructedBaseUsing = D->getUsingDecl(); 6526 } else if (ConstructedBase != DConstructedBase && 6527 !Shadow->isInvalidDecl()) { 6528 if (!DiagnosedMultipleConstructedBases) { 6529 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor) 6530 << Shadow->getTargetDecl(); 6531 S.Diag(ConstructedBaseUsing->getLocation(), 6532 diag::note_ambiguous_inherited_constructor_using) 6533 << ConstructedBase; 6534 DiagnosedMultipleConstructedBases = true; 6535 } 6536 S.Diag(D->getUsingDecl()->getLocation(), 6537 diag::note_ambiguous_inherited_constructor_using) 6538 << DConstructedBase; 6539 } 6540 } 6541 6542 if (DiagnosedMultipleConstructedBases) 6543 Shadow->setInvalidDecl(); 6544 } 6545 6546 /// Find the constructor to use for inherited construction of a base class, 6547 /// and whether that base class constructor inherits the constructor from a 6548 /// virtual base class (in which case it won't actually invoke it). 6549 std::pair<CXXConstructorDecl *, bool> 6550 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const { 6551 auto It = InheritedFromBases.find(Base->getCanonicalDecl()); 6552 if (It == InheritedFromBases.end()) 6553 return std::make_pair(nullptr, false); 6554 6555 // This is an intermediary class. 6556 if (It->second) 6557 return std::make_pair( 6558 S.findInheritingConstructor(UseLoc, Ctor, It->second), 6559 It->second->constructsVirtualBase()); 6560 6561 // This is the base class from which the constructor was inherited. 6562 return std::make_pair(Ctor, false); 6563 } 6564 }; 6565 6566 /// Is the special member function which would be selected to perform the 6567 /// specified operation on the specified class type a constexpr constructor? 6568 static bool 6569 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl, 6570 Sema::CXXSpecialMember CSM, unsigned Quals, 6571 bool ConstRHS, 6572 CXXConstructorDecl *InheritedCtor = nullptr, 6573 Sema::InheritedConstructorInfo *Inherited = nullptr) { 6574 // If we're inheriting a constructor, see if we need to call it for this base 6575 // class. 6576 if (InheritedCtor) { 6577 assert(CSM == Sema::CXXDefaultConstructor); 6578 auto BaseCtor = 6579 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first; 6580 if (BaseCtor) 6581 return BaseCtor->isConstexpr(); 6582 } 6583 6584 if (CSM == Sema::CXXDefaultConstructor) 6585 return ClassDecl->hasConstexprDefaultConstructor(); 6586 if (CSM == Sema::CXXDestructor) 6587 return ClassDecl->hasConstexprDestructor(); 6588 6589 Sema::SpecialMemberOverloadResult SMOR = 6590 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS); 6591 if (!SMOR.getMethod()) 6592 // A constructor we wouldn't select can't be "involved in initializing" 6593 // anything. 6594 return true; 6595 return SMOR.getMethod()->isConstexpr(); 6596 } 6597 6598 /// Determine whether the specified special member function would be constexpr 6599 /// if it were implicitly defined. 6600 static bool defaultedSpecialMemberIsConstexpr( 6601 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM, 6602 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr, 6603 Sema::InheritedConstructorInfo *Inherited = nullptr) { 6604 if (!S.getLangOpts().CPlusPlus11) 6605 return false; 6606 6607 // C++11 [dcl.constexpr]p4: 6608 // In the definition of a constexpr constructor [...] 6609 bool Ctor = true; 6610 switch (CSM) { 6611 case Sema::CXXDefaultConstructor: 6612 if (Inherited) 6613 break; 6614 // Since default constructor lookup is essentially trivial (and cannot 6615 // involve, for instance, template instantiation), we compute whether a 6616 // defaulted default constructor is constexpr directly within CXXRecordDecl. 6617 // 6618 // This is important for performance; we need to know whether the default 6619 // constructor is constexpr to determine whether the type is a literal type. 6620 return ClassDecl->defaultedDefaultConstructorIsConstexpr(); 6621 6622 case Sema::CXXCopyConstructor: 6623 case Sema::CXXMoveConstructor: 6624 // For copy or move constructors, we need to perform overload resolution. 6625 break; 6626 6627 case Sema::CXXCopyAssignment: 6628 case Sema::CXXMoveAssignment: 6629 if (!S.getLangOpts().CPlusPlus14) 6630 return false; 6631 // In C++1y, we need to perform overload resolution. 6632 Ctor = false; 6633 break; 6634 6635 case Sema::CXXDestructor: 6636 return ClassDecl->defaultedDestructorIsConstexpr(); 6637 6638 case Sema::CXXInvalid: 6639 return false; 6640 } 6641 6642 // -- if the class is a non-empty union, or for each non-empty anonymous 6643 // union member of a non-union class, exactly one non-static data member 6644 // shall be initialized; [DR1359] 6645 // 6646 // If we squint, this is guaranteed, since exactly one non-static data member 6647 // will be initialized (if the constructor isn't deleted), we just don't know 6648 // which one. 6649 if (Ctor && ClassDecl->isUnion()) 6650 return CSM == Sema::CXXDefaultConstructor 6651 ? ClassDecl->hasInClassInitializer() || 6652 !ClassDecl->hasVariantMembers() 6653 : true; 6654 6655 // -- the class shall not have any virtual base classes; 6656 if (Ctor && ClassDecl->getNumVBases()) 6657 return false; 6658 6659 // C++1y [class.copy]p26: 6660 // -- [the class] is a literal type, and 6661 if (!Ctor && !ClassDecl->isLiteral()) 6662 return false; 6663 6664 // -- every constructor involved in initializing [...] base class 6665 // sub-objects shall be a constexpr constructor; 6666 // -- the assignment operator selected to copy/move each direct base 6667 // class is a constexpr function, and 6668 for (const auto &B : ClassDecl->bases()) { 6669 const RecordType *BaseType = B.getType()->getAs<RecordType>(); 6670 if (!BaseType) continue; 6671 6672 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl()); 6673 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg, 6674 InheritedCtor, Inherited)) 6675 return false; 6676 } 6677 6678 // -- every constructor involved in initializing non-static data members 6679 // [...] shall be a constexpr constructor; 6680 // -- every non-static data member and base class sub-object shall be 6681 // initialized 6682 // -- for each non-static data member of X that is of class type (or array 6683 // thereof), the assignment operator selected to copy/move that member is 6684 // a constexpr function 6685 for (const auto *F : ClassDecl->fields()) { 6686 if (F->isInvalidDecl()) 6687 continue; 6688 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer()) 6689 continue; 6690 QualType BaseType = S.Context.getBaseElementType(F->getType()); 6691 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) { 6692 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 6693 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM, 6694 BaseType.getCVRQualifiers(), 6695 ConstArg && !F->isMutable())) 6696 return false; 6697 } else if (CSM == Sema::CXXDefaultConstructor) { 6698 return false; 6699 } 6700 } 6701 6702 // All OK, it's constexpr! 6703 return true; 6704 } 6705 6706 static Sema::ImplicitExceptionSpecification 6707 ComputeDefaultedSpecialMemberExceptionSpec( 6708 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 6709 Sema::InheritedConstructorInfo *ICI); 6710 6711 static Sema::ImplicitExceptionSpecification 6712 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) { 6713 auto CSM = S.getSpecialMember(MD); 6714 if (CSM != Sema::CXXInvalid) 6715 return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr); 6716 6717 auto *CD = cast<CXXConstructorDecl>(MD); 6718 assert(CD->getInheritedConstructor() && 6719 "only special members have implicit exception specs"); 6720 Sema::InheritedConstructorInfo ICI( 6721 S, Loc, CD->getInheritedConstructor().getShadowDecl()); 6722 return ComputeDefaultedSpecialMemberExceptionSpec( 6723 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI); 6724 } 6725 6726 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S, 6727 CXXMethodDecl *MD) { 6728 FunctionProtoType::ExtProtoInfo EPI; 6729 6730 // Build an exception specification pointing back at this member. 6731 EPI.ExceptionSpec.Type = EST_Unevaluated; 6732 EPI.ExceptionSpec.SourceDecl = MD; 6733 6734 // Set the calling convention to the default for C++ instance methods. 6735 EPI.ExtInfo = EPI.ExtInfo.withCallingConv( 6736 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false, 6737 /*IsCXXMethod=*/true)); 6738 return EPI; 6739 } 6740 6741 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) { 6742 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 6743 if (FPT->getExceptionSpecType() != EST_Unevaluated) 6744 return; 6745 6746 // Evaluate the exception specification. 6747 auto IES = computeImplicitExceptionSpec(*this, Loc, MD); 6748 auto ESI = IES.getExceptionSpec(); 6749 6750 // Update the type of the special member to use it. 6751 UpdateExceptionSpec(MD, ESI); 6752 6753 // A user-provided destructor can be defined outside the class. When that 6754 // happens, be sure to update the exception specification on both 6755 // declarations. 6756 const FunctionProtoType *CanonicalFPT = 6757 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>(); 6758 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated) 6759 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI); 6760 } 6761 6762 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) { 6763 CXXRecordDecl *RD = MD->getParent(); 6764 CXXSpecialMember CSM = getSpecialMember(MD); 6765 6766 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid && 6767 "not an explicitly-defaulted special member"); 6768 6769 // Whether this was the first-declared instance of the constructor. 6770 // This affects whether we implicitly add an exception spec and constexpr. 6771 bool First = MD == MD->getCanonicalDecl(); 6772 6773 bool HadError = false; 6774 6775 // C++11 [dcl.fct.def.default]p1: 6776 // A function that is explicitly defaulted shall 6777 // -- be a special member function (checked elsewhere), 6778 // -- have the same type (except for ref-qualifiers, and except that a 6779 // copy operation can take a non-const reference) as an implicit 6780 // declaration, and 6781 // -- not have default arguments. 6782 // C++2a changes the second bullet to instead delete the function if it's 6783 // defaulted on its first declaration, unless it's "an assignment operator, 6784 // and its return type differs or its parameter type is not a reference". 6785 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus2a && First; 6786 bool ShouldDeleteForTypeMismatch = false; 6787 unsigned ExpectedParams = 1; 6788 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor) 6789 ExpectedParams = 0; 6790 if (MD->getNumParams() != ExpectedParams) { 6791 // This checks for default arguments: a copy or move constructor with a 6792 // default argument is classified as a default constructor, and assignment 6793 // operations and destructors can't have default arguments. 6794 Diag(MD->getLocation(), diag::err_defaulted_special_member_params) 6795 << CSM << MD->getSourceRange(); 6796 HadError = true; 6797 } else if (MD->isVariadic()) { 6798 if (DeleteOnTypeMismatch) 6799 ShouldDeleteForTypeMismatch = true; 6800 else { 6801 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic) 6802 << CSM << MD->getSourceRange(); 6803 HadError = true; 6804 } 6805 } 6806 6807 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>(); 6808 6809 bool CanHaveConstParam = false; 6810 if (CSM == CXXCopyConstructor) 6811 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam(); 6812 else if (CSM == CXXCopyAssignment) 6813 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam(); 6814 6815 QualType ReturnType = Context.VoidTy; 6816 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) { 6817 // Check for return type matching. 6818 ReturnType = Type->getReturnType(); 6819 6820 QualType DeclType = Context.getTypeDeclType(RD); 6821 DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace()); 6822 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType); 6823 6824 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) { 6825 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type) 6826 << (CSM == CXXMoveAssignment) << ExpectedReturnType; 6827 HadError = true; 6828 } 6829 6830 // A defaulted special member cannot have cv-qualifiers. 6831 if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) { 6832 if (DeleteOnTypeMismatch) 6833 ShouldDeleteForTypeMismatch = true; 6834 else { 6835 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals) 6836 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14; 6837 HadError = true; 6838 } 6839 } 6840 } 6841 6842 // Check for parameter type matching. 6843 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType(); 6844 bool HasConstParam = false; 6845 if (ExpectedParams && ArgType->isReferenceType()) { 6846 // Argument must be reference to possibly-const T. 6847 QualType ReferentType = ArgType->getPointeeType(); 6848 HasConstParam = ReferentType.isConstQualified(); 6849 6850 if (ReferentType.isVolatileQualified()) { 6851 if (DeleteOnTypeMismatch) 6852 ShouldDeleteForTypeMismatch = true; 6853 else { 6854 Diag(MD->getLocation(), 6855 diag::err_defaulted_special_member_volatile_param) << CSM; 6856 HadError = true; 6857 } 6858 } 6859 6860 if (HasConstParam && !CanHaveConstParam) { 6861 if (DeleteOnTypeMismatch) 6862 ShouldDeleteForTypeMismatch = true; 6863 else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) { 6864 Diag(MD->getLocation(), 6865 diag::err_defaulted_special_member_copy_const_param) 6866 << (CSM == CXXCopyAssignment); 6867 // FIXME: Explain why this special member can't be const. 6868 HadError = true; 6869 } else { 6870 Diag(MD->getLocation(), 6871 diag::err_defaulted_special_member_move_const_param) 6872 << (CSM == CXXMoveAssignment); 6873 HadError = true; 6874 } 6875 } 6876 } else if (ExpectedParams) { 6877 // A copy assignment operator can take its argument by value, but a 6878 // defaulted one cannot. 6879 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument"); 6880 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref); 6881 HadError = true; 6882 } 6883 6884 // C++11 [dcl.fct.def.default]p2: 6885 // An explicitly-defaulted function may be declared constexpr only if it 6886 // would have been implicitly declared as constexpr, 6887 // Do not apply this rule to members of class templates, since core issue 1358 6888 // makes such functions always instantiate to constexpr functions. For 6889 // functions which cannot be constexpr (for non-constructors in C++11 and for 6890 // destructors in C++14 and C++17), this is checked elsewhere. 6891 // 6892 // FIXME: This should not apply if the member is deleted. 6893 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM, 6894 HasConstParam); 6895 if ((getLangOpts().CPlusPlus2a || 6896 (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD) 6897 : isa<CXXConstructorDecl>(MD))) && 6898 MD->isConstexpr() && !Constexpr && 6899 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) { 6900 Diag(MD->getBeginLoc(), MD->isConsteval() 6901 ? diag::err_incorrect_defaulted_consteval 6902 : diag::err_incorrect_defaulted_constexpr) 6903 << CSM; 6904 // FIXME: Explain why the special member can't be constexpr. 6905 HadError = true; 6906 } 6907 6908 if (First) { 6909 // C++2a [dcl.fct.def.default]p3: 6910 // If a function is explicitly defaulted on its first declaration, it is 6911 // implicitly considered to be constexpr if the implicit declaration 6912 // would be. 6913 MD->setConstexprKind(Constexpr ? CSK_constexpr : CSK_unspecified); 6914 6915 if (!Type->hasExceptionSpec()) { 6916 // C++2a [except.spec]p3: 6917 // If a declaration of a function does not have a noexcept-specifier 6918 // [and] is defaulted on its first declaration, [...] the exception 6919 // specification is as specified below 6920 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo(); 6921 EPI.ExceptionSpec.Type = EST_Unevaluated; 6922 EPI.ExceptionSpec.SourceDecl = MD; 6923 MD->setType(Context.getFunctionType(ReturnType, 6924 llvm::makeArrayRef(&ArgType, 6925 ExpectedParams), 6926 EPI)); 6927 } 6928 } 6929 6930 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) { 6931 if (First) { 6932 SetDeclDeleted(MD, MD->getLocation()); 6933 if (!inTemplateInstantiation() && !HadError) { 6934 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM; 6935 if (ShouldDeleteForTypeMismatch) { 6936 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM; 6937 } else { 6938 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 6939 } 6940 } 6941 if (ShouldDeleteForTypeMismatch && !HadError) { 6942 Diag(MD->getLocation(), 6943 diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM; 6944 } 6945 } else { 6946 // C++11 [dcl.fct.def.default]p4: 6947 // [For a] user-provided explicitly-defaulted function [...] if such a 6948 // function is implicitly defined as deleted, the program is ill-formed. 6949 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM; 6950 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl"); 6951 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true); 6952 HadError = true; 6953 } 6954 } 6955 6956 if (HadError) 6957 MD->setInvalidDecl(); 6958 } 6959 6960 void Sema::CheckDelayedMemberExceptionSpecs() { 6961 decltype(DelayedOverridingExceptionSpecChecks) Overriding; 6962 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent; 6963 6964 std::swap(Overriding, DelayedOverridingExceptionSpecChecks); 6965 std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks); 6966 6967 // Perform any deferred checking of exception specifications for virtual 6968 // destructors. 6969 for (auto &Check : Overriding) 6970 CheckOverridingFunctionExceptionSpec(Check.first, Check.second); 6971 6972 // Perform any deferred checking of exception specifications for befriended 6973 // special members. 6974 for (auto &Check : Equivalent) 6975 CheckEquivalentExceptionSpec(Check.second, Check.first); 6976 } 6977 6978 namespace { 6979 /// CRTP base class for visiting operations performed by a special member 6980 /// function (or inherited constructor). 6981 template<typename Derived> 6982 struct SpecialMemberVisitor { 6983 Sema &S; 6984 CXXMethodDecl *MD; 6985 Sema::CXXSpecialMember CSM; 6986 Sema::InheritedConstructorInfo *ICI; 6987 6988 // Properties of the special member, computed for convenience. 6989 bool IsConstructor = false, IsAssignment = false, ConstArg = false; 6990 6991 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 6992 Sema::InheritedConstructorInfo *ICI) 6993 : S(S), MD(MD), CSM(CSM), ICI(ICI) { 6994 switch (CSM) { 6995 case Sema::CXXDefaultConstructor: 6996 case Sema::CXXCopyConstructor: 6997 case Sema::CXXMoveConstructor: 6998 IsConstructor = true; 6999 break; 7000 case Sema::CXXCopyAssignment: 7001 case Sema::CXXMoveAssignment: 7002 IsAssignment = true; 7003 break; 7004 case Sema::CXXDestructor: 7005 break; 7006 case Sema::CXXInvalid: 7007 llvm_unreachable("invalid special member kind"); 7008 } 7009 7010 if (MD->getNumParams()) { 7011 if (const ReferenceType *RT = 7012 MD->getParamDecl(0)->getType()->getAs<ReferenceType>()) 7013 ConstArg = RT->getPointeeType().isConstQualified(); 7014 } 7015 } 7016 7017 Derived &getDerived() { return static_cast<Derived&>(*this); } 7018 7019 /// Is this a "move" special member? 7020 bool isMove() const { 7021 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment; 7022 } 7023 7024 /// Look up the corresponding special member in the given class. 7025 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class, 7026 unsigned Quals, bool IsMutable) { 7027 return lookupCallFromSpecialMember(S, Class, CSM, Quals, 7028 ConstArg && !IsMutable); 7029 } 7030 7031 /// Look up the constructor for the specified base class to see if it's 7032 /// overridden due to this being an inherited constructor. 7033 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) { 7034 if (!ICI) 7035 return {}; 7036 assert(CSM == Sema::CXXDefaultConstructor); 7037 auto *BaseCtor = 7038 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor(); 7039 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first) 7040 return MD; 7041 return {}; 7042 } 7043 7044 /// A base or member subobject. 7045 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject; 7046 7047 /// Get the location to use for a subobject in diagnostics. 7048 static SourceLocation getSubobjectLoc(Subobject Subobj) { 7049 // FIXME: For an indirect virtual base, the direct base leading to 7050 // the indirect virtual base would be a more useful choice. 7051 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>()) 7052 return B->getBaseTypeLoc(); 7053 else 7054 return Subobj.get<FieldDecl*>()->getLocation(); 7055 } 7056 7057 enum BasesToVisit { 7058 /// Visit all non-virtual (direct) bases. 7059 VisitNonVirtualBases, 7060 /// Visit all direct bases, virtual or not. 7061 VisitDirectBases, 7062 /// Visit all non-virtual bases, and all virtual bases if the class 7063 /// is not abstract. 7064 VisitPotentiallyConstructedBases, 7065 /// Visit all direct or virtual bases. 7066 VisitAllBases 7067 }; 7068 7069 // Visit the bases and members of the class. 7070 bool visit(BasesToVisit Bases) { 7071 CXXRecordDecl *RD = MD->getParent(); 7072 7073 if (Bases == VisitPotentiallyConstructedBases) 7074 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases; 7075 7076 for (auto &B : RD->bases()) 7077 if ((Bases == VisitDirectBases || !B.isVirtual()) && 7078 getDerived().visitBase(&B)) 7079 return true; 7080 7081 if (Bases == VisitAllBases) 7082 for (auto &B : RD->vbases()) 7083 if (getDerived().visitBase(&B)) 7084 return true; 7085 7086 for (auto *F : RD->fields()) 7087 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() && 7088 getDerived().visitField(F)) 7089 return true; 7090 7091 return false; 7092 } 7093 }; 7094 } 7095 7096 namespace { 7097 struct SpecialMemberDeletionInfo 7098 : SpecialMemberVisitor<SpecialMemberDeletionInfo> { 7099 bool Diagnose; 7100 7101 SourceLocation Loc; 7102 7103 bool AllFieldsAreConst; 7104 7105 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD, 7106 Sema::CXXSpecialMember CSM, 7107 Sema::InheritedConstructorInfo *ICI, bool Diagnose) 7108 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose), 7109 Loc(MD->getLocation()), AllFieldsAreConst(true) {} 7110 7111 bool inUnion() const { return MD->getParent()->isUnion(); } 7112 7113 Sema::CXXSpecialMember getEffectiveCSM() { 7114 return ICI ? Sema::CXXInvalid : CSM; 7115 } 7116 7117 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType); 7118 7119 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); } 7120 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); } 7121 7122 bool shouldDeleteForBase(CXXBaseSpecifier *Base); 7123 bool shouldDeleteForField(FieldDecl *FD); 7124 bool shouldDeleteForAllConstMembers(); 7125 7126 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 7127 unsigned Quals); 7128 bool shouldDeleteForSubobjectCall(Subobject Subobj, 7129 Sema::SpecialMemberOverloadResult SMOR, 7130 bool IsDtorCallInCtor); 7131 7132 bool isAccessible(Subobject Subobj, CXXMethodDecl *D); 7133 }; 7134 } 7135 7136 /// Is the given special member inaccessible when used on the given 7137 /// sub-object. 7138 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj, 7139 CXXMethodDecl *target) { 7140 /// If we're operating on a base class, the object type is the 7141 /// type of this special member. 7142 QualType objectTy; 7143 AccessSpecifier access = target->getAccess(); 7144 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) { 7145 objectTy = S.Context.getTypeDeclType(MD->getParent()); 7146 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access); 7147 7148 // If we're operating on a field, the object type is the type of the field. 7149 } else { 7150 objectTy = S.Context.getTypeDeclType(target->getParent()); 7151 } 7152 7153 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy); 7154 } 7155 7156 /// Check whether we should delete a special member due to the implicit 7157 /// definition containing a call to a special member of a subobject. 7158 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall( 7159 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR, 7160 bool IsDtorCallInCtor) { 7161 CXXMethodDecl *Decl = SMOR.getMethod(); 7162 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 7163 7164 int DiagKind = -1; 7165 7166 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) 7167 DiagKind = !Decl ? 0 : 1; 7168 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 7169 DiagKind = 2; 7170 else if (!isAccessible(Subobj, Decl)) 7171 DiagKind = 3; 7172 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() && 7173 !Decl->isTrivial()) { 7174 // A member of a union must have a trivial corresponding special member. 7175 // As a weird special case, a destructor call from a union's constructor 7176 // must be accessible and non-deleted, but need not be trivial. Such a 7177 // destructor is never actually called, but is semantically checked as 7178 // if it were. 7179 DiagKind = 4; 7180 } 7181 7182 if (DiagKind == -1) 7183 return false; 7184 7185 if (Diagnose) { 7186 if (Field) { 7187 S.Diag(Field->getLocation(), 7188 diag::note_deleted_special_member_class_subobject) 7189 << getEffectiveCSM() << MD->getParent() << /*IsField*/true 7190 << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false; 7191 } else { 7192 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>(); 7193 S.Diag(Base->getBeginLoc(), 7194 diag::note_deleted_special_member_class_subobject) 7195 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 7196 << Base->getType() << DiagKind << IsDtorCallInCtor 7197 << /*IsObjCPtr*/false; 7198 } 7199 7200 if (DiagKind == 1) 7201 S.NoteDeletedFunction(Decl); 7202 // FIXME: Explain inaccessibility if DiagKind == 3. 7203 } 7204 7205 return true; 7206 } 7207 7208 /// Check whether we should delete a special member function due to having a 7209 /// direct or virtual base class or non-static data member of class type M. 7210 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject( 7211 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) { 7212 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 7213 bool IsMutable = Field && Field->isMutable(); 7214 7215 // C++11 [class.ctor]p5: 7216 // -- any direct or virtual base class, or non-static data member with no 7217 // brace-or-equal-initializer, has class type M (or array thereof) and 7218 // either M has no default constructor or overload resolution as applied 7219 // to M's default constructor results in an ambiguity or in a function 7220 // that is deleted or inaccessible 7221 // C++11 [class.copy]p11, C++11 [class.copy]p23: 7222 // -- a direct or virtual base class B that cannot be copied/moved because 7223 // overload resolution, as applied to B's corresponding special member, 7224 // results in an ambiguity or a function that is deleted or inaccessible 7225 // from the defaulted special member 7226 // C++11 [class.dtor]p5: 7227 // -- any direct or virtual base class [...] has a type with a destructor 7228 // that is deleted or inaccessible 7229 if (!(CSM == Sema::CXXDefaultConstructor && 7230 Field && Field->hasInClassInitializer()) && 7231 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable), 7232 false)) 7233 return true; 7234 7235 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 7236 // -- any direct or virtual base class or non-static data member has a 7237 // type with a destructor that is deleted or inaccessible 7238 if (IsConstructor) { 7239 Sema::SpecialMemberOverloadResult SMOR = 7240 S.LookupSpecialMember(Class, Sema::CXXDestructor, 7241 false, false, false, false, false); 7242 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true)) 7243 return true; 7244 } 7245 7246 return false; 7247 } 7248 7249 bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember( 7250 FieldDecl *FD, QualType FieldType) { 7251 // The defaulted special functions are defined as deleted if this is a variant 7252 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak 7253 // type under ARC. 7254 if (!FieldType.hasNonTrivialObjCLifetime()) 7255 return false; 7256 7257 // Don't make the defaulted default constructor defined as deleted if the 7258 // member has an in-class initializer. 7259 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) 7260 return false; 7261 7262 if (Diagnose) { 7263 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent()); 7264 S.Diag(FD->getLocation(), 7265 diag::note_deleted_special_member_class_subobject) 7266 << getEffectiveCSM() << ParentClass << /*IsField*/true 7267 << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true; 7268 } 7269 7270 return true; 7271 } 7272 7273 /// Check whether we should delete a special member function due to the class 7274 /// having a particular direct or virtual base class. 7275 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) { 7276 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl(); 7277 // If program is correct, BaseClass cannot be null, but if it is, the error 7278 // must be reported elsewhere. 7279 if (!BaseClass) 7280 return false; 7281 // If we have an inheriting constructor, check whether we're calling an 7282 // inherited constructor instead of a default constructor. 7283 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 7284 if (auto *BaseCtor = SMOR.getMethod()) { 7285 // Note that we do not check access along this path; other than that, 7286 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false); 7287 // FIXME: Check that the base has a usable destructor! Sink this into 7288 // shouldDeleteForClassSubobject. 7289 if (BaseCtor->isDeleted() && Diagnose) { 7290 S.Diag(Base->getBeginLoc(), 7291 diag::note_deleted_special_member_class_subobject) 7292 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false 7293 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false 7294 << /*IsObjCPtr*/false; 7295 S.NoteDeletedFunction(BaseCtor); 7296 } 7297 return BaseCtor->isDeleted(); 7298 } 7299 return shouldDeleteForClassSubobject(BaseClass, Base, 0); 7300 } 7301 7302 /// Check whether we should delete a special member function due to the class 7303 /// having a particular non-static data member. 7304 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) { 7305 QualType FieldType = S.Context.getBaseElementType(FD->getType()); 7306 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl(); 7307 7308 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType)) 7309 return true; 7310 7311 if (CSM == Sema::CXXDefaultConstructor) { 7312 // For a default constructor, all references must be initialized in-class 7313 // and, if a union, it must have a non-const member. 7314 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) { 7315 if (Diagnose) 7316 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 7317 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0; 7318 return true; 7319 } 7320 // C++11 [class.ctor]p5: any non-variant non-static data member of 7321 // const-qualified type (or array thereof) with no 7322 // brace-or-equal-initializer does not have a user-provided default 7323 // constructor. 7324 if (!inUnion() && FieldType.isConstQualified() && 7325 !FD->hasInClassInitializer() && 7326 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) { 7327 if (Diagnose) 7328 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field) 7329 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1; 7330 return true; 7331 } 7332 7333 if (inUnion() && !FieldType.isConstQualified()) 7334 AllFieldsAreConst = false; 7335 } else if (CSM == Sema::CXXCopyConstructor) { 7336 // For a copy constructor, data members must not be of rvalue reference 7337 // type. 7338 if (FieldType->isRValueReferenceType()) { 7339 if (Diagnose) 7340 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference) 7341 << MD->getParent() << FD << FieldType; 7342 return true; 7343 } 7344 } else if (IsAssignment) { 7345 // For an assignment operator, data members must not be of reference type. 7346 if (FieldType->isReferenceType()) { 7347 if (Diagnose) 7348 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 7349 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0; 7350 return true; 7351 } 7352 if (!FieldRecord && FieldType.isConstQualified()) { 7353 // C++11 [class.copy]p23: 7354 // -- a non-static data member of const non-class type (or array thereof) 7355 if (Diagnose) 7356 S.Diag(FD->getLocation(), diag::note_deleted_assign_field) 7357 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1; 7358 return true; 7359 } 7360 } 7361 7362 if (FieldRecord) { 7363 // Some additional restrictions exist on the variant members. 7364 if (!inUnion() && FieldRecord->isUnion() && 7365 FieldRecord->isAnonymousStructOrUnion()) { 7366 bool AllVariantFieldsAreConst = true; 7367 7368 // FIXME: Handle anonymous unions declared within anonymous unions. 7369 for (auto *UI : FieldRecord->fields()) { 7370 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType()); 7371 7372 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType)) 7373 return true; 7374 7375 if (!UnionFieldType.isConstQualified()) 7376 AllVariantFieldsAreConst = false; 7377 7378 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl(); 7379 if (UnionFieldRecord && 7380 shouldDeleteForClassSubobject(UnionFieldRecord, UI, 7381 UnionFieldType.getCVRQualifiers())) 7382 return true; 7383 } 7384 7385 // At least one member in each anonymous union must be non-const 7386 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst && 7387 !FieldRecord->field_empty()) { 7388 if (Diagnose) 7389 S.Diag(FieldRecord->getLocation(), 7390 diag::note_deleted_default_ctor_all_const) 7391 << !!ICI << MD->getParent() << /*anonymous union*/1; 7392 return true; 7393 } 7394 7395 // Don't check the implicit member of the anonymous union type. 7396 // This is technically non-conformant, but sanity demands it. 7397 return false; 7398 } 7399 7400 if (shouldDeleteForClassSubobject(FieldRecord, FD, 7401 FieldType.getCVRQualifiers())) 7402 return true; 7403 } 7404 7405 return false; 7406 } 7407 7408 /// C++11 [class.ctor] p5: 7409 /// A defaulted default constructor for a class X is defined as deleted if 7410 /// X is a union and all of its variant members are of const-qualified type. 7411 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() { 7412 // This is a silly definition, because it gives an empty union a deleted 7413 // default constructor. Don't do that. 7414 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) { 7415 bool AnyFields = false; 7416 for (auto *F : MD->getParent()->fields()) 7417 if ((AnyFields = !F->isUnnamedBitfield())) 7418 break; 7419 if (!AnyFields) 7420 return false; 7421 if (Diagnose) 7422 S.Diag(MD->getParent()->getLocation(), 7423 diag::note_deleted_default_ctor_all_const) 7424 << !!ICI << MD->getParent() << /*not anonymous union*/0; 7425 return true; 7426 } 7427 return false; 7428 } 7429 7430 /// Determine whether a defaulted special member function should be defined as 7431 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11, 7432 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5. 7433 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 7434 InheritedConstructorInfo *ICI, 7435 bool Diagnose) { 7436 if (MD->isInvalidDecl()) 7437 return false; 7438 CXXRecordDecl *RD = MD->getParent(); 7439 assert(!RD->isDependentType() && "do deletion after instantiation"); 7440 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl()) 7441 return false; 7442 7443 // C++11 [expr.lambda.prim]p19: 7444 // The closure type associated with a lambda-expression has a 7445 // deleted (8.4.3) default constructor and a deleted copy 7446 // assignment operator. 7447 // C++2a adds back these operators if the lambda has no lambda-capture. 7448 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() && 7449 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) { 7450 if (Diagnose) 7451 Diag(RD->getLocation(), diag::note_lambda_decl); 7452 return true; 7453 } 7454 7455 // For an anonymous struct or union, the copy and assignment special members 7456 // will never be used, so skip the check. For an anonymous union declared at 7457 // namespace scope, the constructor and destructor are used. 7458 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor && 7459 RD->isAnonymousStructOrUnion()) 7460 return false; 7461 7462 // C++11 [class.copy]p7, p18: 7463 // If the class definition declares a move constructor or move assignment 7464 // operator, an implicitly declared copy constructor or copy assignment 7465 // operator is defined as deleted. 7466 if (MD->isImplicit() && 7467 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) { 7468 CXXMethodDecl *UserDeclaredMove = nullptr; 7469 7470 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the 7471 // deletion of the corresponding copy operation, not both copy operations. 7472 // MSVC 2015 has adopted the standards conforming behavior. 7473 bool DeletesOnlyMatchingCopy = 7474 getLangOpts().MSVCCompat && 7475 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015); 7476 7477 if (RD->hasUserDeclaredMoveConstructor() && 7478 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) { 7479 if (!Diagnose) return true; 7480 7481 // Find any user-declared move constructor. 7482 for (auto *I : RD->ctors()) { 7483 if (I->isMoveConstructor()) { 7484 UserDeclaredMove = I; 7485 break; 7486 } 7487 } 7488 assert(UserDeclaredMove); 7489 } else if (RD->hasUserDeclaredMoveAssignment() && 7490 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) { 7491 if (!Diagnose) return true; 7492 7493 // Find any user-declared move assignment operator. 7494 for (auto *I : RD->methods()) { 7495 if (I->isMoveAssignmentOperator()) { 7496 UserDeclaredMove = I; 7497 break; 7498 } 7499 } 7500 assert(UserDeclaredMove); 7501 } 7502 7503 if (UserDeclaredMove) { 7504 Diag(UserDeclaredMove->getLocation(), 7505 diag::note_deleted_copy_user_declared_move) 7506 << (CSM == CXXCopyAssignment) << RD 7507 << UserDeclaredMove->isMoveAssignmentOperator(); 7508 return true; 7509 } 7510 } 7511 7512 // Do access control from the special member function 7513 ContextRAII MethodContext(*this, MD); 7514 7515 // C++11 [class.dtor]p5: 7516 // -- for a virtual destructor, lookup of the non-array deallocation function 7517 // results in an ambiguity or in a function that is deleted or inaccessible 7518 if (CSM == CXXDestructor && MD->isVirtual()) { 7519 FunctionDecl *OperatorDelete = nullptr; 7520 DeclarationName Name = 7521 Context.DeclarationNames.getCXXOperatorName(OO_Delete); 7522 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name, 7523 OperatorDelete, /*Diagnose*/false)) { 7524 if (Diagnose) 7525 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete); 7526 return true; 7527 } 7528 } 7529 7530 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose); 7531 7532 // Per DR1611, do not consider virtual bases of constructors of abstract 7533 // classes, since we are not going to construct them. 7534 // Per DR1658, do not consider virtual bases of destructors of abstract 7535 // classes either. 7536 // Per DR2180, for assignment operators we only assign (and thus only 7537 // consider) direct bases. 7538 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases 7539 : SMI.VisitPotentiallyConstructedBases)) 7540 return true; 7541 7542 if (SMI.shouldDeleteForAllConstMembers()) 7543 return true; 7544 7545 if (getLangOpts().CUDA) { 7546 // We should delete the special member in CUDA mode if target inference 7547 // failed. 7548 // For inherited constructors (non-null ICI), CSM may be passed so that MD 7549 // is treated as certain special member, which may not reflect what special 7550 // member MD really is. However inferCUDATargetForImplicitSpecialMember 7551 // expects CSM to match MD, therefore recalculate CSM. 7552 assert(ICI || CSM == getSpecialMember(MD)); 7553 auto RealCSM = CSM; 7554 if (ICI) 7555 RealCSM = getSpecialMember(MD); 7556 7557 return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD, 7558 SMI.ConstArg, Diagnose); 7559 } 7560 7561 return false; 7562 } 7563 7564 /// Perform lookup for a special member of the specified kind, and determine 7565 /// whether it is trivial. If the triviality can be determined without the 7566 /// lookup, skip it. This is intended for use when determining whether a 7567 /// special member of a containing object is trivial, and thus does not ever 7568 /// perform overload resolution for default constructors. 7569 /// 7570 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the 7571 /// member that was most likely to be intended to be trivial, if any. 7572 /// 7573 /// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to 7574 /// determine whether the special member is trivial. 7575 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD, 7576 Sema::CXXSpecialMember CSM, unsigned Quals, 7577 bool ConstRHS, 7578 Sema::TrivialABIHandling TAH, 7579 CXXMethodDecl **Selected) { 7580 if (Selected) 7581 *Selected = nullptr; 7582 7583 switch (CSM) { 7584 case Sema::CXXInvalid: 7585 llvm_unreachable("not a special member"); 7586 7587 case Sema::CXXDefaultConstructor: 7588 // C++11 [class.ctor]p5: 7589 // A default constructor is trivial if: 7590 // - all the [direct subobjects] have trivial default constructors 7591 // 7592 // Note, no overload resolution is performed in this case. 7593 if (RD->hasTrivialDefaultConstructor()) 7594 return true; 7595 7596 if (Selected) { 7597 // If there's a default constructor which could have been trivial, dig it 7598 // out. Otherwise, if there's any user-provided default constructor, point 7599 // to that as an example of why there's not a trivial one. 7600 CXXConstructorDecl *DefCtor = nullptr; 7601 if (RD->needsImplicitDefaultConstructor()) 7602 S.DeclareImplicitDefaultConstructor(RD); 7603 for (auto *CI : RD->ctors()) { 7604 if (!CI->isDefaultConstructor()) 7605 continue; 7606 DefCtor = CI; 7607 if (!DefCtor->isUserProvided()) 7608 break; 7609 } 7610 7611 *Selected = DefCtor; 7612 } 7613 7614 return false; 7615 7616 case Sema::CXXDestructor: 7617 // C++11 [class.dtor]p5: 7618 // A destructor is trivial if: 7619 // - all the direct [subobjects] have trivial destructors 7620 if (RD->hasTrivialDestructor() || 7621 (TAH == Sema::TAH_ConsiderTrivialABI && 7622 RD->hasTrivialDestructorForCall())) 7623 return true; 7624 7625 if (Selected) { 7626 if (RD->needsImplicitDestructor()) 7627 S.DeclareImplicitDestructor(RD); 7628 *Selected = RD->getDestructor(); 7629 } 7630 7631 return false; 7632 7633 case Sema::CXXCopyConstructor: 7634 // C++11 [class.copy]p12: 7635 // A copy constructor is trivial if: 7636 // - the constructor selected to copy each direct [subobject] is trivial 7637 if (RD->hasTrivialCopyConstructor() || 7638 (TAH == Sema::TAH_ConsiderTrivialABI && 7639 RD->hasTrivialCopyConstructorForCall())) { 7640 if (Quals == Qualifiers::Const) 7641 // We must either select the trivial copy constructor or reach an 7642 // ambiguity; no need to actually perform overload resolution. 7643 return true; 7644 } else if (!Selected) { 7645 return false; 7646 } 7647 // In C++98, we are not supposed to perform overload resolution here, but we 7648 // treat that as a language defect, as suggested on cxx-abi-dev, to treat 7649 // cases like B as having a non-trivial copy constructor: 7650 // struct A { template<typename T> A(T&); }; 7651 // struct B { mutable A a; }; 7652 goto NeedOverloadResolution; 7653 7654 case Sema::CXXCopyAssignment: 7655 // C++11 [class.copy]p25: 7656 // A copy assignment operator is trivial if: 7657 // - the assignment operator selected to copy each direct [subobject] is 7658 // trivial 7659 if (RD->hasTrivialCopyAssignment()) { 7660 if (Quals == Qualifiers::Const) 7661 return true; 7662 } else if (!Selected) { 7663 return false; 7664 } 7665 // In C++98, we are not supposed to perform overload resolution here, but we 7666 // treat that as a language defect. 7667 goto NeedOverloadResolution; 7668 7669 case Sema::CXXMoveConstructor: 7670 case Sema::CXXMoveAssignment: 7671 NeedOverloadResolution: 7672 Sema::SpecialMemberOverloadResult SMOR = 7673 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS); 7674 7675 // The standard doesn't describe how to behave if the lookup is ambiguous. 7676 // We treat it as not making the member non-trivial, just like the standard 7677 // mandates for the default constructor. This should rarely matter, because 7678 // the member will also be deleted. 7679 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous) 7680 return true; 7681 7682 if (!SMOR.getMethod()) { 7683 assert(SMOR.getKind() == 7684 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted); 7685 return false; 7686 } 7687 7688 // We deliberately don't check if we found a deleted special member. We're 7689 // not supposed to! 7690 if (Selected) 7691 *Selected = SMOR.getMethod(); 7692 7693 if (TAH == Sema::TAH_ConsiderTrivialABI && 7694 (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor)) 7695 return SMOR.getMethod()->isTrivialForCall(); 7696 return SMOR.getMethod()->isTrivial(); 7697 } 7698 7699 llvm_unreachable("unknown special method kind"); 7700 } 7701 7702 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) { 7703 for (auto *CI : RD->ctors()) 7704 if (!CI->isImplicit()) 7705 return CI; 7706 7707 // Look for constructor templates. 7708 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter; 7709 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) { 7710 if (CXXConstructorDecl *CD = 7711 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl())) 7712 return CD; 7713 } 7714 7715 return nullptr; 7716 } 7717 7718 /// The kind of subobject we are checking for triviality. The values of this 7719 /// enumeration are used in diagnostics. 7720 enum TrivialSubobjectKind { 7721 /// The subobject is a base class. 7722 TSK_BaseClass, 7723 /// The subobject is a non-static data member. 7724 TSK_Field, 7725 /// The object is actually the complete object. 7726 TSK_CompleteObject 7727 }; 7728 7729 /// Check whether the special member selected for a given type would be trivial. 7730 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc, 7731 QualType SubType, bool ConstRHS, 7732 Sema::CXXSpecialMember CSM, 7733 TrivialSubobjectKind Kind, 7734 Sema::TrivialABIHandling TAH, bool Diagnose) { 7735 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl(); 7736 if (!SubRD) 7737 return true; 7738 7739 CXXMethodDecl *Selected; 7740 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(), 7741 ConstRHS, TAH, Diagnose ? &Selected : nullptr)) 7742 return true; 7743 7744 if (Diagnose) { 7745 if (ConstRHS) 7746 SubType.addConst(); 7747 7748 if (!Selected && CSM == Sema::CXXDefaultConstructor) { 7749 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor) 7750 << Kind << SubType.getUnqualifiedType(); 7751 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD)) 7752 S.Diag(CD->getLocation(), diag::note_user_declared_ctor); 7753 } else if (!Selected) 7754 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy) 7755 << Kind << SubType.getUnqualifiedType() << CSM << SubType; 7756 else if (Selected->isUserProvided()) { 7757 if (Kind == TSK_CompleteObject) 7758 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided) 7759 << Kind << SubType.getUnqualifiedType() << CSM; 7760 else { 7761 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided) 7762 << Kind << SubType.getUnqualifiedType() << CSM; 7763 S.Diag(Selected->getLocation(), diag::note_declared_at); 7764 } 7765 } else { 7766 if (Kind != TSK_CompleteObject) 7767 S.Diag(SubobjLoc, diag::note_nontrivial_subobject) 7768 << Kind << SubType.getUnqualifiedType() << CSM; 7769 7770 // Explain why the defaulted or deleted special member isn't trivial. 7771 S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI, 7772 Diagnose); 7773 } 7774 } 7775 7776 return false; 7777 } 7778 7779 /// Check whether the members of a class type allow a special member to be 7780 /// trivial. 7781 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD, 7782 Sema::CXXSpecialMember CSM, 7783 bool ConstArg, 7784 Sema::TrivialABIHandling TAH, 7785 bool Diagnose) { 7786 for (const auto *FI : RD->fields()) { 7787 if (FI->isInvalidDecl() || FI->isUnnamedBitfield()) 7788 continue; 7789 7790 QualType FieldType = S.Context.getBaseElementType(FI->getType()); 7791 7792 // Pretend anonymous struct or union members are members of this class. 7793 if (FI->isAnonymousStructOrUnion()) { 7794 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(), 7795 CSM, ConstArg, TAH, Diagnose)) 7796 return false; 7797 continue; 7798 } 7799 7800 // C++11 [class.ctor]p5: 7801 // A default constructor is trivial if [...] 7802 // -- no non-static data member of its class has a 7803 // brace-or-equal-initializer 7804 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) { 7805 if (Diagnose) 7806 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI; 7807 return false; 7808 } 7809 7810 // Objective C ARC 4.3.5: 7811 // [...] nontrivally ownership-qualified types are [...] not trivially 7812 // default constructible, copy constructible, move constructible, copy 7813 // assignable, move assignable, or destructible [...] 7814 if (FieldType.hasNonTrivialObjCLifetime()) { 7815 if (Diagnose) 7816 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership) 7817 << RD << FieldType.getObjCLifetime(); 7818 return false; 7819 } 7820 7821 bool ConstRHS = ConstArg && !FI->isMutable(); 7822 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS, 7823 CSM, TSK_Field, TAH, Diagnose)) 7824 return false; 7825 } 7826 7827 return true; 7828 } 7829 7830 /// Diagnose why the specified class does not have a trivial special member of 7831 /// the given kind. 7832 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) { 7833 QualType Ty = Context.getRecordType(RD); 7834 7835 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment); 7836 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM, 7837 TSK_CompleteObject, TAH_IgnoreTrivialABI, 7838 /*Diagnose*/true); 7839 } 7840 7841 /// Determine whether a defaulted or deleted special member function is trivial, 7842 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12, 7843 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5. 7844 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, 7845 TrivialABIHandling TAH, bool Diagnose) { 7846 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough"); 7847 7848 CXXRecordDecl *RD = MD->getParent(); 7849 7850 bool ConstArg = false; 7851 7852 // C++11 [class.copy]p12, p25: [DR1593] 7853 // A [special member] is trivial if [...] its parameter-type-list is 7854 // equivalent to the parameter-type-list of an implicit declaration [...] 7855 switch (CSM) { 7856 case CXXDefaultConstructor: 7857 case CXXDestructor: 7858 // Trivial default constructors and destructors cannot have parameters. 7859 break; 7860 7861 case CXXCopyConstructor: 7862 case CXXCopyAssignment: { 7863 // Trivial copy operations always have const, non-volatile parameter types. 7864 ConstArg = true; 7865 const ParmVarDecl *Param0 = MD->getParamDecl(0); 7866 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>(); 7867 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) { 7868 if (Diagnose) 7869 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 7870 << Param0->getSourceRange() << Param0->getType() 7871 << Context.getLValueReferenceType( 7872 Context.getRecordType(RD).withConst()); 7873 return false; 7874 } 7875 break; 7876 } 7877 7878 case CXXMoveConstructor: 7879 case CXXMoveAssignment: { 7880 // Trivial move operations always have non-cv-qualified parameters. 7881 const ParmVarDecl *Param0 = MD->getParamDecl(0); 7882 const RValueReferenceType *RT = 7883 Param0->getType()->getAs<RValueReferenceType>(); 7884 if (!RT || RT->getPointeeType().getCVRQualifiers()) { 7885 if (Diagnose) 7886 Diag(Param0->getLocation(), diag::note_nontrivial_param_type) 7887 << Param0->getSourceRange() << Param0->getType() 7888 << Context.getRValueReferenceType(Context.getRecordType(RD)); 7889 return false; 7890 } 7891 break; 7892 } 7893 7894 case CXXInvalid: 7895 llvm_unreachable("not a special member"); 7896 } 7897 7898 if (MD->getMinRequiredArguments() < MD->getNumParams()) { 7899 if (Diagnose) 7900 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(), 7901 diag::note_nontrivial_default_arg) 7902 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange(); 7903 return false; 7904 } 7905 if (MD->isVariadic()) { 7906 if (Diagnose) 7907 Diag(MD->getLocation(), diag::note_nontrivial_variadic); 7908 return false; 7909 } 7910 7911 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 7912 // A copy/move [constructor or assignment operator] is trivial if 7913 // -- the [member] selected to copy/move each direct base class subobject 7914 // is trivial 7915 // 7916 // C++11 [class.copy]p12, C++11 [class.copy]p25: 7917 // A [default constructor or destructor] is trivial if 7918 // -- all the direct base classes have trivial [default constructors or 7919 // destructors] 7920 for (const auto &BI : RD->bases()) 7921 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(), 7922 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose)) 7923 return false; 7924 7925 // C++11 [class.ctor]p5, C++11 [class.dtor]p5: 7926 // A copy/move [constructor or assignment operator] for a class X is 7927 // trivial if 7928 // -- for each non-static data member of X that is of class type (or array 7929 // thereof), the constructor selected to copy/move that member is 7930 // trivial 7931 // 7932 // C++11 [class.copy]p12, C++11 [class.copy]p25: 7933 // A [default constructor or destructor] is trivial if 7934 // -- for all of the non-static data members of its class that are of class 7935 // type (or array thereof), each such class has a trivial [default 7936 // constructor or destructor] 7937 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose)) 7938 return false; 7939 7940 // C++11 [class.dtor]p5: 7941 // A destructor is trivial if [...] 7942 // -- the destructor is not virtual 7943 if (CSM == CXXDestructor && MD->isVirtual()) { 7944 if (Diagnose) 7945 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD; 7946 return false; 7947 } 7948 7949 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 7950 // A [special member] for class X is trivial if [...] 7951 // -- class X has no virtual functions and no virtual base classes 7952 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) { 7953 if (!Diagnose) 7954 return false; 7955 7956 if (RD->getNumVBases()) { 7957 // Check for virtual bases. We already know that the corresponding 7958 // member in all bases is trivial, so vbases must all be direct. 7959 CXXBaseSpecifier &BS = *RD->vbases_begin(); 7960 assert(BS.isVirtual()); 7961 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1; 7962 return false; 7963 } 7964 7965 // Must have a virtual method. 7966 for (const auto *MI : RD->methods()) { 7967 if (MI->isVirtual()) { 7968 SourceLocation MLoc = MI->getBeginLoc(); 7969 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0; 7970 return false; 7971 } 7972 } 7973 7974 llvm_unreachable("dynamic class with no vbases and no virtual functions"); 7975 } 7976 7977 // Looks like it's trivial! 7978 return true; 7979 } 7980 7981 namespace { 7982 struct FindHiddenVirtualMethod { 7983 Sema *S; 7984 CXXMethodDecl *Method; 7985 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods; 7986 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 7987 7988 private: 7989 /// Check whether any most overridden method from MD in Methods 7990 static bool CheckMostOverridenMethods( 7991 const CXXMethodDecl *MD, 7992 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) { 7993 if (MD->size_overridden_methods() == 0) 7994 return Methods.count(MD->getCanonicalDecl()); 7995 for (const CXXMethodDecl *O : MD->overridden_methods()) 7996 if (CheckMostOverridenMethods(O, Methods)) 7997 return true; 7998 return false; 7999 } 8000 8001 public: 8002 /// Member lookup function that determines whether a given C++ 8003 /// method overloads virtual methods in a base class without overriding any, 8004 /// to be used with CXXRecordDecl::lookupInBases(). 8005 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 8006 RecordDecl *BaseRecord = 8007 Specifier->getType()->getAs<RecordType>()->getDecl(); 8008 8009 DeclarationName Name = Method->getDeclName(); 8010 assert(Name.getNameKind() == DeclarationName::Identifier); 8011 8012 bool foundSameNameMethod = false; 8013 SmallVector<CXXMethodDecl *, 8> overloadedMethods; 8014 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 8015 Path.Decls = Path.Decls.slice(1)) { 8016 NamedDecl *D = Path.Decls.front(); 8017 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 8018 MD = MD->getCanonicalDecl(); 8019 foundSameNameMethod = true; 8020 // Interested only in hidden virtual methods. 8021 if (!MD->isVirtual()) 8022 continue; 8023 // If the method we are checking overrides a method from its base 8024 // don't warn about the other overloaded methods. Clang deviates from 8025 // GCC by only diagnosing overloads of inherited virtual functions that 8026 // do not override any other virtual functions in the base. GCC's 8027 // -Woverloaded-virtual diagnoses any derived function hiding a virtual 8028 // function from a base class. These cases may be better served by a 8029 // warning (not specific to virtual functions) on call sites when the 8030 // call would select a different function from the base class, were it 8031 // visible. 8032 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example. 8033 if (!S->IsOverload(Method, MD, false)) 8034 return true; 8035 // Collect the overload only if its hidden. 8036 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods)) 8037 overloadedMethods.push_back(MD); 8038 } 8039 } 8040 8041 if (foundSameNameMethod) 8042 OverloadedMethods.append(overloadedMethods.begin(), 8043 overloadedMethods.end()); 8044 return foundSameNameMethod; 8045 } 8046 }; 8047 } // end anonymous namespace 8048 8049 /// Add the most overriden methods from MD to Methods 8050 static void AddMostOverridenMethods(const CXXMethodDecl *MD, 8051 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) { 8052 if (MD->size_overridden_methods() == 0) 8053 Methods.insert(MD->getCanonicalDecl()); 8054 else 8055 for (const CXXMethodDecl *O : MD->overridden_methods()) 8056 AddMostOverridenMethods(O, Methods); 8057 } 8058 8059 /// Check if a method overloads virtual methods in a base class without 8060 /// overriding any. 8061 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD, 8062 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 8063 if (!MD->getDeclName().isIdentifier()) 8064 return; 8065 8066 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases. 8067 /*bool RecordPaths=*/false, 8068 /*bool DetectVirtual=*/false); 8069 FindHiddenVirtualMethod FHVM; 8070 FHVM.Method = MD; 8071 FHVM.S = this; 8072 8073 // Keep the base methods that were overridden or introduced in the subclass 8074 // by 'using' in a set. A base method not in this set is hidden. 8075 CXXRecordDecl *DC = MD->getParent(); 8076 DeclContext::lookup_result R = DC->lookup(MD->getDeclName()); 8077 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) { 8078 NamedDecl *ND = *I; 8079 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I)) 8080 ND = shad->getTargetDecl(); 8081 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 8082 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods); 8083 } 8084 8085 if (DC->lookupInBases(FHVM, Paths)) 8086 OverloadedMethods = FHVM.OverloadedMethods; 8087 } 8088 8089 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD, 8090 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) { 8091 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) { 8092 CXXMethodDecl *overloadedMD = OverloadedMethods[i]; 8093 PartialDiagnostic PD = PDiag( 8094 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD; 8095 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType()); 8096 Diag(overloadedMD->getLocation(), PD); 8097 } 8098 } 8099 8100 /// Diagnose methods which overload virtual methods in a base class 8101 /// without overriding any. 8102 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) { 8103 if (MD->isInvalidDecl()) 8104 return; 8105 8106 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation())) 8107 return; 8108 8109 SmallVector<CXXMethodDecl *, 8> OverloadedMethods; 8110 FindHiddenVirtualMethods(MD, OverloadedMethods); 8111 if (!OverloadedMethods.empty()) { 8112 Diag(MD->getLocation(), diag::warn_overloaded_virtual) 8113 << MD << (OverloadedMethods.size() > 1); 8114 8115 NoteHiddenVirtualMethods(MD, OverloadedMethods); 8116 } 8117 } 8118 8119 void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) { 8120 auto PrintDiagAndRemoveAttr = [&]() { 8121 // No diagnostics if this is a template instantiation. 8122 if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) 8123 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(), 8124 diag::ext_cannot_use_trivial_abi) << &RD; 8125 RD.dropAttr<TrivialABIAttr>(); 8126 }; 8127 8128 // Ill-formed if the struct has virtual functions. 8129 if (RD.isPolymorphic()) { 8130 PrintDiagAndRemoveAttr(); 8131 return; 8132 } 8133 8134 for (const auto &B : RD.bases()) { 8135 // Ill-formed if the base class is non-trivial for the purpose of calls or a 8136 // virtual base. 8137 if ((!B.getType()->isDependentType() && 8138 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) || 8139 B.isVirtual()) { 8140 PrintDiagAndRemoveAttr(); 8141 return; 8142 } 8143 } 8144 8145 for (const auto *FD : RD.fields()) { 8146 // Ill-formed if the field is an ObjectiveC pointer or of a type that is 8147 // non-trivial for the purpose of calls. 8148 QualType FT = FD->getType(); 8149 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) { 8150 PrintDiagAndRemoveAttr(); 8151 return; 8152 } 8153 8154 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>()) 8155 if (!RT->isDependentType() && 8156 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) { 8157 PrintDiagAndRemoveAttr(); 8158 return; 8159 } 8160 } 8161 } 8162 8163 void Sema::ActOnFinishCXXMemberSpecification( 8164 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, 8165 SourceLocation RBrac, const ParsedAttributesView &AttrList) { 8166 if (!TagDecl) 8167 return; 8168 8169 AdjustDeclIfTemplate(TagDecl); 8170 8171 for (const ParsedAttr &AL : AttrList) { 8172 if (AL.getKind() != ParsedAttr::AT_Visibility) 8173 continue; 8174 AL.setInvalid(); 8175 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL; 8176 } 8177 8178 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef( 8179 // strict aliasing violation! 8180 reinterpret_cast<Decl**>(FieldCollector->getCurFields()), 8181 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList); 8182 8183 CheckCompletedCXXClass(cast<CXXRecordDecl>(TagDecl)); 8184 } 8185 8186 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared 8187 /// special functions, such as the default constructor, copy 8188 /// constructor, or destructor, to the given C++ class (C++ 8189 /// [special]p1). This routine can only be executed just before the 8190 /// definition of the class is complete. 8191 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) { 8192 if (ClassDecl->needsImplicitDefaultConstructor()) { 8193 ++getASTContext().NumImplicitDefaultConstructors; 8194 8195 if (ClassDecl->hasInheritedConstructor()) 8196 DeclareImplicitDefaultConstructor(ClassDecl); 8197 } 8198 8199 if (ClassDecl->needsImplicitCopyConstructor()) { 8200 ++getASTContext().NumImplicitCopyConstructors; 8201 8202 // If the properties or semantics of the copy constructor couldn't be 8203 // determined while the class was being declared, force a declaration 8204 // of it now. 8205 if (ClassDecl->needsOverloadResolutionForCopyConstructor() || 8206 ClassDecl->hasInheritedConstructor()) 8207 DeclareImplicitCopyConstructor(ClassDecl); 8208 // For the MS ABI we need to know whether the copy ctor is deleted. A 8209 // prerequisite for deleting the implicit copy ctor is that the class has a 8210 // move ctor or move assignment that is either user-declared or whose 8211 // semantics are inherited from a subobject. FIXME: We should provide a more 8212 // direct way for CodeGen to ask whether the constructor was deleted. 8213 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 8214 (ClassDecl->hasUserDeclaredMoveConstructor() || 8215 ClassDecl->needsOverloadResolutionForMoveConstructor() || 8216 ClassDecl->hasUserDeclaredMoveAssignment() || 8217 ClassDecl->needsOverloadResolutionForMoveAssignment())) 8218 DeclareImplicitCopyConstructor(ClassDecl); 8219 } 8220 8221 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) { 8222 ++getASTContext().NumImplicitMoveConstructors; 8223 8224 if (ClassDecl->needsOverloadResolutionForMoveConstructor() || 8225 ClassDecl->hasInheritedConstructor()) 8226 DeclareImplicitMoveConstructor(ClassDecl); 8227 } 8228 8229 if (ClassDecl->needsImplicitCopyAssignment()) { 8230 ++getASTContext().NumImplicitCopyAssignmentOperators; 8231 8232 // If we have a dynamic class, then the copy assignment operator may be 8233 // virtual, so we have to declare it immediately. This ensures that, e.g., 8234 // it shows up in the right place in the vtable and that we diagnose 8235 // problems with the implicit exception specification. 8236 if (ClassDecl->isDynamicClass() || 8237 ClassDecl->needsOverloadResolutionForCopyAssignment() || 8238 ClassDecl->hasInheritedAssignment()) 8239 DeclareImplicitCopyAssignment(ClassDecl); 8240 } 8241 8242 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) { 8243 ++getASTContext().NumImplicitMoveAssignmentOperators; 8244 8245 // Likewise for the move assignment operator. 8246 if (ClassDecl->isDynamicClass() || 8247 ClassDecl->needsOverloadResolutionForMoveAssignment() || 8248 ClassDecl->hasInheritedAssignment()) 8249 DeclareImplicitMoveAssignment(ClassDecl); 8250 } 8251 8252 if (ClassDecl->needsImplicitDestructor()) { 8253 ++getASTContext().NumImplicitDestructors; 8254 8255 // If we have a dynamic class, then the destructor may be virtual, so we 8256 // have to declare the destructor immediately. This ensures that, e.g., it 8257 // shows up in the right place in the vtable and that we diagnose problems 8258 // with the implicit exception specification. 8259 if (ClassDecl->isDynamicClass() || 8260 ClassDecl->needsOverloadResolutionForDestructor()) 8261 DeclareImplicitDestructor(ClassDecl); 8262 } 8263 } 8264 8265 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) { 8266 if (!D) 8267 return 0; 8268 8269 // The order of template parameters is not important here. All names 8270 // get added to the same scope. 8271 SmallVector<TemplateParameterList *, 4> ParameterLists; 8272 8273 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 8274 D = TD->getTemplatedDecl(); 8275 8276 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) 8277 ParameterLists.push_back(PSD->getTemplateParameters()); 8278 8279 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) { 8280 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i) 8281 ParameterLists.push_back(DD->getTemplateParameterList(i)); 8282 8283 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 8284 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) 8285 ParameterLists.push_back(FTD->getTemplateParameters()); 8286 } 8287 } 8288 8289 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 8290 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i) 8291 ParameterLists.push_back(TD->getTemplateParameterList(i)); 8292 8293 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) { 8294 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) 8295 ParameterLists.push_back(CTD->getTemplateParameters()); 8296 } 8297 } 8298 8299 unsigned Count = 0; 8300 for (TemplateParameterList *Params : ParameterLists) { 8301 if (Params->size() > 0) 8302 // Ignore explicit specializations; they don't contribute to the template 8303 // depth. 8304 ++Count; 8305 for (NamedDecl *Param : *Params) { 8306 if (Param->getDeclName()) { 8307 S->AddDecl(Param); 8308 IdResolver.AddDecl(Param); 8309 } 8310 } 8311 } 8312 8313 return Count; 8314 } 8315 8316 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 8317 if (!RecordD) return; 8318 AdjustDeclIfTemplate(RecordD); 8319 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD); 8320 PushDeclContext(S, Record); 8321 } 8322 8323 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) { 8324 if (!RecordD) return; 8325 PopDeclContext(); 8326 } 8327 8328 /// This is used to implement the constant expression evaluation part of the 8329 /// attribute enable_if extension. There is nothing in standard C++ which would 8330 /// require reentering parameters. 8331 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) { 8332 if (!Param) 8333 return; 8334 8335 S->AddDecl(Param); 8336 if (Param->getDeclName()) 8337 IdResolver.AddDecl(Param); 8338 } 8339 8340 /// ActOnStartDelayedCXXMethodDeclaration - We have completed 8341 /// parsing a top-level (non-nested) C++ class, and we are now 8342 /// parsing those parts of the given Method declaration that could 8343 /// not be parsed earlier (C++ [class.mem]p2), such as default 8344 /// arguments. This action should enter the scope of the given 8345 /// Method declaration as if we had just parsed the qualified method 8346 /// name. However, it should not bring the parameters into scope; 8347 /// that will be performed by ActOnDelayedCXXMethodParameter. 8348 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 8349 } 8350 8351 /// ActOnDelayedCXXMethodParameter - We've already started a delayed 8352 /// C++ method declaration. We're (re-)introducing the given 8353 /// function parameter into scope for use in parsing later parts of 8354 /// the method declaration. For example, we could see an 8355 /// ActOnParamDefaultArgument event for this parameter. 8356 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) { 8357 if (!ParamD) 8358 return; 8359 8360 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD); 8361 8362 // If this parameter has an unparsed default argument, clear it out 8363 // to make way for the parsed default argument. 8364 if (Param->hasUnparsedDefaultArg()) 8365 Param->setDefaultArg(nullptr); 8366 8367 S->AddDecl(Param); 8368 if (Param->getDeclName()) 8369 IdResolver.AddDecl(Param); 8370 } 8371 8372 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished 8373 /// processing the delayed method declaration for Method. The method 8374 /// declaration is now considered finished. There may be a separate 8375 /// ActOnStartOfFunctionDef action later (not necessarily 8376 /// immediately!) for this method, if it was also defined inside the 8377 /// class body. 8378 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) { 8379 if (!MethodD) 8380 return; 8381 8382 AdjustDeclIfTemplate(MethodD); 8383 8384 FunctionDecl *Method = cast<FunctionDecl>(MethodD); 8385 8386 // Now that we have our default arguments, check the constructor 8387 // again. It could produce additional diagnostics or affect whether 8388 // the class has implicitly-declared destructors, among other 8389 // things. 8390 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) 8391 CheckConstructor(Constructor); 8392 8393 // Check the default arguments, which we may have added. 8394 if (!Method->isInvalidDecl()) 8395 CheckCXXDefaultArguments(Method); 8396 } 8397 8398 // Emit the given diagnostic for each non-address-space qualifier. 8399 // Common part of CheckConstructorDeclarator and CheckDestructorDeclarator. 8400 static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) { 8401 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 8402 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) { 8403 bool DiagOccured = false; 8404 FTI.MethodQualifiers->forEachQualifier( 8405 [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName, 8406 SourceLocation SL) { 8407 // This diagnostic should be emitted on any qualifier except an addr 8408 // space qualifier. However, forEachQualifier currently doesn't visit 8409 // addr space qualifiers, so there's no way to write this condition 8410 // right now; we just diagnose on everything. 8411 S.Diag(SL, DiagID) << QualName << SourceRange(SL); 8412 DiagOccured = true; 8413 }); 8414 if (DiagOccured) 8415 D.setInvalidType(); 8416 } 8417 } 8418 8419 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check 8420 /// the well-formedness of the constructor declarator @p D with type @p 8421 /// R. If there are any errors in the declarator, this routine will 8422 /// emit diagnostics and set the invalid bit to true. In any case, the type 8423 /// will be updated to reflect a well-formed type for the constructor and 8424 /// returned. 8425 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R, 8426 StorageClass &SC) { 8427 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 8428 8429 // C++ [class.ctor]p3: 8430 // A constructor shall not be virtual (10.3) or static (9.4). A 8431 // constructor can be invoked for a const, volatile or const 8432 // volatile object. A constructor shall not be declared const, 8433 // volatile, or const volatile (9.3.2). 8434 if (isVirtual) { 8435 if (!D.isInvalidType()) 8436 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 8437 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc()) 8438 << SourceRange(D.getIdentifierLoc()); 8439 D.setInvalidType(); 8440 } 8441 if (SC == SC_Static) { 8442 if (!D.isInvalidType()) 8443 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be) 8444 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 8445 << SourceRange(D.getIdentifierLoc()); 8446 D.setInvalidType(); 8447 SC = SC_None; 8448 } 8449 8450 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 8451 diagnoseIgnoredQualifiers( 8452 diag::err_constructor_return_type, TypeQuals, SourceLocation(), 8453 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(), 8454 D.getDeclSpec().getRestrictSpecLoc(), 8455 D.getDeclSpec().getAtomicSpecLoc()); 8456 D.setInvalidType(); 8457 } 8458 8459 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor); 8460 8461 // C++0x [class.ctor]p4: 8462 // A constructor shall not be declared with a ref-qualifier. 8463 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 8464 if (FTI.hasRefQualifier()) { 8465 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor) 8466 << FTI.RefQualifierIsLValueRef 8467 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 8468 D.setInvalidType(); 8469 } 8470 8471 // Rebuild the function type "R" without any type qualifiers (in 8472 // case any of the errors above fired) and with "void" as the 8473 // return type, since constructors don't have return types. 8474 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 8475 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType()) 8476 return R; 8477 8478 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 8479 EPI.TypeQuals = Qualifiers(); 8480 EPI.RefQualifier = RQ_None; 8481 8482 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI); 8483 } 8484 8485 /// CheckConstructor - Checks a fully-formed constructor for 8486 /// well-formedness, issuing any diagnostics required. Returns true if 8487 /// the constructor declarator is invalid. 8488 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) { 8489 CXXRecordDecl *ClassDecl 8490 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext()); 8491 if (!ClassDecl) 8492 return Constructor->setInvalidDecl(); 8493 8494 // C++ [class.copy]p3: 8495 // A declaration of a constructor for a class X is ill-formed if 8496 // its first parameter is of type (optionally cv-qualified) X and 8497 // either there are no other parameters or else all other 8498 // parameters have default arguments. 8499 if (!Constructor->isInvalidDecl() && 8500 ((Constructor->getNumParams() == 1) || 8501 (Constructor->getNumParams() > 1 && 8502 Constructor->getParamDecl(1)->hasDefaultArg())) && 8503 Constructor->getTemplateSpecializationKind() 8504 != TSK_ImplicitInstantiation) { 8505 QualType ParamType = Constructor->getParamDecl(0)->getType(); 8506 QualType ClassTy = Context.getTagDeclType(ClassDecl); 8507 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) { 8508 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation(); 8509 const char *ConstRef 8510 = Constructor->getParamDecl(0)->getIdentifier() ? "const &" 8511 : " const &"; 8512 Diag(ParamLoc, diag::err_constructor_byvalue_arg) 8513 << FixItHint::CreateInsertion(ParamLoc, ConstRef); 8514 8515 // FIXME: Rather that making the constructor invalid, we should endeavor 8516 // to fix the type. 8517 Constructor->setInvalidDecl(); 8518 } 8519 } 8520 } 8521 8522 /// CheckDestructor - Checks a fully-formed destructor definition for 8523 /// well-formedness, issuing any diagnostics required. Returns true 8524 /// on error. 8525 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) { 8526 CXXRecordDecl *RD = Destructor->getParent(); 8527 8528 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) { 8529 SourceLocation Loc; 8530 8531 if (!Destructor->isImplicit()) 8532 Loc = Destructor->getLocation(); 8533 else 8534 Loc = RD->getLocation(); 8535 8536 // If we have a virtual destructor, look up the deallocation function 8537 if (FunctionDecl *OperatorDelete = 8538 FindDeallocationFunctionForDestructor(Loc, RD)) { 8539 Expr *ThisArg = nullptr; 8540 8541 // If the notional 'delete this' expression requires a non-trivial 8542 // conversion from 'this' to the type of a destroying operator delete's 8543 // first parameter, perform that conversion now. 8544 if (OperatorDelete->isDestroyingOperatorDelete()) { 8545 QualType ParamType = OperatorDelete->getParamDecl(0)->getType(); 8546 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) { 8547 // C++ [class.dtor]p13: 8548 // ... as if for the expression 'delete this' appearing in a 8549 // non-virtual destructor of the destructor's class. 8550 ContextRAII SwitchContext(*this, Destructor); 8551 ExprResult This = 8552 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation()); 8553 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?"); 8554 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing); 8555 if (This.isInvalid()) { 8556 // FIXME: Register this as a context note so that it comes out 8557 // in the right order. 8558 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here); 8559 return true; 8560 } 8561 ThisArg = This.get(); 8562 } 8563 } 8564 8565 DiagnoseUseOfDecl(OperatorDelete, Loc); 8566 MarkFunctionReferenced(Loc, OperatorDelete); 8567 Destructor->setOperatorDelete(OperatorDelete, ThisArg); 8568 } 8569 } 8570 8571 return false; 8572 } 8573 8574 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check 8575 /// the well-formednes of the destructor declarator @p D with type @p 8576 /// R. If there are any errors in the declarator, this routine will 8577 /// emit diagnostics and set the declarator to invalid. Even if this happens, 8578 /// will be updated to reflect a well-formed type for the destructor and 8579 /// returned. 8580 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R, 8581 StorageClass& SC) { 8582 // C++ [class.dtor]p1: 8583 // [...] A typedef-name that names a class is a class-name 8584 // (7.1.3); however, a typedef-name that names a class shall not 8585 // be used as the identifier in the declarator for a destructor 8586 // declaration. 8587 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName); 8588 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>()) 8589 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 8590 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl()); 8591 else if (const TemplateSpecializationType *TST = 8592 DeclaratorType->getAs<TemplateSpecializationType>()) 8593 if (TST->isTypeAlias()) 8594 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name) 8595 << DeclaratorType << 1; 8596 8597 // C++ [class.dtor]p2: 8598 // A destructor is used to destroy objects of its class type. A 8599 // destructor takes no parameters, and no return type can be 8600 // specified for it (not even void). The address of a destructor 8601 // shall not be taken. A destructor shall not be static. A 8602 // destructor can be invoked for a const, volatile or const 8603 // volatile object. A destructor shall not be declared const, 8604 // volatile or const volatile (9.3.2). 8605 if (SC == SC_Static) { 8606 if (!D.isInvalidType()) 8607 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be) 8608 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 8609 << SourceRange(D.getIdentifierLoc()) 8610 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 8611 8612 SC = SC_None; 8613 } 8614 if (!D.isInvalidType()) { 8615 // Destructors don't have return types, but the parser will 8616 // happily parse something like: 8617 // 8618 // class X { 8619 // float ~X(); 8620 // }; 8621 // 8622 // The return type will be eliminated later. 8623 if (D.getDeclSpec().hasTypeSpecifier()) 8624 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type) 8625 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8626 << SourceRange(D.getIdentifierLoc()); 8627 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) { 8628 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals, 8629 SourceLocation(), 8630 D.getDeclSpec().getConstSpecLoc(), 8631 D.getDeclSpec().getVolatileSpecLoc(), 8632 D.getDeclSpec().getRestrictSpecLoc(), 8633 D.getDeclSpec().getAtomicSpecLoc()); 8634 D.setInvalidType(); 8635 } 8636 } 8637 8638 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor); 8639 8640 // C++0x [class.dtor]p2: 8641 // A destructor shall not be declared with a ref-qualifier. 8642 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 8643 if (FTI.hasRefQualifier()) { 8644 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor) 8645 << FTI.RefQualifierIsLValueRef 8646 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc()); 8647 D.setInvalidType(); 8648 } 8649 8650 // Make sure we don't have any parameters. 8651 if (FTIHasNonVoidParameters(FTI)) { 8652 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params); 8653 8654 // Delete the parameters. 8655 FTI.freeParams(); 8656 D.setInvalidType(); 8657 } 8658 8659 // Make sure the destructor isn't variadic. 8660 if (FTI.isVariadic) { 8661 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic); 8662 D.setInvalidType(); 8663 } 8664 8665 // Rebuild the function type "R" without any type qualifiers or 8666 // parameters (in case any of the errors above fired) and with 8667 // "void" as the return type, since destructors don't have return 8668 // types. 8669 if (!D.isInvalidType()) 8670 return R; 8671 8672 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 8673 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); 8674 EPI.Variadic = false; 8675 EPI.TypeQuals = Qualifiers(); 8676 EPI.RefQualifier = RQ_None; 8677 return Context.getFunctionType(Context.VoidTy, None, EPI); 8678 } 8679 8680 static void extendLeft(SourceRange &R, SourceRange Before) { 8681 if (Before.isInvalid()) 8682 return; 8683 R.setBegin(Before.getBegin()); 8684 if (R.getEnd().isInvalid()) 8685 R.setEnd(Before.getEnd()); 8686 } 8687 8688 static void extendRight(SourceRange &R, SourceRange After) { 8689 if (After.isInvalid()) 8690 return; 8691 if (R.getBegin().isInvalid()) 8692 R.setBegin(After.getBegin()); 8693 R.setEnd(After.getEnd()); 8694 } 8695 8696 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the 8697 /// well-formednes of the conversion function declarator @p D with 8698 /// type @p R. If there are any errors in the declarator, this routine 8699 /// will emit diagnostics and return true. Otherwise, it will return 8700 /// false. Either way, the type @p R will be updated to reflect a 8701 /// well-formed type for the conversion operator. 8702 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R, 8703 StorageClass& SC) { 8704 // C++ [class.conv.fct]p1: 8705 // Neither parameter types nor return type can be specified. The 8706 // type of a conversion function (8.3.5) is "function taking no 8707 // parameter returning conversion-type-id." 8708 if (SC == SC_Static) { 8709 if (!D.isInvalidType()) 8710 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member) 8711 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc()) 8712 << D.getName().getSourceRange(); 8713 D.setInvalidType(); 8714 SC = SC_None; 8715 } 8716 8717 TypeSourceInfo *ConvTSI = nullptr; 8718 QualType ConvType = 8719 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI); 8720 8721 const DeclSpec &DS = D.getDeclSpec(); 8722 if (DS.hasTypeSpecifier() && !D.isInvalidType()) { 8723 // Conversion functions don't have return types, but the parser will 8724 // happily parse something like: 8725 // 8726 // class X { 8727 // float operator bool(); 8728 // }; 8729 // 8730 // The return type will be changed later anyway. 8731 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type) 8732 << SourceRange(DS.getTypeSpecTypeLoc()) 8733 << SourceRange(D.getIdentifierLoc()); 8734 D.setInvalidType(); 8735 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) { 8736 // It's also plausible that the user writes type qualifiers in the wrong 8737 // place, such as: 8738 // struct S { const operator int(); }; 8739 // FIXME: we could provide a fixit to move the qualifiers onto the 8740 // conversion type. 8741 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl) 8742 << SourceRange(D.getIdentifierLoc()) << 0; 8743 D.setInvalidType(); 8744 } 8745 8746 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>(); 8747 8748 // Make sure we don't have any parameters. 8749 if (Proto->getNumParams() > 0) { 8750 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params); 8751 8752 // Delete the parameters. 8753 D.getFunctionTypeInfo().freeParams(); 8754 D.setInvalidType(); 8755 } else if (Proto->isVariadic()) { 8756 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic); 8757 D.setInvalidType(); 8758 } 8759 8760 // Diagnose "&operator bool()" and other such nonsense. This 8761 // is actually a gcc extension which we don't support. 8762 if (Proto->getReturnType() != ConvType) { 8763 bool NeedsTypedef = false; 8764 SourceRange Before, After; 8765 8766 // Walk the chunks and extract information on them for our diagnostic. 8767 bool PastFunctionChunk = false; 8768 for (auto &Chunk : D.type_objects()) { 8769 switch (Chunk.Kind) { 8770 case DeclaratorChunk::Function: 8771 if (!PastFunctionChunk) { 8772 if (Chunk.Fun.HasTrailingReturnType) { 8773 TypeSourceInfo *TRT = nullptr; 8774 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT); 8775 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange()); 8776 } 8777 PastFunctionChunk = true; 8778 break; 8779 } 8780 LLVM_FALLTHROUGH; 8781 case DeclaratorChunk::Array: 8782 NeedsTypedef = true; 8783 extendRight(After, Chunk.getSourceRange()); 8784 break; 8785 8786 case DeclaratorChunk::Pointer: 8787 case DeclaratorChunk::BlockPointer: 8788 case DeclaratorChunk::Reference: 8789 case DeclaratorChunk::MemberPointer: 8790 case DeclaratorChunk::Pipe: 8791 extendLeft(Before, Chunk.getSourceRange()); 8792 break; 8793 8794 case DeclaratorChunk::Paren: 8795 extendLeft(Before, Chunk.Loc); 8796 extendRight(After, Chunk.EndLoc); 8797 break; 8798 } 8799 } 8800 8801 SourceLocation Loc = Before.isValid() ? Before.getBegin() : 8802 After.isValid() ? After.getBegin() : 8803 D.getIdentifierLoc(); 8804 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl); 8805 DB << Before << After; 8806 8807 if (!NeedsTypedef) { 8808 DB << /*don't need a typedef*/0; 8809 8810 // If we can provide a correct fix-it hint, do so. 8811 if (After.isInvalid() && ConvTSI) { 8812 SourceLocation InsertLoc = 8813 getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc()); 8814 DB << FixItHint::CreateInsertion(InsertLoc, " ") 8815 << FixItHint::CreateInsertionFromRange( 8816 InsertLoc, CharSourceRange::getTokenRange(Before)) 8817 << FixItHint::CreateRemoval(Before); 8818 } 8819 } else if (!Proto->getReturnType()->isDependentType()) { 8820 DB << /*typedef*/1 << Proto->getReturnType(); 8821 } else if (getLangOpts().CPlusPlus11) { 8822 DB << /*alias template*/2 << Proto->getReturnType(); 8823 } else { 8824 DB << /*might not be fixable*/3; 8825 } 8826 8827 // Recover by incorporating the other type chunks into the result type. 8828 // Note, this does *not* change the name of the function. This is compatible 8829 // with the GCC extension: 8830 // struct S { &operator int(); } s; 8831 // int &r = s.operator int(); // ok in GCC 8832 // S::operator int&() {} // error in GCC, function name is 'operator int'. 8833 ConvType = Proto->getReturnType(); 8834 } 8835 8836 // C++ [class.conv.fct]p4: 8837 // The conversion-type-id shall not represent a function type nor 8838 // an array type. 8839 if (ConvType->isArrayType()) { 8840 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array); 8841 ConvType = Context.getPointerType(ConvType); 8842 D.setInvalidType(); 8843 } else if (ConvType->isFunctionType()) { 8844 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function); 8845 ConvType = Context.getPointerType(ConvType); 8846 D.setInvalidType(); 8847 } 8848 8849 // Rebuild the function type "R" without any parameters (in case any 8850 // of the errors above fired) and with the conversion type as the 8851 // return type. 8852 if (D.isInvalidType()) 8853 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo()); 8854 8855 // C++0x explicit conversion operators. 8856 if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus2a) 8857 Diag(DS.getExplicitSpecLoc(), 8858 getLangOpts().CPlusPlus11 8859 ? diag::warn_cxx98_compat_explicit_conversion_functions 8860 : diag::ext_explicit_conversion_functions) 8861 << SourceRange(DS.getExplicitSpecRange()); 8862 } 8863 8864 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete 8865 /// the declaration of the given C++ conversion function. This routine 8866 /// is responsible for recording the conversion function in the C++ 8867 /// class, if possible. 8868 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) { 8869 assert(Conversion && "Expected to receive a conversion function declaration"); 8870 8871 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext()); 8872 8873 // Make sure we aren't redeclaring the conversion function. 8874 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType()); 8875 8876 // C++ [class.conv.fct]p1: 8877 // [...] A conversion function is never used to convert a 8878 // (possibly cv-qualified) object to the (possibly cv-qualified) 8879 // same object type (or a reference to it), to a (possibly 8880 // cv-qualified) base class of that type (or a reference to it), 8881 // or to (possibly cv-qualified) void. 8882 // FIXME: Suppress this warning if the conversion function ends up being a 8883 // virtual function that overrides a virtual function in a base class. 8884 QualType ClassType 8885 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 8886 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>()) 8887 ConvType = ConvTypeRef->getPointeeType(); 8888 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared && 8889 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) 8890 /* Suppress diagnostics for instantiations. */; 8891 else if (ConvType->isRecordType()) { 8892 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType(); 8893 if (ConvType == ClassType) 8894 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used) 8895 << ClassType; 8896 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType)) 8897 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used) 8898 << ClassType << ConvType; 8899 } else if (ConvType->isVoidType()) { 8900 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used) 8901 << ClassType << ConvType; 8902 } 8903 8904 if (FunctionTemplateDecl *ConversionTemplate 8905 = Conversion->getDescribedFunctionTemplate()) 8906 return ConversionTemplate; 8907 8908 return Conversion; 8909 } 8910 8911 namespace { 8912 /// Utility class to accumulate and print a diagnostic listing the invalid 8913 /// specifier(s) on a declaration. 8914 struct BadSpecifierDiagnoser { 8915 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID) 8916 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {} 8917 ~BadSpecifierDiagnoser() { 8918 Diagnostic << Specifiers; 8919 } 8920 8921 template<typename T> void check(SourceLocation SpecLoc, T Spec) { 8922 return check(SpecLoc, DeclSpec::getSpecifierName(Spec)); 8923 } 8924 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) { 8925 return check(SpecLoc, 8926 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy())); 8927 } 8928 void check(SourceLocation SpecLoc, const char *Spec) { 8929 if (SpecLoc.isInvalid()) return; 8930 Diagnostic << SourceRange(SpecLoc, SpecLoc); 8931 if (!Specifiers.empty()) Specifiers += " "; 8932 Specifiers += Spec; 8933 } 8934 8935 Sema &S; 8936 Sema::SemaDiagnosticBuilder Diagnostic; 8937 std::string Specifiers; 8938 }; 8939 } 8940 8941 /// Check the validity of a declarator that we parsed for a deduction-guide. 8942 /// These aren't actually declarators in the grammar, so we need to check that 8943 /// the user didn't specify any pieces that are not part of the deduction-guide 8944 /// grammar. 8945 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R, 8946 StorageClass &SC) { 8947 TemplateName GuidedTemplate = D.getName().TemplateName.get().get(); 8948 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl(); 8949 assert(GuidedTemplateDecl && "missing template decl for deduction guide"); 8950 8951 // C++ [temp.deduct.guide]p3: 8952 // A deduction-gide shall be declared in the same scope as the 8953 // corresponding class template. 8954 if (!CurContext->getRedeclContext()->Equals( 8955 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) { 8956 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope) 8957 << GuidedTemplateDecl; 8958 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here); 8959 } 8960 8961 auto &DS = D.getMutableDeclSpec(); 8962 // We leave 'friend' and 'virtual' to be rejected in the normal way. 8963 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() || 8964 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() || 8965 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) { 8966 BadSpecifierDiagnoser Diagnoser( 8967 *this, D.getIdentifierLoc(), 8968 diag::err_deduction_guide_invalid_specifier); 8969 8970 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec()); 8971 DS.ClearStorageClassSpecs(); 8972 SC = SC_None; 8973 8974 // 'explicit' is permitted. 8975 Diagnoser.check(DS.getInlineSpecLoc(), "inline"); 8976 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn"); 8977 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr"); 8978 DS.ClearConstexprSpec(); 8979 8980 Diagnoser.check(DS.getConstSpecLoc(), "const"); 8981 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict"); 8982 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile"); 8983 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic"); 8984 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned"); 8985 DS.ClearTypeQualifiers(); 8986 8987 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex()); 8988 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign()); 8989 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth()); 8990 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType()); 8991 DS.ClearTypeSpecType(); 8992 } 8993 8994 if (D.isInvalidType()) 8995 return; 8996 8997 // Check the declarator is simple enough. 8998 bool FoundFunction = false; 8999 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) { 9000 if (Chunk.Kind == DeclaratorChunk::Paren) 9001 continue; 9002 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) { 9003 Diag(D.getDeclSpec().getBeginLoc(), 9004 diag::err_deduction_guide_with_complex_decl) 9005 << D.getSourceRange(); 9006 break; 9007 } 9008 if (!Chunk.Fun.hasTrailingReturnType()) { 9009 Diag(D.getName().getBeginLoc(), 9010 diag::err_deduction_guide_no_trailing_return_type); 9011 break; 9012 } 9013 9014 // Check that the return type is written as a specialization of 9015 // the template specified as the deduction-guide's name. 9016 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType(); 9017 TypeSourceInfo *TSI = nullptr; 9018 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI); 9019 assert(TSI && "deduction guide has valid type but invalid return type?"); 9020 bool AcceptableReturnType = false; 9021 bool MightInstantiateToSpecialization = false; 9022 if (auto RetTST = 9023 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) { 9024 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName(); 9025 bool TemplateMatches = 9026 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate); 9027 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches) 9028 AcceptableReturnType = true; 9029 else { 9030 // This could still instantiate to the right type, unless we know it 9031 // names the wrong class template. 9032 auto *TD = SpecifiedName.getAsTemplateDecl(); 9033 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) && 9034 !TemplateMatches); 9035 } 9036 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) { 9037 MightInstantiateToSpecialization = true; 9038 } 9039 9040 if (!AcceptableReturnType) { 9041 Diag(TSI->getTypeLoc().getBeginLoc(), 9042 diag::err_deduction_guide_bad_trailing_return_type) 9043 << GuidedTemplate << TSI->getType() 9044 << MightInstantiateToSpecialization 9045 << TSI->getTypeLoc().getSourceRange(); 9046 } 9047 9048 // Keep going to check that we don't have any inner declarator pieces (we 9049 // could still have a function returning a pointer to a function). 9050 FoundFunction = true; 9051 } 9052 9053 if (D.isFunctionDefinition()) 9054 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function); 9055 } 9056 9057 //===----------------------------------------------------------------------===// 9058 // Namespace Handling 9059 //===----------------------------------------------------------------------===// 9060 9061 /// Diagnose a mismatch in 'inline' qualifiers when a namespace is 9062 /// reopened. 9063 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc, 9064 SourceLocation Loc, 9065 IdentifierInfo *II, bool *IsInline, 9066 NamespaceDecl *PrevNS) { 9067 assert(*IsInline != PrevNS->isInline()); 9068 9069 // HACK: Work around a bug in libstdc++4.6's <atomic>, where 9070 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as 9071 // inline namespaces, with the intention of bringing names into namespace std. 9072 // 9073 // We support this just well enough to get that case working; this is not 9074 // sufficient to support reopening namespaces as inline in general. 9075 if (*IsInline && II && II->getName().startswith("__atomic") && 9076 S.getSourceManager().isInSystemHeader(Loc)) { 9077 // Mark all prior declarations of the namespace as inline. 9078 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS; 9079 NS = NS->getPreviousDecl()) 9080 NS->setInline(*IsInline); 9081 // Patch up the lookup table for the containing namespace. This isn't really 9082 // correct, but it's good enough for this particular case. 9083 for (auto *I : PrevNS->decls()) 9084 if (auto *ND = dyn_cast<NamedDecl>(I)) 9085 PrevNS->getParent()->makeDeclVisibleInContext(ND); 9086 return; 9087 } 9088 9089 if (PrevNS->isInline()) 9090 // The user probably just forgot the 'inline', so suggest that it 9091 // be added back. 9092 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline) 9093 << FixItHint::CreateInsertion(KeywordLoc, "inline "); 9094 else 9095 S.Diag(Loc, diag::err_inline_namespace_mismatch); 9096 9097 S.Diag(PrevNS->getLocation(), diag::note_previous_definition); 9098 *IsInline = PrevNS->isInline(); 9099 } 9100 9101 /// ActOnStartNamespaceDef - This is called at the start of a namespace 9102 /// definition. 9103 Decl *Sema::ActOnStartNamespaceDef( 9104 Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc, 9105 SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace, 9106 const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) { 9107 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc; 9108 // For anonymous namespace, take the location of the left brace. 9109 SourceLocation Loc = II ? IdentLoc : LBrace; 9110 bool IsInline = InlineLoc.isValid(); 9111 bool IsInvalid = false; 9112 bool IsStd = false; 9113 bool AddToKnown = false; 9114 Scope *DeclRegionScope = NamespcScope->getParent(); 9115 9116 NamespaceDecl *PrevNS = nullptr; 9117 if (II) { 9118 // C++ [namespace.def]p2: 9119 // The identifier in an original-namespace-definition shall not 9120 // have been previously defined in the declarative region in 9121 // which the original-namespace-definition appears. The 9122 // identifier in an original-namespace-definition is the name of 9123 // the namespace. Subsequently in that declarative region, it is 9124 // treated as an original-namespace-name. 9125 // 9126 // Since namespace names are unique in their scope, and we don't 9127 // look through using directives, just look for any ordinary names 9128 // as if by qualified name lookup. 9129 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName, 9130 ForExternalRedeclaration); 9131 LookupQualifiedName(R, CurContext->getRedeclContext()); 9132 NamedDecl *PrevDecl = 9133 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr; 9134 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl); 9135 9136 if (PrevNS) { 9137 // This is an extended namespace definition. 9138 if (IsInline != PrevNS->isInline()) 9139 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II, 9140 &IsInline, PrevNS); 9141 } else if (PrevDecl) { 9142 // This is an invalid name redefinition. 9143 Diag(Loc, diag::err_redefinition_different_kind) 9144 << II; 9145 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 9146 IsInvalid = true; 9147 // Continue on to push Namespc as current DeclContext and return it. 9148 } else if (II->isStr("std") && 9149 CurContext->getRedeclContext()->isTranslationUnit()) { 9150 // This is the first "real" definition of the namespace "std", so update 9151 // our cache of the "std" namespace to point at this definition. 9152 PrevNS = getStdNamespace(); 9153 IsStd = true; 9154 AddToKnown = !IsInline; 9155 } else { 9156 // We've seen this namespace for the first time. 9157 AddToKnown = !IsInline; 9158 } 9159 } else { 9160 // Anonymous namespaces. 9161 9162 // Determine whether the parent already has an anonymous namespace. 9163 DeclContext *Parent = CurContext->getRedeclContext(); 9164 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 9165 PrevNS = TU->getAnonymousNamespace(); 9166 } else { 9167 NamespaceDecl *ND = cast<NamespaceDecl>(Parent); 9168 PrevNS = ND->getAnonymousNamespace(); 9169 } 9170 9171 if (PrevNS && IsInline != PrevNS->isInline()) 9172 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II, 9173 &IsInline, PrevNS); 9174 } 9175 9176 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline, 9177 StartLoc, Loc, II, PrevNS); 9178 if (IsInvalid) 9179 Namespc->setInvalidDecl(); 9180 9181 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList); 9182 AddPragmaAttributes(DeclRegionScope, Namespc); 9183 9184 // FIXME: Should we be merging attributes? 9185 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>()) 9186 PushNamespaceVisibilityAttr(Attr, Loc); 9187 9188 if (IsStd) 9189 StdNamespace = Namespc; 9190 if (AddToKnown) 9191 KnownNamespaces[Namespc] = false; 9192 9193 if (II) { 9194 PushOnScopeChains(Namespc, DeclRegionScope); 9195 } else { 9196 // Link the anonymous namespace into its parent. 9197 DeclContext *Parent = CurContext->getRedeclContext(); 9198 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) { 9199 TU->setAnonymousNamespace(Namespc); 9200 } else { 9201 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc); 9202 } 9203 9204 CurContext->addDecl(Namespc); 9205 9206 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition 9207 // behaves as if it were replaced by 9208 // namespace unique { /* empty body */ } 9209 // using namespace unique; 9210 // namespace unique { namespace-body } 9211 // where all occurrences of 'unique' in a translation unit are 9212 // replaced by the same identifier and this identifier differs 9213 // from all other identifiers in the entire program. 9214 9215 // We just create the namespace with an empty name and then add an 9216 // implicit using declaration, just like the standard suggests. 9217 // 9218 // CodeGen enforces the "universally unique" aspect by giving all 9219 // declarations semantically contained within an anonymous 9220 // namespace internal linkage. 9221 9222 if (!PrevNS) { 9223 UD = UsingDirectiveDecl::Create(Context, Parent, 9224 /* 'using' */ LBrace, 9225 /* 'namespace' */ SourceLocation(), 9226 /* qualifier */ NestedNameSpecifierLoc(), 9227 /* identifier */ SourceLocation(), 9228 Namespc, 9229 /* Ancestor */ Parent); 9230 UD->setImplicit(); 9231 Parent->addDecl(UD); 9232 } 9233 } 9234 9235 ActOnDocumentableDecl(Namespc); 9236 9237 // Although we could have an invalid decl (i.e. the namespace name is a 9238 // redefinition), push it as current DeclContext and try to continue parsing. 9239 // FIXME: We should be able to push Namespc here, so that the each DeclContext 9240 // for the namespace has the declarations that showed up in that particular 9241 // namespace definition. 9242 PushDeclContext(NamespcScope, Namespc); 9243 return Namespc; 9244 } 9245 9246 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl 9247 /// is a namespace alias, returns the namespace it points to. 9248 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) { 9249 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D)) 9250 return AD->getNamespace(); 9251 return dyn_cast_or_null<NamespaceDecl>(D); 9252 } 9253 9254 /// ActOnFinishNamespaceDef - This callback is called after a namespace is 9255 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef. 9256 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) { 9257 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl); 9258 assert(Namespc && "Invalid parameter, expected NamespaceDecl"); 9259 Namespc->setRBraceLoc(RBrace); 9260 PopDeclContext(); 9261 if (Namespc->hasAttr<VisibilityAttr>()) 9262 PopPragmaVisibility(true, RBrace); 9263 // If this namespace contains an export-declaration, export it now. 9264 if (DeferredExportedNamespaces.erase(Namespc)) 9265 Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported); 9266 } 9267 9268 CXXRecordDecl *Sema::getStdBadAlloc() const { 9269 return cast_or_null<CXXRecordDecl>( 9270 StdBadAlloc.get(Context.getExternalSource())); 9271 } 9272 9273 EnumDecl *Sema::getStdAlignValT() const { 9274 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource())); 9275 } 9276 9277 NamespaceDecl *Sema::getStdNamespace() const { 9278 return cast_or_null<NamespaceDecl>( 9279 StdNamespace.get(Context.getExternalSource())); 9280 } 9281 9282 NamespaceDecl *Sema::lookupStdExperimentalNamespace() { 9283 if (!StdExperimentalNamespaceCache) { 9284 if (auto Std = getStdNamespace()) { 9285 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"), 9286 SourceLocation(), LookupNamespaceName); 9287 if (!LookupQualifiedName(Result, Std) || 9288 !(StdExperimentalNamespaceCache = 9289 Result.getAsSingle<NamespaceDecl>())) 9290 Result.suppressDiagnostics(); 9291 } 9292 } 9293 return StdExperimentalNamespaceCache; 9294 } 9295 9296 namespace { 9297 9298 enum UnsupportedSTLSelect { 9299 USS_InvalidMember, 9300 USS_MissingMember, 9301 USS_NonTrivial, 9302 USS_Other 9303 }; 9304 9305 struct InvalidSTLDiagnoser { 9306 Sema &S; 9307 SourceLocation Loc; 9308 QualType TyForDiags; 9309 9310 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "", 9311 const VarDecl *VD = nullptr) { 9312 { 9313 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported) 9314 << TyForDiags << ((int)Sel); 9315 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) { 9316 assert(!Name.empty()); 9317 D << Name; 9318 } 9319 } 9320 if (Sel == USS_InvalidMember) { 9321 S.Diag(VD->getLocation(), diag::note_var_declared_here) 9322 << VD << VD->getSourceRange(); 9323 } 9324 return QualType(); 9325 } 9326 }; 9327 } // namespace 9328 9329 QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind, 9330 SourceLocation Loc) { 9331 assert(getLangOpts().CPlusPlus && 9332 "Looking for comparison category type outside of C++."); 9333 9334 // Check if we've already successfully checked the comparison category type 9335 // before. If so, skip checking it again. 9336 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind); 9337 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) 9338 return Info->getType(); 9339 9340 // If lookup failed 9341 if (!Info) { 9342 std::string NameForDiags = "std::"; 9343 NameForDiags += ComparisonCategories::getCategoryString(Kind); 9344 Diag(Loc, diag::err_implied_comparison_category_type_not_found) 9345 << NameForDiags; 9346 return QualType(); 9347 } 9348 9349 assert(Info->Kind == Kind); 9350 assert(Info->Record); 9351 9352 // Update the Record decl in case we encountered a forward declaration on our 9353 // first pass. FIXME: This is a bit of a hack. 9354 if (Info->Record->hasDefinition()) 9355 Info->Record = Info->Record->getDefinition(); 9356 9357 // Use an elaborated type for diagnostics which has a name containing the 9358 // prepended 'std' namespace but not any inline namespace names. 9359 QualType TyForDiags = [&]() { 9360 auto *NNS = 9361 NestedNameSpecifier::Create(Context, nullptr, getStdNamespace()); 9362 return Context.getElaboratedType(ETK_None, NNS, Info->getType()); 9363 }(); 9364 9365 if (RequireCompleteType(Loc, TyForDiags, diag::err_incomplete_type)) 9366 return QualType(); 9367 9368 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags}; 9369 9370 if (!Info->Record->isTriviallyCopyable()) 9371 return UnsupportedSTLError(USS_NonTrivial); 9372 9373 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) { 9374 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl(); 9375 // Tolerate empty base classes. 9376 if (Base->isEmpty()) 9377 continue; 9378 // Reject STL implementations which have at least one non-empty base. 9379 return UnsupportedSTLError(); 9380 } 9381 9382 // Check that the STL has implemented the types using a single integer field. 9383 // This expectation allows better codegen for builtin operators. We require: 9384 // (1) The class has exactly one field. 9385 // (2) The field is an integral or enumeration type. 9386 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end(); 9387 if (std::distance(FIt, FEnd) != 1 || 9388 !FIt->getType()->isIntegralOrEnumerationType()) { 9389 return UnsupportedSTLError(); 9390 } 9391 9392 // Build each of the require values and store them in Info. 9393 for (ComparisonCategoryResult CCR : 9394 ComparisonCategories::getPossibleResultsForType(Kind)) { 9395 StringRef MemName = ComparisonCategories::getResultString(CCR); 9396 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR); 9397 9398 if (!ValInfo) 9399 return UnsupportedSTLError(USS_MissingMember, MemName); 9400 9401 VarDecl *VD = ValInfo->VD; 9402 assert(VD && "should not be null!"); 9403 9404 // Attempt to diagnose reasons why the STL definition of this type 9405 // might be foobar, including it failing to be a constant expression. 9406 // TODO Handle more ways the lookup or result can be invalid. 9407 if (!VD->isStaticDataMember() || !VD->isConstexpr() || !VD->hasInit() || 9408 !VD->checkInitIsICE()) 9409 return UnsupportedSTLError(USS_InvalidMember, MemName, VD); 9410 9411 // Attempt to evaluate the var decl as a constant expression and extract 9412 // the value of its first field as a ICE. If this fails, the STL 9413 // implementation is not supported. 9414 if (!ValInfo->hasValidIntValue()) 9415 return UnsupportedSTLError(); 9416 9417 MarkVariableReferenced(Loc, VD); 9418 } 9419 9420 // We've successfully built the required types and expressions. Update 9421 // the cache and return the newly cached value. 9422 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true; 9423 return Info->getType(); 9424 } 9425 9426 /// Retrieve the special "std" namespace, which may require us to 9427 /// implicitly define the namespace. 9428 NamespaceDecl *Sema::getOrCreateStdNamespace() { 9429 if (!StdNamespace) { 9430 // The "std" namespace has not yet been defined, so build one implicitly. 9431 StdNamespace = NamespaceDecl::Create(Context, 9432 Context.getTranslationUnitDecl(), 9433 /*Inline=*/false, 9434 SourceLocation(), SourceLocation(), 9435 &PP.getIdentifierTable().get("std"), 9436 /*PrevDecl=*/nullptr); 9437 getStdNamespace()->setImplicit(true); 9438 } 9439 9440 return getStdNamespace(); 9441 } 9442 9443 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) { 9444 assert(getLangOpts().CPlusPlus && 9445 "Looking for std::initializer_list outside of C++."); 9446 9447 // We're looking for implicit instantiations of 9448 // template <typename E> class std::initializer_list. 9449 9450 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it. 9451 return false; 9452 9453 ClassTemplateDecl *Template = nullptr; 9454 const TemplateArgument *Arguments = nullptr; 9455 9456 if (const RecordType *RT = Ty->getAs<RecordType>()) { 9457 9458 ClassTemplateSpecializationDecl *Specialization = 9459 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 9460 if (!Specialization) 9461 return false; 9462 9463 Template = Specialization->getSpecializedTemplate(); 9464 Arguments = Specialization->getTemplateArgs().data(); 9465 } else if (const TemplateSpecializationType *TST = 9466 Ty->getAs<TemplateSpecializationType>()) { 9467 Template = dyn_cast_or_null<ClassTemplateDecl>( 9468 TST->getTemplateName().getAsTemplateDecl()); 9469 Arguments = TST->getArgs(); 9470 } 9471 if (!Template) 9472 return false; 9473 9474 if (!StdInitializerList) { 9475 // Haven't recognized std::initializer_list yet, maybe this is it. 9476 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl(); 9477 if (TemplateClass->getIdentifier() != 9478 &PP.getIdentifierTable().get("initializer_list") || 9479 !getStdNamespace()->InEnclosingNamespaceSetOf( 9480 TemplateClass->getDeclContext())) 9481 return false; 9482 // This is a template called std::initializer_list, but is it the right 9483 // template? 9484 TemplateParameterList *Params = Template->getTemplateParameters(); 9485 if (Params->getMinRequiredArguments() != 1) 9486 return false; 9487 if (!isa<TemplateTypeParmDecl>(Params->getParam(0))) 9488 return false; 9489 9490 // It's the right template. 9491 StdInitializerList = Template; 9492 } 9493 9494 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl()) 9495 return false; 9496 9497 // This is an instance of std::initializer_list. Find the argument type. 9498 if (Element) 9499 *Element = Arguments[0].getAsType(); 9500 return true; 9501 } 9502 9503 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){ 9504 NamespaceDecl *Std = S.getStdNamespace(); 9505 if (!Std) { 9506 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 9507 return nullptr; 9508 } 9509 9510 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"), 9511 Loc, Sema::LookupOrdinaryName); 9512 if (!S.LookupQualifiedName(Result, Std)) { 9513 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found); 9514 return nullptr; 9515 } 9516 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>(); 9517 if (!Template) { 9518 Result.suppressDiagnostics(); 9519 // We found something weird. Complain about the first thing we found. 9520 NamedDecl *Found = *Result.begin(); 9521 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list); 9522 return nullptr; 9523 } 9524 9525 // We found some template called std::initializer_list. Now verify that it's 9526 // correct. 9527 TemplateParameterList *Params = Template->getTemplateParameters(); 9528 if (Params->getMinRequiredArguments() != 1 || 9529 !isa<TemplateTypeParmDecl>(Params->getParam(0))) { 9530 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list); 9531 return nullptr; 9532 } 9533 9534 return Template; 9535 } 9536 9537 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) { 9538 if (!StdInitializerList) { 9539 StdInitializerList = LookupStdInitializerList(*this, Loc); 9540 if (!StdInitializerList) 9541 return QualType(); 9542 } 9543 9544 TemplateArgumentListInfo Args(Loc, Loc); 9545 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element), 9546 Context.getTrivialTypeSourceInfo(Element, 9547 Loc))); 9548 return Context.getCanonicalType( 9549 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args)); 9550 } 9551 9552 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) { 9553 // C++ [dcl.init.list]p2: 9554 // A constructor is an initializer-list constructor if its first parameter 9555 // is of type std::initializer_list<E> or reference to possibly cv-qualified 9556 // std::initializer_list<E> for some type E, and either there are no other 9557 // parameters or else all other parameters have default arguments. 9558 if (Ctor->getNumParams() < 1 || 9559 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg())) 9560 return false; 9561 9562 QualType ArgType = Ctor->getParamDecl(0)->getType(); 9563 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>()) 9564 ArgType = RT->getPointeeType().getUnqualifiedType(); 9565 9566 return isStdInitializerList(ArgType, nullptr); 9567 } 9568 9569 /// Determine whether a using statement is in a context where it will be 9570 /// apply in all contexts. 9571 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) { 9572 switch (CurContext->getDeclKind()) { 9573 case Decl::TranslationUnit: 9574 return true; 9575 case Decl::LinkageSpec: 9576 return IsUsingDirectiveInToplevelContext(CurContext->getParent()); 9577 default: 9578 return false; 9579 } 9580 } 9581 9582 namespace { 9583 9584 // Callback to only accept typo corrections that are namespaces. 9585 class NamespaceValidatorCCC final : public CorrectionCandidateCallback { 9586 public: 9587 bool ValidateCandidate(const TypoCorrection &candidate) override { 9588 if (NamedDecl *ND = candidate.getCorrectionDecl()) 9589 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND); 9590 return false; 9591 } 9592 9593 std::unique_ptr<CorrectionCandidateCallback> clone() override { 9594 return std::make_unique<NamespaceValidatorCCC>(*this); 9595 } 9596 }; 9597 9598 } 9599 9600 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc, 9601 CXXScopeSpec &SS, 9602 SourceLocation IdentLoc, 9603 IdentifierInfo *Ident) { 9604 R.clear(); 9605 NamespaceValidatorCCC CCC{}; 9606 if (TypoCorrection Corrected = 9607 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC, 9608 Sema::CTK_ErrorRecovery)) { 9609 if (DeclContext *DC = S.computeDeclContext(SS, false)) { 9610 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts())); 9611 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 9612 Ident->getName().equals(CorrectedStr); 9613 S.diagnoseTypo(Corrected, 9614 S.PDiag(diag::err_using_directive_member_suggest) 9615 << Ident << DC << DroppedSpecifier << SS.getRange(), 9616 S.PDiag(diag::note_namespace_defined_here)); 9617 } else { 9618 S.diagnoseTypo(Corrected, 9619 S.PDiag(diag::err_using_directive_suggest) << Ident, 9620 S.PDiag(diag::note_namespace_defined_here)); 9621 } 9622 R.addDecl(Corrected.getFoundDecl()); 9623 return true; 9624 } 9625 return false; 9626 } 9627 9628 Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc, 9629 SourceLocation NamespcLoc, CXXScopeSpec &SS, 9630 SourceLocation IdentLoc, 9631 IdentifierInfo *NamespcName, 9632 const ParsedAttributesView &AttrList) { 9633 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 9634 assert(NamespcName && "Invalid NamespcName."); 9635 assert(IdentLoc.isValid() && "Invalid NamespceName location."); 9636 9637 // This can only happen along a recovery path. 9638 while (S->isTemplateParamScope()) 9639 S = S->getParent(); 9640 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 9641 9642 UsingDirectiveDecl *UDir = nullptr; 9643 NestedNameSpecifier *Qualifier = nullptr; 9644 if (SS.isSet()) 9645 Qualifier = SS.getScopeRep(); 9646 9647 // Lookup namespace name. 9648 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName); 9649 LookupParsedName(R, S, &SS); 9650 if (R.isAmbiguous()) 9651 return nullptr; 9652 9653 if (R.empty()) { 9654 R.clear(); 9655 // Allow "using namespace std;" or "using namespace ::std;" even if 9656 // "std" hasn't been defined yet, for GCC compatibility. 9657 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) && 9658 NamespcName->isStr("std")) { 9659 Diag(IdentLoc, diag::ext_using_undefined_std); 9660 R.addDecl(getOrCreateStdNamespace()); 9661 R.resolveKind(); 9662 } 9663 // Otherwise, attempt typo correction. 9664 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName); 9665 } 9666 9667 if (!R.empty()) { 9668 NamedDecl *Named = R.getRepresentativeDecl(); 9669 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>(); 9670 assert(NS && "expected namespace decl"); 9671 9672 // The use of a nested name specifier may trigger deprecation warnings. 9673 DiagnoseUseOfDecl(Named, IdentLoc); 9674 9675 // C++ [namespace.udir]p1: 9676 // A using-directive specifies that the names in the nominated 9677 // namespace can be used in the scope in which the 9678 // using-directive appears after the using-directive. During 9679 // unqualified name lookup (3.4.1), the names appear as if they 9680 // were declared in the nearest enclosing namespace which 9681 // contains both the using-directive and the nominated 9682 // namespace. [Note: in this context, "contains" means "contains 9683 // directly or indirectly". ] 9684 9685 // Find enclosing context containing both using-directive and 9686 // nominated namespace. 9687 DeclContext *CommonAncestor = NS; 9688 while (CommonAncestor && !CommonAncestor->Encloses(CurContext)) 9689 CommonAncestor = CommonAncestor->getParent(); 9690 9691 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc, 9692 SS.getWithLocInContext(Context), 9693 IdentLoc, Named, CommonAncestor); 9694 9695 if (IsUsingDirectiveInToplevelContext(CurContext) && 9696 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) { 9697 Diag(IdentLoc, diag::warn_using_directive_in_header); 9698 } 9699 9700 PushUsingDirective(S, UDir); 9701 } else { 9702 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 9703 } 9704 9705 if (UDir) 9706 ProcessDeclAttributeList(S, UDir, AttrList); 9707 9708 return UDir; 9709 } 9710 9711 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) { 9712 // If the scope has an associated entity and the using directive is at 9713 // namespace or translation unit scope, add the UsingDirectiveDecl into 9714 // its lookup structure so qualified name lookup can find it. 9715 DeclContext *Ctx = S->getEntity(); 9716 if (Ctx && !Ctx->isFunctionOrMethod()) 9717 Ctx->addDecl(UDir); 9718 else 9719 // Otherwise, it is at block scope. The using-directives will affect lookup 9720 // only to the end of the scope. 9721 S->PushUsingDirective(UDir); 9722 } 9723 9724 Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS, 9725 SourceLocation UsingLoc, 9726 SourceLocation TypenameLoc, CXXScopeSpec &SS, 9727 UnqualifiedId &Name, 9728 SourceLocation EllipsisLoc, 9729 const ParsedAttributesView &AttrList) { 9730 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope."); 9731 9732 if (SS.isEmpty()) { 9733 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname); 9734 return nullptr; 9735 } 9736 9737 switch (Name.getKind()) { 9738 case UnqualifiedIdKind::IK_ImplicitSelfParam: 9739 case UnqualifiedIdKind::IK_Identifier: 9740 case UnqualifiedIdKind::IK_OperatorFunctionId: 9741 case UnqualifiedIdKind::IK_LiteralOperatorId: 9742 case UnqualifiedIdKind::IK_ConversionFunctionId: 9743 break; 9744 9745 case UnqualifiedIdKind::IK_ConstructorName: 9746 case UnqualifiedIdKind::IK_ConstructorTemplateId: 9747 // C++11 inheriting constructors. 9748 Diag(Name.getBeginLoc(), 9749 getLangOpts().CPlusPlus11 9750 ? diag::warn_cxx98_compat_using_decl_constructor 9751 : diag::err_using_decl_constructor) 9752 << SS.getRange(); 9753 9754 if (getLangOpts().CPlusPlus11) break; 9755 9756 return nullptr; 9757 9758 case UnqualifiedIdKind::IK_DestructorName: 9759 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange(); 9760 return nullptr; 9761 9762 case UnqualifiedIdKind::IK_TemplateId: 9763 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id) 9764 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); 9765 return nullptr; 9766 9767 case UnqualifiedIdKind::IK_DeductionGuideName: 9768 llvm_unreachable("cannot parse qualified deduction guide name"); 9769 } 9770 9771 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 9772 DeclarationName TargetName = TargetNameInfo.getName(); 9773 if (!TargetName) 9774 return nullptr; 9775 9776 // Warn about access declarations. 9777 if (UsingLoc.isInvalid()) { 9778 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11 9779 ? diag::err_access_decl 9780 : diag::warn_access_decl_deprecated) 9781 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using "); 9782 } 9783 9784 if (EllipsisLoc.isInvalid()) { 9785 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) || 9786 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration)) 9787 return nullptr; 9788 } else { 9789 if (!SS.getScopeRep()->containsUnexpandedParameterPack() && 9790 !TargetNameInfo.containsUnexpandedParameterPack()) { 9791 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 9792 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc()); 9793 EllipsisLoc = SourceLocation(); 9794 } 9795 } 9796 9797 NamedDecl *UD = 9798 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc, 9799 SS, TargetNameInfo, EllipsisLoc, AttrList, 9800 /*IsInstantiation*/false); 9801 if (UD) 9802 PushOnScopeChains(UD, S, /*AddToContext*/ false); 9803 9804 return UD; 9805 } 9806 9807 /// Determine whether a using declaration considers the given 9808 /// declarations as "equivalent", e.g., if they are redeclarations of 9809 /// the same entity or are both typedefs of the same type. 9810 static bool 9811 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) { 9812 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) 9813 return true; 9814 9815 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1)) 9816 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) 9817 return Context.hasSameType(TD1->getUnderlyingType(), 9818 TD2->getUnderlyingType()); 9819 9820 return false; 9821 } 9822 9823 9824 /// Determines whether to create a using shadow decl for a particular 9825 /// decl, given the set of decls existing prior to this using lookup. 9826 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig, 9827 const LookupResult &Previous, 9828 UsingShadowDecl *&PrevShadow) { 9829 // Diagnose finding a decl which is not from a base class of the 9830 // current class. We do this now because there are cases where this 9831 // function will silently decide not to build a shadow decl, which 9832 // will pre-empt further diagnostics. 9833 // 9834 // We don't need to do this in C++11 because we do the check once on 9835 // the qualifier. 9836 // 9837 // FIXME: diagnose the following if we care enough: 9838 // struct A { int foo; }; 9839 // struct B : A { using A::foo; }; 9840 // template <class T> struct C : A {}; 9841 // template <class T> struct D : C<T> { using B::foo; } // <--- 9842 // This is invalid (during instantiation) in C++03 because B::foo 9843 // resolves to the using decl in B, which is not a base class of D<T>. 9844 // We can't diagnose it immediately because C<T> is an unknown 9845 // specialization. The UsingShadowDecl in D<T> then points directly 9846 // to A::foo, which will look well-formed when we instantiate. 9847 // The right solution is to not collapse the shadow-decl chain. 9848 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) { 9849 DeclContext *OrigDC = Orig->getDeclContext(); 9850 9851 // Handle enums and anonymous structs. 9852 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent(); 9853 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC); 9854 while (OrigRec->isAnonymousStructOrUnion()) 9855 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext()); 9856 9857 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) { 9858 if (OrigDC == CurContext) { 9859 Diag(Using->getLocation(), 9860 diag::err_using_decl_nested_name_specifier_is_current_class) 9861 << Using->getQualifierLoc().getSourceRange(); 9862 Diag(Orig->getLocation(), diag::note_using_decl_target); 9863 Using->setInvalidDecl(); 9864 return true; 9865 } 9866 9867 Diag(Using->getQualifierLoc().getBeginLoc(), 9868 diag::err_using_decl_nested_name_specifier_is_not_base_class) 9869 << Using->getQualifier() 9870 << cast<CXXRecordDecl>(CurContext) 9871 << Using->getQualifierLoc().getSourceRange(); 9872 Diag(Orig->getLocation(), diag::note_using_decl_target); 9873 Using->setInvalidDecl(); 9874 return true; 9875 } 9876 } 9877 9878 if (Previous.empty()) return false; 9879 9880 NamedDecl *Target = Orig; 9881 if (isa<UsingShadowDecl>(Target)) 9882 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 9883 9884 // If the target happens to be one of the previous declarations, we 9885 // don't have a conflict. 9886 // 9887 // FIXME: but we might be increasing its access, in which case we 9888 // should redeclare it. 9889 NamedDecl *NonTag = nullptr, *Tag = nullptr; 9890 bool FoundEquivalentDecl = false; 9891 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 9892 I != E; ++I) { 9893 NamedDecl *D = (*I)->getUnderlyingDecl(); 9894 // We can have UsingDecls in our Previous results because we use the same 9895 // LookupResult for checking whether the UsingDecl itself is a valid 9896 // redeclaration. 9897 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D)) 9898 continue; 9899 9900 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) { 9901 // C++ [class.mem]p19: 9902 // If T is the name of a class, then [every named member other than 9903 // a non-static data member] shall have a name different from T 9904 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) && 9905 !isa<IndirectFieldDecl>(Target) && 9906 !isa<UnresolvedUsingValueDecl>(Target) && 9907 DiagnoseClassNameShadow( 9908 CurContext, 9909 DeclarationNameInfo(Using->getDeclName(), Using->getLocation()))) 9910 return true; 9911 } 9912 9913 if (IsEquivalentForUsingDecl(Context, D, Target)) { 9914 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I)) 9915 PrevShadow = Shadow; 9916 FoundEquivalentDecl = true; 9917 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) { 9918 // We don't conflict with an existing using shadow decl of an equivalent 9919 // declaration, but we're not a redeclaration of it. 9920 FoundEquivalentDecl = true; 9921 } 9922 9923 if (isVisible(D)) 9924 (isa<TagDecl>(D) ? Tag : NonTag) = D; 9925 } 9926 9927 if (FoundEquivalentDecl) 9928 return false; 9929 9930 if (FunctionDecl *FD = Target->getAsFunction()) { 9931 NamedDecl *OldDecl = nullptr; 9932 switch (CheckOverload(nullptr, FD, Previous, OldDecl, 9933 /*IsForUsingDecl*/ true)) { 9934 case Ovl_Overload: 9935 return false; 9936 9937 case Ovl_NonFunction: 9938 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9939 break; 9940 9941 // We found a decl with the exact signature. 9942 case Ovl_Match: 9943 // If we're in a record, we want to hide the target, so we 9944 // return true (without a diagnostic) to tell the caller not to 9945 // build a shadow decl. 9946 if (CurContext->isRecord()) 9947 return true; 9948 9949 // If we're not in a record, this is an error. 9950 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9951 break; 9952 } 9953 9954 Diag(Target->getLocation(), diag::note_using_decl_target); 9955 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict); 9956 Using->setInvalidDecl(); 9957 return true; 9958 } 9959 9960 // Target is not a function. 9961 9962 if (isa<TagDecl>(Target)) { 9963 // No conflict between a tag and a non-tag. 9964 if (!Tag) return false; 9965 9966 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9967 Diag(Target->getLocation(), diag::note_using_decl_target); 9968 Diag(Tag->getLocation(), diag::note_using_decl_conflict); 9969 Using->setInvalidDecl(); 9970 return true; 9971 } 9972 9973 // No conflict between a tag and a non-tag. 9974 if (!NonTag) return false; 9975 9976 Diag(Using->getLocation(), diag::err_using_decl_conflict); 9977 Diag(Target->getLocation(), diag::note_using_decl_target); 9978 Diag(NonTag->getLocation(), diag::note_using_decl_conflict); 9979 Using->setInvalidDecl(); 9980 return true; 9981 } 9982 9983 /// Determine whether a direct base class is a virtual base class. 9984 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) { 9985 if (!Derived->getNumVBases()) 9986 return false; 9987 for (auto &B : Derived->bases()) 9988 if (B.getType()->getAsCXXRecordDecl() == Base) 9989 return B.isVirtual(); 9990 llvm_unreachable("not a direct base class"); 9991 } 9992 9993 /// Builds a shadow declaration corresponding to a 'using' declaration. 9994 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, 9995 UsingDecl *UD, 9996 NamedDecl *Orig, 9997 UsingShadowDecl *PrevDecl) { 9998 // If we resolved to another shadow declaration, just coalesce them. 9999 NamedDecl *Target = Orig; 10000 if (isa<UsingShadowDecl>(Target)) { 10001 Target = cast<UsingShadowDecl>(Target)->getTargetDecl(); 10002 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration"); 10003 } 10004 10005 NamedDecl *NonTemplateTarget = Target; 10006 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target)) 10007 NonTemplateTarget = TargetTD->getTemplatedDecl(); 10008 10009 UsingShadowDecl *Shadow; 10010 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) { 10011 bool IsVirtualBase = 10012 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext), 10013 UD->getQualifier()->getAsRecordDecl()); 10014 Shadow = ConstructorUsingShadowDecl::Create( 10015 Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase); 10016 } else { 10017 Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD, 10018 Target); 10019 } 10020 UD->addShadowDecl(Shadow); 10021 10022 Shadow->setAccess(UD->getAccess()); 10023 if (Orig->isInvalidDecl() || UD->isInvalidDecl()) 10024 Shadow->setInvalidDecl(); 10025 10026 Shadow->setPreviousDecl(PrevDecl); 10027 10028 if (S) 10029 PushOnScopeChains(Shadow, S); 10030 else 10031 CurContext->addDecl(Shadow); 10032 10033 10034 return Shadow; 10035 } 10036 10037 /// Hides a using shadow declaration. This is required by the current 10038 /// using-decl implementation when a resolvable using declaration in a 10039 /// class is followed by a declaration which would hide or override 10040 /// one or more of the using decl's targets; for example: 10041 /// 10042 /// struct Base { void foo(int); }; 10043 /// struct Derived : Base { 10044 /// using Base::foo; 10045 /// void foo(int); 10046 /// }; 10047 /// 10048 /// The governing language is C++03 [namespace.udecl]p12: 10049 /// 10050 /// When a using-declaration brings names from a base class into a 10051 /// derived class scope, member functions in the derived class 10052 /// override and/or hide member functions with the same name and 10053 /// parameter types in a base class (rather than conflicting). 10054 /// 10055 /// There are two ways to implement this: 10056 /// (1) optimistically create shadow decls when they're not hidden 10057 /// by existing declarations, or 10058 /// (2) don't create any shadow decls (or at least don't make them 10059 /// visible) until we've fully parsed/instantiated the class. 10060 /// The problem with (1) is that we might have to retroactively remove 10061 /// a shadow decl, which requires several O(n) operations because the 10062 /// decl structures are (very reasonably) not designed for removal. 10063 /// (2) avoids this but is very fiddly and phase-dependent. 10064 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) { 10065 if (Shadow->getDeclName().getNameKind() == 10066 DeclarationName::CXXConversionFunctionName) 10067 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow); 10068 10069 // Remove it from the DeclContext... 10070 Shadow->getDeclContext()->removeDecl(Shadow); 10071 10072 // ...and the scope, if applicable... 10073 if (S) { 10074 S->RemoveDecl(Shadow); 10075 IdResolver.RemoveDecl(Shadow); 10076 } 10077 10078 // ...and the using decl. 10079 Shadow->getUsingDecl()->removeShadowDecl(Shadow); 10080 10081 // TODO: complain somehow if Shadow was used. It shouldn't 10082 // be possible for this to happen, because...? 10083 } 10084 10085 /// Find the base specifier for a base class with the given type. 10086 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived, 10087 QualType DesiredBase, 10088 bool &AnyDependentBases) { 10089 // Check whether the named type is a direct base class. 10090 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified() 10091 .getUnqualifiedType(); 10092 for (auto &Base : Derived->bases()) { 10093 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified(); 10094 if (CanonicalDesiredBase == BaseType) 10095 return &Base; 10096 if (BaseType->isDependentType()) 10097 AnyDependentBases = true; 10098 } 10099 return nullptr; 10100 } 10101 10102 namespace { 10103 class UsingValidatorCCC final : public CorrectionCandidateCallback { 10104 public: 10105 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation, 10106 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf) 10107 : HasTypenameKeyword(HasTypenameKeyword), 10108 IsInstantiation(IsInstantiation), OldNNS(NNS), 10109 RequireMemberOf(RequireMemberOf) {} 10110 10111 bool ValidateCandidate(const TypoCorrection &Candidate) override { 10112 NamedDecl *ND = Candidate.getCorrectionDecl(); 10113 10114 // Keywords are not valid here. 10115 if (!ND || isa<NamespaceDecl>(ND)) 10116 return false; 10117 10118 // Completely unqualified names are invalid for a 'using' declaration. 10119 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier()) 10120 return false; 10121 10122 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would 10123 // reject. 10124 10125 if (RequireMemberOf) { 10126 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 10127 if (FoundRecord && FoundRecord->isInjectedClassName()) { 10128 // No-one ever wants a using-declaration to name an injected-class-name 10129 // of a base class, unless they're declaring an inheriting constructor. 10130 ASTContext &Ctx = ND->getASTContext(); 10131 if (!Ctx.getLangOpts().CPlusPlus11) 10132 return false; 10133 QualType FoundType = Ctx.getRecordType(FoundRecord); 10134 10135 // Check that the injected-class-name is named as a member of its own 10136 // type; we don't want to suggest 'using Derived::Base;', since that 10137 // means something else. 10138 NestedNameSpecifier *Specifier = 10139 Candidate.WillReplaceSpecifier() 10140 ? Candidate.getCorrectionSpecifier() 10141 : OldNNS; 10142 if (!Specifier->getAsType() || 10143 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType)) 10144 return false; 10145 10146 // Check that this inheriting constructor declaration actually names a 10147 // direct base class of the current class. 10148 bool AnyDependentBases = false; 10149 if (!findDirectBaseWithType(RequireMemberOf, 10150 Ctx.getRecordType(FoundRecord), 10151 AnyDependentBases) && 10152 !AnyDependentBases) 10153 return false; 10154 } else { 10155 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext()); 10156 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD)) 10157 return false; 10158 10159 // FIXME: Check that the base class member is accessible? 10160 } 10161 } else { 10162 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND); 10163 if (FoundRecord && FoundRecord->isInjectedClassName()) 10164 return false; 10165 } 10166 10167 if (isa<TypeDecl>(ND)) 10168 return HasTypenameKeyword || !IsInstantiation; 10169 10170 return !HasTypenameKeyword; 10171 } 10172 10173 std::unique_ptr<CorrectionCandidateCallback> clone() override { 10174 return std::make_unique<UsingValidatorCCC>(*this); 10175 } 10176 10177 private: 10178 bool HasTypenameKeyword; 10179 bool IsInstantiation; 10180 NestedNameSpecifier *OldNNS; 10181 CXXRecordDecl *RequireMemberOf; 10182 }; 10183 } // end anonymous namespace 10184 10185 /// Builds a using declaration. 10186 /// 10187 /// \param IsInstantiation - Whether this call arises from an 10188 /// instantiation of an unresolved using declaration. We treat 10189 /// the lookup differently for these declarations. 10190 NamedDecl *Sema::BuildUsingDeclaration( 10191 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, 10192 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, 10193 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, 10194 const ParsedAttributesView &AttrList, bool IsInstantiation) { 10195 assert(!SS.isInvalid() && "Invalid CXXScopeSpec."); 10196 SourceLocation IdentLoc = NameInfo.getLoc(); 10197 assert(IdentLoc.isValid() && "Invalid TargetName location."); 10198 10199 // FIXME: We ignore attributes for now. 10200 10201 // For an inheriting constructor declaration, the name of the using 10202 // declaration is the name of a constructor in this class, not in the 10203 // base class. 10204 DeclarationNameInfo UsingName = NameInfo; 10205 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName) 10206 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext)) 10207 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 10208 Context.getCanonicalType(Context.getRecordType(RD)))); 10209 10210 // Do the redeclaration lookup in the current scope. 10211 LookupResult Previous(*this, UsingName, LookupUsingDeclName, 10212 ForVisibleRedeclaration); 10213 Previous.setHideTags(false); 10214 if (S) { 10215 LookupName(Previous, S); 10216 10217 // It is really dumb that we have to do this. 10218 LookupResult::Filter F = Previous.makeFilter(); 10219 while (F.hasNext()) { 10220 NamedDecl *D = F.next(); 10221 if (!isDeclInScope(D, CurContext, S)) 10222 F.erase(); 10223 // If we found a local extern declaration that's not ordinarily visible, 10224 // and this declaration is being added to a non-block scope, ignore it. 10225 // We're only checking for scope conflicts here, not also for violations 10226 // of the linkage rules. 10227 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() && 10228 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary)) 10229 F.erase(); 10230 } 10231 F.done(); 10232 } else { 10233 assert(IsInstantiation && "no scope in non-instantiation"); 10234 if (CurContext->isRecord()) 10235 LookupQualifiedName(Previous, CurContext); 10236 else { 10237 // No redeclaration check is needed here; in non-member contexts we 10238 // diagnosed all possible conflicts with other using-declarations when 10239 // building the template: 10240 // 10241 // For a dependent non-type using declaration, the only valid case is 10242 // if we instantiate to a single enumerator. We check for conflicts 10243 // between shadow declarations we introduce, and we check in the template 10244 // definition for conflicts between a non-type using declaration and any 10245 // other declaration, which together covers all cases. 10246 // 10247 // A dependent typename using declaration will never successfully 10248 // instantiate, since it will always name a class member, so we reject 10249 // that in the template definition. 10250 } 10251 } 10252 10253 // Check for invalid redeclarations. 10254 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword, 10255 SS, IdentLoc, Previous)) 10256 return nullptr; 10257 10258 // Check for bad qualifiers. 10259 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo, 10260 IdentLoc)) 10261 return nullptr; 10262 10263 DeclContext *LookupContext = computeDeclContext(SS); 10264 NamedDecl *D; 10265 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 10266 if (!LookupContext || EllipsisLoc.isValid()) { 10267 if (HasTypenameKeyword) { 10268 // FIXME: not all declaration name kinds are legal here 10269 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext, 10270 UsingLoc, TypenameLoc, 10271 QualifierLoc, 10272 IdentLoc, NameInfo.getName(), 10273 EllipsisLoc); 10274 } else { 10275 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc, 10276 QualifierLoc, NameInfo, EllipsisLoc); 10277 } 10278 D->setAccess(AS); 10279 CurContext->addDecl(D); 10280 return D; 10281 } 10282 10283 auto Build = [&](bool Invalid) { 10284 UsingDecl *UD = 10285 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc, 10286 UsingName, HasTypenameKeyword); 10287 UD->setAccess(AS); 10288 CurContext->addDecl(UD); 10289 UD->setInvalidDecl(Invalid); 10290 return UD; 10291 }; 10292 auto BuildInvalid = [&]{ return Build(true); }; 10293 auto BuildValid = [&]{ return Build(false); }; 10294 10295 if (RequireCompleteDeclContext(SS, LookupContext)) 10296 return BuildInvalid(); 10297 10298 // Look up the target name. 10299 LookupResult R(*this, NameInfo, LookupOrdinaryName); 10300 10301 // Unlike most lookups, we don't always want to hide tag 10302 // declarations: tag names are visible through the using declaration 10303 // even if hidden by ordinary names, *except* in a dependent context 10304 // where it's important for the sanity of two-phase lookup. 10305 if (!IsInstantiation) 10306 R.setHideTags(false); 10307 10308 // For the purposes of this lookup, we have a base object type 10309 // equal to that of the current context. 10310 if (CurContext->isRecord()) { 10311 R.setBaseObjectType( 10312 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext))); 10313 } 10314 10315 LookupQualifiedName(R, LookupContext); 10316 10317 // Try to correct typos if possible. If constructor name lookup finds no 10318 // results, that means the named class has no explicit constructors, and we 10319 // suppressed declaring implicit ones (probably because it's dependent or 10320 // invalid). 10321 if (R.empty() && 10322 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) { 10323 // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes 10324 // it will believe that glibc provides a ::gets in cases where it does not, 10325 // and will try to pull it into namespace std with a using-declaration. 10326 // Just ignore the using-declaration in that case. 10327 auto *II = NameInfo.getName().getAsIdentifierInfo(); 10328 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") && 10329 CurContext->isStdNamespace() && 10330 isa<TranslationUnitDecl>(LookupContext) && 10331 getSourceManager().isInSystemHeader(UsingLoc)) 10332 return nullptr; 10333 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(), 10334 dyn_cast<CXXRecordDecl>(CurContext)); 10335 if (TypoCorrection Corrected = 10336 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC, 10337 CTK_ErrorRecovery)) { 10338 // We reject candidates where DroppedSpecifier == true, hence the 10339 // literal '0' below. 10340 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest) 10341 << NameInfo.getName() << LookupContext << 0 10342 << SS.getRange()); 10343 10344 // If we picked a correction with no attached Decl we can't do anything 10345 // useful with it, bail out. 10346 NamedDecl *ND = Corrected.getCorrectionDecl(); 10347 if (!ND) 10348 return BuildInvalid(); 10349 10350 // If we corrected to an inheriting constructor, handle it as one. 10351 auto *RD = dyn_cast<CXXRecordDecl>(ND); 10352 if (RD && RD->isInjectedClassName()) { 10353 // The parent of the injected class name is the class itself. 10354 RD = cast<CXXRecordDecl>(RD->getParent()); 10355 10356 // Fix up the information we'll use to build the using declaration. 10357 if (Corrected.WillReplaceSpecifier()) { 10358 NestedNameSpecifierLocBuilder Builder; 10359 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 10360 QualifierLoc.getSourceRange()); 10361 QualifierLoc = Builder.getWithLocInContext(Context); 10362 } 10363 10364 // In this case, the name we introduce is the name of a derived class 10365 // constructor. 10366 auto *CurClass = cast<CXXRecordDecl>(CurContext); 10367 UsingName.setName(Context.DeclarationNames.getCXXConstructorName( 10368 Context.getCanonicalType(Context.getRecordType(CurClass)))); 10369 UsingName.setNamedTypeInfo(nullptr); 10370 for (auto *Ctor : LookupConstructors(RD)) 10371 R.addDecl(Ctor); 10372 R.resolveKind(); 10373 } else { 10374 // FIXME: Pick up all the declarations if we found an overloaded 10375 // function. 10376 UsingName.setName(ND->getDeclName()); 10377 R.addDecl(ND); 10378 } 10379 } else { 10380 Diag(IdentLoc, diag::err_no_member) 10381 << NameInfo.getName() << LookupContext << SS.getRange(); 10382 return BuildInvalid(); 10383 } 10384 } 10385 10386 if (R.isAmbiguous()) 10387 return BuildInvalid(); 10388 10389 if (HasTypenameKeyword) { 10390 // If we asked for a typename and got a non-type decl, error out. 10391 if (!R.getAsSingle<TypeDecl>()) { 10392 Diag(IdentLoc, diag::err_using_typename_non_type); 10393 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 10394 Diag((*I)->getUnderlyingDecl()->getLocation(), 10395 diag::note_using_decl_target); 10396 return BuildInvalid(); 10397 } 10398 } else { 10399 // If we asked for a non-typename and we got a type, error out, 10400 // but only if this is an instantiation of an unresolved using 10401 // decl. Otherwise just silently find the type name. 10402 if (IsInstantiation && R.getAsSingle<TypeDecl>()) { 10403 Diag(IdentLoc, diag::err_using_dependent_value_is_type); 10404 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target); 10405 return BuildInvalid(); 10406 } 10407 } 10408 10409 // C++14 [namespace.udecl]p6: 10410 // A using-declaration shall not name a namespace. 10411 if (R.getAsSingle<NamespaceDecl>()) { 10412 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace) 10413 << SS.getRange(); 10414 return BuildInvalid(); 10415 } 10416 10417 // C++14 [namespace.udecl]p7: 10418 // A using-declaration shall not name a scoped enumerator. 10419 if (auto *ED = R.getAsSingle<EnumConstantDecl>()) { 10420 if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) { 10421 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum) 10422 << SS.getRange(); 10423 return BuildInvalid(); 10424 } 10425 } 10426 10427 UsingDecl *UD = BuildValid(); 10428 10429 // Some additional rules apply to inheriting constructors. 10430 if (UsingName.getName().getNameKind() == 10431 DeclarationName::CXXConstructorName) { 10432 // Suppress access diagnostics; the access check is instead performed at the 10433 // point of use for an inheriting constructor. 10434 R.suppressDiagnostics(); 10435 if (CheckInheritingConstructorUsingDecl(UD)) 10436 return UD; 10437 } 10438 10439 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 10440 UsingShadowDecl *PrevDecl = nullptr; 10441 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl)) 10442 BuildUsingShadowDecl(S, UD, *I, PrevDecl); 10443 } 10444 10445 return UD; 10446 } 10447 10448 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom, 10449 ArrayRef<NamedDecl *> Expansions) { 10450 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) || 10451 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) || 10452 isa<UsingPackDecl>(InstantiatedFrom)); 10453 10454 auto *UPD = 10455 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions); 10456 UPD->setAccess(InstantiatedFrom->getAccess()); 10457 CurContext->addDecl(UPD); 10458 return UPD; 10459 } 10460 10461 /// Additional checks for a using declaration referring to a constructor name. 10462 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) { 10463 assert(!UD->hasTypename() && "expecting a constructor name"); 10464 10465 const Type *SourceType = UD->getQualifier()->getAsType(); 10466 assert(SourceType && 10467 "Using decl naming constructor doesn't have type in scope spec."); 10468 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext); 10469 10470 // Check whether the named type is a direct base class. 10471 bool AnyDependentBases = false; 10472 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0), 10473 AnyDependentBases); 10474 if (!Base && !AnyDependentBases) { 10475 Diag(UD->getUsingLoc(), 10476 diag::err_using_decl_constructor_not_in_direct_base) 10477 << UD->getNameInfo().getSourceRange() 10478 << QualType(SourceType, 0) << TargetClass; 10479 UD->setInvalidDecl(); 10480 return true; 10481 } 10482 10483 if (Base) 10484 Base->setInheritConstructors(); 10485 10486 return false; 10487 } 10488 10489 /// Checks that the given using declaration is not an invalid 10490 /// redeclaration. Note that this is checking only for the using decl 10491 /// itself, not for any ill-formedness among the UsingShadowDecls. 10492 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 10493 bool HasTypenameKeyword, 10494 const CXXScopeSpec &SS, 10495 SourceLocation NameLoc, 10496 const LookupResult &Prev) { 10497 NestedNameSpecifier *Qual = SS.getScopeRep(); 10498 10499 // C++03 [namespace.udecl]p8: 10500 // C++0x [namespace.udecl]p10: 10501 // A using-declaration is a declaration and can therefore be used 10502 // repeatedly where (and only where) multiple declarations are 10503 // allowed. 10504 // 10505 // That's in non-member contexts. 10506 if (!CurContext->getRedeclContext()->isRecord()) { 10507 // A dependent qualifier outside a class can only ever resolve to an 10508 // enumeration type. Therefore it conflicts with any other non-type 10509 // declaration in the same scope. 10510 // FIXME: How should we check for dependent type-type conflicts at block 10511 // scope? 10512 if (Qual->isDependent() && !HasTypenameKeyword) { 10513 for (auto *D : Prev) { 10514 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) { 10515 bool OldCouldBeEnumerator = 10516 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D); 10517 Diag(NameLoc, 10518 OldCouldBeEnumerator ? diag::err_redefinition 10519 : diag::err_redefinition_different_kind) 10520 << Prev.getLookupName(); 10521 Diag(D->getLocation(), diag::note_previous_definition); 10522 return true; 10523 } 10524 } 10525 } 10526 return false; 10527 } 10528 10529 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) { 10530 NamedDecl *D = *I; 10531 10532 bool DTypename; 10533 NestedNameSpecifier *DQual; 10534 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) { 10535 DTypename = UD->hasTypename(); 10536 DQual = UD->getQualifier(); 10537 } else if (UnresolvedUsingValueDecl *UD 10538 = dyn_cast<UnresolvedUsingValueDecl>(D)) { 10539 DTypename = false; 10540 DQual = UD->getQualifier(); 10541 } else if (UnresolvedUsingTypenameDecl *UD 10542 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) { 10543 DTypename = true; 10544 DQual = UD->getQualifier(); 10545 } else continue; 10546 10547 // using decls differ if one says 'typename' and the other doesn't. 10548 // FIXME: non-dependent using decls? 10549 if (HasTypenameKeyword != DTypename) continue; 10550 10551 // using decls differ if they name different scopes (but note that 10552 // template instantiation can cause this check to trigger when it 10553 // didn't before instantiation). 10554 if (Context.getCanonicalNestedNameSpecifier(Qual) != 10555 Context.getCanonicalNestedNameSpecifier(DQual)) 10556 continue; 10557 10558 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange(); 10559 Diag(D->getLocation(), diag::note_using_decl) << 1; 10560 return true; 10561 } 10562 10563 return false; 10564 } 10565 10566 10567 /// Checks that the given nested-name qualifier used in a using decl 10568 /// in the current context is appropriately related to the current 10569 /// scope. If an error is found, diagnoses it and returns true. 10570 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, 10571 bool HasTypename, 10572 const CXXScopeSpec &SS, 10573 const DeclarationNameInfo &NameInfo, 10574 SourceLocation NameLoc) { 10575 DeclContext *NamedContext = computeDeclContext(SS); 10576 10577 if (!CurContext->isRecord()) { 10578 // C++03 [namespace.udecl]p3: 10579 // C++0x [namespace.udecl]p8: 10580 // A using-declaration for a class member shall be a member-declaration. 10581 10582 // If we weren't able to compute a valid scope, it might validly be a 10583 // dependent class scope or a dependent enumeration unscoped scope. If 10584 // we have a 'typename' keyword, the scope must resolve to a class type. 10585 if ((HasTypename && !NamedContext) || 10586 (NamedContext && NamedContext->getRedeclContext()->isRecord())) { 10587 auto *RD = NamedContext 10588 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext()) 10589 : nullptr; 10590 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD)) 10591 RD = nullptr; 10592 10593 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member) 10594 << SS.getRange(); 10595 10596 // If we have a complete, non-dependent source type, try to suggest a 10597 // way to get the same effect. 10598 if (!RD) 10599 return true; 10600 10601 // Find what this using-declaration was referring to. 10602 LookupResult R(*this, NameInfo, LookupOrdinaryName); 10603 R.setHideTags(false); 10604 R.suppressDiagnostics(); 10605 LookupQualifiedName(R, RD); 10606 10607 if (R.getAsSingle<TypeDecl>()) { 10608 if (getLangOpts().CPlusPlus11) { 10609 // Convert 'using X::Y;' to 'using Y = X::Y;'. 10610 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround) 10611 << 0 // alias declaration 10612 << FixItHint::CreateInsertion(SS.getBeginLoc(), 10613 NameInfo.getName().getAsString() + 10614 " = "); 10615 } else { 10616 // Convert 'using X::Y;' to 'typedef X::Y Y;'. 10617 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc()); 10618 Diag(InsertLoc, diag::note_using_decl_class_member_workaround) 10619 << 1 // typedef declaration 10620 << FixItHint::CreateReplacement(UsingLoc, "typedef") 10621 << FixItHint::CreateInsertion( 10622 InsertLoc, " " + NameInfo.getName().getAsString()); 10623 } 10624 } else if (R.getAsSingle<VarDecl>()) { 10625 // Don't provide a fixit outside C++11 mode; we don't want to suggest 10626 // repeating the type of the static data member here. 10627 FixItHint FixIt; 10628 if (getLangOpts().CPlusPlus11) { 10629 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 10630 FixIt = FixItHint::CreateReplacement( 10631 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = "); 10632 } 10633 10634 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 10635 << 2 // reference declaration 10636 << FixIt; 10637 } else if (R.getAsSingle<EnumConstantDecl>()) { 10638 // Don't provide a fixit outside C++11 mode; we don't want to suggest 10639 // repeating the type of the enumeration here, and we can't do so if 10640 // the type is anonymous. 10641 FixItHint FixIt; 10642 if (getLangOpts().CPlusPlus11) { 10643 // Convert 'using X::Y;' to 'auto &Y = X::Y;'. 10644 FixIt = FixItHint::CreateReplacement( 10645 UsingLoc, 10646 "constexpr auto " + NameInfo.getName().getAsString() + " = "); 10647 } 10648 10649 Diag(UsingLoc, diag::note_using_decl_class_member_workaround) 10650 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable 10651 << FixIt; 10652 } 10653 return true; 10654 } 10655 10656 // Otherwise, this might be valid. 10657 return false; 10658 } 10659 10660 // The current scope is a record. 10661 10662 // If the named context is dependent, we can't decide much. 10663 if (!NamedContext) { 10664 // FIXME: in C++0x, we can diagnose if we can prove that the 10665 // nested-name-specifier does not refer to a base class, which is 10666 // still possible in some cases. 10667 10668 // Otherwise we have to conservatively report that things might be 10669 // okay. 10670 return false; 10671 } 10672 10673 if (!NamedContext->isRecord()) { 10674 // Ideally this would point at the last name in the specifier, 10675 // but we don't have that level of source info. 10676 Diag(SS.getRange().getBegin(), 10677 diag::err_using_decl_nested_name_specifier_is_not_class) 10678 << SS.getScopeRep() << SS.getRange(); 10679 return true; 10680 } 10681 10682 if (!NamedContext->isDependentContext() && 10683 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext)) 10684 return true; 10685 10686 if (getLangOpts().CPlusPlus11) { 10687 // C++11 [namespace.udecl]p3: 10688 // In a using-declaration used as a member-declaration, the 10689 // nested-name-specifier shall name a base class of the class 10690 // being defined. 10691 10692 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom( 10693 cast<CXXRecordDecl>(NamedContext))) { 10694 if (CurContext == NamedContext) { 10695 Diag(NameLoc, 10696 diag::err_using_decl_nested_name_specifier_is_current_class) 10697 << SS.getRange(); 10698 return true; 10699 } 10700 10701 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) { 10702 Diag(SS.getRange().getBegin(), 10703 diag::err_using_decl_nested_name_specifier_is_not_base_class) 10704 << SS.getScopeRep() 10705 << cast<CXXRecordDecl>(CurContext) 10706 << SS.getRange(); 10707 } 10708 return true; 10709 } 10710 10711 return false; 10712 } 10713 10714 // C++03 [namespace.udecl]p4: 10715 // A using-declaration used as a member-declaration shall refer 10716 // to a member of a base class of the class being defined [etc.]. 10717 10718 // Salient point: SS doesn't have to name a base class as long as 10719 // lookup only finds members from base classes. Therefore we can 10720 // diagnose here only if we can prove that that can't happen, 10721 // i.e. if the class hierarchies provably don't intersect. 10722 10723 // TODO: it would be nice if "definitely valid" results were cached 10724 // in the UsingDecl and UsingShadowDecl so that these checks didn't 10725 // need to be repeated. 10726 10727 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases; 10728 auto Collect = [&Bases](const CXXRecordDecl *Base) { 10729 Bases.insert(Base); 10730 return true; 10731 }; 10732 10733 // Collect all bases. Return false if we find a dependent base. 10734 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect)) 10735 return false; 10736 10737 // Returns true if the base is dependent or is one of the accumulated base 10738 // classes. 10739 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) { 10740 return !Bases.count(Base); 10741 }; 10742 10743 // Return false if the class has a dependent base or if it or one 10744 // of its bases is present in the base set of the current context. 10745 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) || 10746 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase)) 10747 return false; 10748 10749 Diag(SS.getRange().getBegin(), 10750 diag::err_using_decl_nested_name_specifier_is_not_base_class) 10751 << SS.getScopeRep() 10752 << cast<CXXRecordDecl>(CurContext) 10753 << SS.getRange(); 10754 10755 return true; 10756 } 10757 10758 Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS, 10759 MultiTemplateParamsArg TemplateParamLists, 10760 SourceLocation UsingLoc, UnqualifiedId &Name, 10761 const ParsedAttributesView &AttrList, 10762 TypeResult Type, Decl *DeclFromDeclSpec) { 10763 // Skip up to the relevant declaration scope. 10764 while (S->isTemplateParamScope()) 10765 S = S->getParent(); 10766 assert((S->getFlags() & Scope::DeclScope) && 10767 "got alias-declaration outside of declaration scope"); 10768 10769 if (Type.isInvalid()) 10770 return nullptr; 10771 10772 bool Invalid = false; 10773 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name); 10774 TypeSourceInfo *TInfo = nullptr; 10775 GetTypeFromParser(Type.get(), &TInfo); 10776 10777 if (DiagnoseClassNameShadow(CurContext, NameInfo)) 10778 return nullptr; 10779 10780 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo, 10781 UPPC_DeclarationType)) { 10782 Invalid = true; 10783 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 10784 TInfo->getTypeLoc().getBeginLoc()); 10785 } 10786 10787 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 10788 TemplateParamLists.size() 10789 ? forRedeclarationInCurContext() 10790 : ForVisibleRedeclaration); 10791 LookupName(Previous, S); 10792 10793 // Warn about shadowing the name of a template parameter. 10794 if (Previous.isSingleResult() && 10795 Previous.getFoundDecl()->isTemplateParameter()) { 10796 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl()); 10797 Previous.clear(); 10798 } 10799 10800 assert(Name.Kind == UnqualifiedIdKind::IK_Identifier && 10801 "name in alias declaration must be an identifier"); 10802 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc, 10803 Name.StartLocation, 10804 Name.Identifier, TInfo); 10805 10806 NewTD->setAccess(AS); 10807 10808 if (Invalid) 10809 NewTD->setInvalidDecl(); 10810 10811 ProcessDeclAttributeList(S, NewTD, AttrList); 10812 AddPragmaAttributes(S, NewTD); 10813 10814 CheckTypedefForVariablyModifiedType(S, NewTD); 10815 Invalid |= NewTD->isInvalidDecl(); 10816 10817 bool Redeclaration = false; 10818 10819 NamedDecl *NewND; 10820 if (TemplateParamLists.size()) { 10821 TypeAliasTemplateDecl *OldDecl = nullptr; 10822 TemplateParameterList *OldTemplateParams = nullptr; 10823 10824 if (TemplateParamLists.size() != 1) { 10825 Diag(UsingLoc, diag::err_alias_template_extra_headers) 10826 << SourceRange(TemplateParamLists[1]->getTemplateLoc(), 10827 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc()); 10828 } 10829 TemplateParameterList *TemplateParams = TemplateParamLists[0]; 10830 10831 // Check that we can declare a template here. 10832 if (CheckTemplateDeclScope(S, TemplateParams)) 10833 return nullptr; 10834 10835 // Only consider previous declarations in the same scope. 10836 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false, 10837 /*ExplicitInstantiationOrSpecialization*/false); 10838 if (!Previous.empty()) { 10839 Redeclaration = true; 10840 10841 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>(); 10842 if (!OldDecl && !Invalid) { 10843 Diag(UsingLoc, diag::err_redefinition_different_kind) 10844 << Name.Identifier; 10845 10846 NamedDecl *OldD = Previous.getRepresentativeDecl(); 10847 if (OldD->getLocation().isValid()) 10848 Diag(OldD->getLocation(), diag::note_previous_definition); 10849 10850 Invalid = true; 10851 } 10852 10853 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) { 10854 if (TemplateParameterListsAreEqual(TemplateParams, 10855 OldDecl->getTemplateParameters(), 10856 /*Complain=*/true, 10857 TPL_TemplateMatch)) 10858 OldTemplateParams = 10859 OldDecl->getMostRecentDecl()->getTemplateParameters(); 10860 else 10861 Invalid = true; 10862 10863 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl(); 10864 if (!Invalid && 10865 !Context.hasSameType(OldTD->getUnderlyingType(), 10866 NewTD->getUnderlyingType())) { 10867 // FIXME: The C++0x standard does not clearly say this is ill-formed, 10868 // but we can't reasonably accept it. 10869 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef) 10870 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType(); 10871 if (OldTD->getLocation().isValid()) 10872 Diag(OldTD->getLocation(), diag::note_previous_definition); 10873 Invalid = true; 10874 } 10875 } 10876 } 10877 10878 // Merge any previous default template arguments into our parameters, 10879 // and check the parameter list. 10880 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams, 10881 TPC_TypeAliasTemplate)) 10882 return nullptr; 10883 10884 TypeAliasTemplateDecl *NewDecl = 10885 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc, 10886 Name.Identifier, TemplateParams, 10887 NewTD); 10888 NewTD->setDescribedAliasTemplate(NewDecl); 10889 10890 NewDecl->setAccess(AS); 10891 10892 if (Invalid) 10893 NewDecl->setInvalidDecl(); 10894 else if (OldDecl) { 10895 NewDecl->setPreviousDecl(OldDecl); 10896 CheckRedeclarationModuleOwnership(NewDecl, OldDecl); 10897 } 10898 10899 NewND = NewDecl; 10900 } else { 10901 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) { 10902 setTagNameForLinkagePurposes(TD, NewTD); 10903 handleTagNumbering(TD, S); 10904 } 10905 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration); 10906 NewND = NewTD; 10907 } 10908 10909 PushOnScopeChains(NewND, S); 10910 ActOnDocumentableDecl(NewND); 10911 return NewND; 10912 } 10913 10914 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc, 10915 SourceLocation AliasLoc, 10916 IdentifierInfo *Alias, CXXScopeSpec &SS, 10917 SourceLocation IdentLoc, 10918 IdentifierInfo *Ident) { 10919 10920 // Lookup the namespace name. 10921 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName); 10922 LookupParsedName(R, S, &SS); 10923 10924 if (R.isAmbiguous()) 10925 return nullptr; 10926 10927 if (R.empty()) { 10928 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) { 10929 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange(); 10930 return nullptr; 10931 } 10932 } 10933 assert(!R.isAmbiguous() && !R.empty()); 10934 NamedDecl *ND = R.getRepresentativeDecl(); 10935 10936 // Check if we have a previous declaration with the same name. 10937 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName, 10938 ForVisibleRedeclaration); 10939 LookupName(PrevR, S); 10940 10941 // Check we're not shadowing a template parameter. 10942 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) { 10943 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl()); 10944 PrevR.clear(); 10945 } 10946 10947 // Filter out any other lookup result from an enclosing scope. 10948 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false, 10949 /*AllowInlineNamespace*/false); 10950 10951 // Find the previous declaration and check that we can redeclare it. 10952 NamespaceAliasDecl *Prev = nullptr; 10953 if (PrevR.isSingleResult()) { 10954 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl(); 10955 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) { 10956 // We already have an alias with the same name that points to the same 10957 // namespace; check that it matches. 10958 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) { 10959 Prev = AD; 10960 } else if (isVisible(PrevDecl)) { 10961 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias) 10962 << Alias; 10963 Diag(AD->getLocation(), diag::note_previous_namespace_alias) 10964 << AD->getNamespace(); 10965 return nullptr; 10966 } 10967 } else if (isVisible(PrevDecl)) { 10968 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl()) 10969 ? diag::err_redefinition 10970 : diag::err_redefinition_different_kind; 10971 Diag(AliasLoc, DiagID) << Alias; 10972 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 10973 return nullptr; 10974 } 10975 } 10976 10977 // The use of a nested name specifier may trigger deprecation warnings. 10978 DiagnoseUseOfDecl(ND, IdentLoc); 10979 10980 NamespaceAliasDecl *AliasDecl = 10981 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc, 10982 Alias, SS.getWithLocInContext(Context), 10983 IdentLoc, ND); 10984 if (Prev) 10985 AliasDecl->setPreviousDecl(Prev); 10986 10987 PushOnScopeChains(AliasDecl, S); 10988 return AliasDecl; 10989 } 10990 10991 namespace { 10992 struct SpecialMemberExceptionSpecInfo 10993 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> { 10994 SourceLocation Loc; 10995 Sema::ImplicitExceptionSpecification ExceptSpec; 10996 10997 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD, 10998 Sema::CXXSpecialMember CSM, 10999 Sema::InheritedConstructorInfo *ICI, 11000 SourceLocation Loc) 11001 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {} 11002 11003 bool visitBase(CXXBaseSpecifier *Base); 11004 bool visitField(FieldDecl *FD); 11005 11006 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj, 11007 unsigned Quals); 11008 11009 void visitSubobjectCall(Subobject Subobj, 11010 Sema::SpecialMemberOverloadResult SMOR); 11011 }; 11012 } 11013 11014 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) { 11015 auto *RT = Base->getType()->getAs<RecordType>(); 11016 if (!RT) 11017 return false; 11018 11019 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl()); 11020 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass); 11021 if (auto *BaseCtor = SMOR.getMethod()) { 11022 visitSubobjectCall(Base, BaseCtor); 11023 return false; 11024 } 11025 11026 visitClassSubobject(BaseClass, Base, 0); 11027 return false; 11028 } 11029 11030 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) { 11031 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) { 11032 Expr *E = FD->getInClassInitializer(); 11033 if (!E) 11034 // FIXME: It's a little wasteful to build and throw away a 11035 // CXXDefaultInitExpr here. 11036 // FIXME: We should have a single context note pointing at Loc, and 11037 // this location should be MD->getLocation() instead, since that's 11038 // the location where we actually use the default init expression. 11039 E = S.BuildCXXDefaultInitExpr(Loc, FD).get(); 11040 if (E) 11041 ExceptSpec.CalledExpr(E); 11042 } else if (auto *RT = S.Context.getBaseElementType(FD->getType()) 11043 ->getAs<RecordType>()) { 11044 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD, 11045 FD->getType().getCVRQualifiers()); 11046 } 11047 return false; 11048 } 11049 11050 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class, 11051 Subobject Subobj, 11052 unsigned Quals) { 11053 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>(); 11054 bool IsMutable = Field && Field->isMutable(); 11055 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable)); 11056 } 11057 11058 void SpecialMemberExceptionSpecInfo::visitSubobjectCall( 11059 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) { 11060 // Note, if lookup fails, it doesn't matter what exception specification we 11061 // choose because the special member will be deleted. 11062 if (CXXMethodDecl *MD = SMOR.getMethod()) 11063 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD); 11064 } 11065 11066 namespace { 11067 /// RAII object to register a special member as being currently declared. 11068 struct ComputingExceptionSpec { 11069 Sema &S; 11070 11071 ComputingExceptionSpec(Sema &S, CXXMethodDecl *MD, SourceLocation Loc) 11072 : S(S) { 11073 Sema::CodeSynthesisContext Ctx; 11074 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation; 11075 Ctx.PointOfInstantiation = Loc; 11076 Ctx.Entity = MD; 11077 S.pushCodeSynthesisContext(Ctx); 11078 } 11079 ~ComputingExceptionSpec() { 11080 S.popCodeSynthesisContext(); 11081 } 11082 }; 11083 } 11084 11085 bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) { 11086 llvm::APSInt Result; 11087 ExprResult Converted = CheckConvertedConstantExpression( 11088 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool); 11089 ExplicitSpec.setExpr(Converted.get()); 11090 if (Converted.isUsable() && !Converted.get()->isValueDependent()) { 11091 ExplicitSpec.setKind(Result.getBoolValue() 11092 ? ExplicitSpecKind::ResolvedTrue 11093 : ExplicitSpecKind::ResolvedFalse); 11094 return true; 11095 } 11096 ExplicitSpec.setKind(ExplicitSpecKind::Unresolved); 11097 return false; 11098 } 11099 11100 ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) { 11101 ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved); 11102 if (!ExplicitExpr->isTypeDependent()) 11103 tryResolveExplicitSpecifier(ES); 11104 return ES; 11105 } 11106 11107 static Sema::ImplicitExceptionSpecification 11108 ComputeDefaultedSpecialMemberExceptionSpec( 11109 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM, 11110 Sema::InheritedConstructorInfo *ICI) { 11111 ComputingExceptionSpec CES(S, MD, Loc); 11112 11113 CXXRecordDecl *ClassDecl = MD->getParent(); 11114 11115 // C++ [except.spec]p14: 11116 // An implicitly declared special member function (Clause 12) shall have an 11117 // exception-specification. [...] 11118 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation()); 11119 if (ClassDecl->isInvalidDecl()) 11120 return Info.ExceptSpec; 11121 11122 // FIXME: If this diagnostic fires, we're probably missing a check for 11123 // attempting to resolve an exception specification before it's known 11124 // at a higher level. 11125 if (S.RequireCompleteType(MD->getLocation(), 11126 S.Context.getRecordType(ClassDecl), 11127 diag::err_exception_spec_incomplete_type)) 11128 return Info.ExceptSpec; 11129 11130 // C++1z [except.spec]p7: 11131 // [Look for exceptions thrown by] a constructor selected [...] to 11132 // initialize a potentially constructed subobject, 11133 // C++1z [except.spec]p8: 11134 // The exception specification for an implicitly-declared destructor, or a 11135 // destructor without a noexcept-specifier, is potentially-throwing if and 11136 // only if any of the destructors for any of its potentially constructed 11137 // subojects is potentially throwing. 11138 // FIXME: We respect the first rule but ignore the "potentially constructed" 11139 // in the second rule to resolve a core issue (no number yet) that would have 11140 // us reject: 11141 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; }; 11142 // struct B : A {}; 11143 // struct C : B { void f(); }; 11144 // ... due to giving B::~B() a non-throwing exception specification. 11145 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases 11146 : Info.VisitAllBases); 11147 11148 return Info.ExceptSpec; 11149 } 11150 11151 namespace { 11152 /// RAII object to register a special member as being currently declared. 11153 struct DeclaringSpecialMember { 11154 Sema &S; 11155 Sema::SpecialMemberDecl D; 11156 Sema::ContextRAII SavedContext; 11157 bool WasAlreadyBeingDeclared; 11158 11159 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM) 11160 : S(S), D(RD, CSM), SavedContext(S, RD) { 11161 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second; 11162 if (WasAlreadyBeingDeclared) 11163 // This almost never happens, but if it does, ensure that our cache 11164 // doesn't contain a stale result. 11165 S.SpecialMemberCache.clear(); 11166 else { 11167 // Register a note to be produced if we encounter an error while 11168 // declaring the special member. 11169 Sema::CodeSynthesisContext Ctx; 11170 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember; 11171 // FIXME: We don't have a location to use here. Using the class's 11172 // location maintains the fiction that we declare all special members 11173 // with the class, but (1) it's not clear that lying about that helps our 11174 // users understand what's going on, and (2) there may be outer contexts 11175 // on the stack (some of which are relevant) and printing them exposes 11176 // our lies. 11177 Ctx.PointOfInstantiation = RD->getLocation(); 11178 Ctx.Entity = RD; 11179 Ctx.SpecialMember = CSM; 11180 S.pushCodeSynthesisContext(Ctx); 11181 } 11182 } 11183 ~DeclaringSpecialMember() { 11184 if (!WasAlreadyBeingDeclared) { 11185 S.SpecialMembersBeingDeclared.erase(D); 11186 S.popCodeSynthesisContext(); 11187 } 11188 } 11189 11190 /// Are we already trying to declare this special member? 11191 bool isAlreadyBeingDeclared() const { 11192 return WasAlreadyBeingDeclared; 11193 } 11194 }; 11195 } 11196 11197 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) { 11198 // Look up any existing declarations, but don't trigger declaration of all 11199 // implicit special members with this name. 11200 DeclarationName Name = FD->getDeclName(); 11201 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName, 11202 ForExternalRedeclaration); 11203 for (auto *D : FD->getParent()->lookup(Name)) 11204 if (auto *Acceptable = R.getAcceptableDecl(D)) 11205 R.addDecl(Acceptable); 11206 R.resolveKind(); 11207 R.suppressDiagnostics(); 11208 11209 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false); 11210 } 11211 11212 void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem, 11213 QualType ResultTy, 11214 ArrayRef<QualType> Args) { 11215 // Build an exception specification pointing back at this constructor. 11216 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem); 11217 11218 if (getLangOpts().OpenCLCPlusPlus) { 11219 // OpenCL: Implicitly defaulted special member are of the generic address 11220 // space. 11221 EPI.TypeQuals.addAddressSpace(LangAS::opencl_generic); 11222 } 11223 11224 auto QT = Context.getFunctionType(ResultTy, Args, EPI); 11225 SpecialMem->setType(QT); 11226 } 11227 11228 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor( 11229 CXXRecordDecl *ClassDecl) { 11230 // C++ [class.ctor]p5: 11231 // A default constructor for a class X is a constructor of class X 11232 // that can be called without an argument. If there is no 11233 // user-declared constructor for class X, a default constructor is 11234 // implicitly declared. An implicitly-declared default constructor 11235 // is an inline public member of its class. 11236 assert(ClassDecl->needsImplicitDefaultConstructor() && 11237 "Should not build implicit default constructor!"); 11238 11239 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor); 11240 if (DSM.isAlreadyBeingDeclared()) 11241 return nullptr; 11242 11243 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 11244 CXXDefaultConstructor, 11245 false); 11246 11247 // Create the actual constructor declaration. 11248 CanQualType ClassType 11249 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 11250 SourceLocation ClassLoc = ClassDecl->getLocation(); 11251 DeclarationName Name 11252 = Context.DeclarationNames.getCXXConstructorName(ClassType); 11253 DeclarationNameInfo NameInfo(Name, ClassLoc); 11254 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create( 11255 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(), 11256 /*TInfo=*/nullptr, ExplicitSpecifier(), 11257 /*isInline=*/true, /*isImplicitlyDeclared=*/true, 11258 Constexpr ? CSK_constexpr : CSK_unspecified); 11259 DefaultCon->setAccess(AS_public); 11260 DefaultCon->setDefaulted(); 11261 11262 if (getLangOpts().CUDA) { 11263 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor, 11264 DefaultCon, 11265 /* ConstRHS */ false, 11266 /* Diagnose */ false); 11267 } 11268 11269 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None); 11270 11271 // We don't need to use SpecialMemberIsTrivial here; triviality for default 11272 // constructors is easy to compute. 11273 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor()); 11274 11275 // Note that we have declared this constructor. 11276 ++getASTContext().NumImplicitDefaultConstructorsDeclared; 11277 11278 Scope *S = getScopeForContext(ClassDecl); 11279 CheckImplicitSpecialMemberDeclaration(S, DefaultCon); 11280 11281 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor)) 11282 SetDeclDeleted(DefaultCon, ClassLoc); 11283 11284 if (S) 11285 PushOnScopeChains(DefaultCon, S, false); 11286 ClassDecl->addDecl(DefaultCon); 11287 11288 return DefaultCon; 11289 } 11290 11291 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 11292 CXXConstructorDecl *Constructor) { 11293 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() && 11294 !Constructor->doesThisDeclarationHaveABody() && 11295 !Constructor->isDeleted()) && 11296 "DefineImplicitDefaultConstructor - call it for implicit default ctor"); 11297 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 11298 return; 11299 11300 CXXRecordDecl *ClassDecl = Constructor->getParent(); 11301 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor"); 11302 11303 SynthesizedFunctionScope Scope(*this, Constructor); 11304 11305 // The exception specification is needed because we are defining the 11306 // function. 11307 ResolveExceptionSpec(CurrentLocation, 11308 Constructor->getType()->castAs<FunctionProtoType>()); 11309 MarkVTableUsed(CurrentLocation, ClassDecl); 11310 11311 // Add a context note for diagnostics produced after this point. 11312 Scope.addContextNote(CurrentLocation); 11313 11314 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) { 11315 Constructor->setInvalidDecl(); 11316 return; 11317 } 11318 11319 SourceLocation Loc = Constructor->getEndLoc().isValid() 11320 ? Constructor->getEndLoc() 11321 : Constructor->getLocation(); 11322 Constructor->setBody(new (Context) CompoundStmt(Loc)); 11323 Constructor->markUsed(Context); 11324 11325 if (ASTMutationListener *L = getASTMutationListener()) { 11326 L->CompletedImplicitDefinition(Constructor); 11327 } 11328 11329 DiagnoseUninitializedFields(*this, Constructor); 11330 } 11331 11332 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) { 11333 // Perform any delayed checks on exception specifications. 11334 CheckDelayedMemberExceptionSpecs(); 11335 } 11336 11337 /// Find or create the fake constructor we synthesize to model constructing an 11338 /// object of a derived class via a constructor of a base class. 11339 CXXConstructorDecl * 11340 Sema::findInheritingConstructor(SourceLocation Loc, 11341 CXXConstructorDecl *BaseCtor, 11342 ConstructorUsingShadowDecl *Shadow) { 11343 CXXRecordDecl *Derived = Shadow->getParent(); 11344 SourceLocation UsingLoc = Shadow->getLocation(); 11345 11346 // FIXME: Add a new kind of DeclarationName for an inherited constructor. 11347 // For now we use the name of the base class constructor as a member of the 11348 // derived class to indicate a (fake) inherited constructor name. 11349 DeclarationName Name = BaseCtor->getDeclName(); 11350 11351 // Check to see if we already have a fake constructor for this inherited 11352 // constructor call. 11353 for (NamedDecl *Ctor : Derived->lookup(Name)) 11354 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor) 11355 ->getInheritedConstructor() 11356 .getConstructor(), 11357 BaseCtor)) 11358 return cast<CXXConstructorDecl>(Ctor); 11359 11360 DeclarationNameInfo NameInfo(Name, UsingLoc); 11361 TypeSourceInfo *TInfo = 11362 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc); 11363 FunctionProtoTypeLoc ProtoLoc = 11364 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>(); 11365 11366 // Check the inherited constructor is valid and find the list of base classes 11367 // from which it was inherited. 11368 InheritedConstructorInfo ICI(*this, Loc, Shadow); 11369 11370 bool Constexpr = 11371 BaseCtor->isConstexpr() && 11372 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor, 11373 false, BaseCtor, &ICI); 11374 11375 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create( 11376 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo, 11377 BaseCtor->getExplicitSpecifier(), /*isInline=*/true, 11378 /*isImplicitlyDeclared=*/true, 11379 Constexpr ? BaseCtor->getConstexprKind() : CSK_unspecified, 11380 InheritedConstructor(Shadow, BaseCtor)); 11381 if (Shadow->isInvalidDecl()) 11382 DerivedCtor->setInvalidDecl(); 11383 11384 // Build an unevaluated exception specification for this fake constructor. 11385 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>(); 11386 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 11387 EPI.ExceptionSpec.Type = EST_Unevaluated; 11388 EPI.ExceptionSpec.SourceDecl = DerivedCtor; 11389 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(), 11390 FPT->getParamTypes(), EPI)); 11391 11392 // Build the parameter declarations. 11393 SmallVector<ParmVarDecl *, 16> ParamDecls; 11394 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) { 11395 TypeSourceInfo *TInfo = 11396 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc); 11397 ParmVarDecl *PD = ParmVarDecl::Create( 11398 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr, 11399 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr); 11400 PD->setScopeInfo(0, I); 11401 PD->setImplicit(); 11402 // Ensure attributes are propagated onto parameters (this matters for 11403 // format, pass_object_size, ...). 11404 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I)); 11405 ParamDecls.push_back(PD); 11406 ProtoLoc.setParam(I, PD); 11407 } 11408 11409 // Set up the new constructor. 11410 assert(!BaseCtor->isDeleted() && "should not use deleted constructor"); 11411 DerivedCtor->setAccess(BaseCtor->getAccess()); 11412 DerivedCtor->setParams(ParamDecls); 11413 Derived->addDecl(DerivedCtor); 11414 11415 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI)) 11416 SetDeclDeleted(DerivedCtor, UsingLoc); 11417 11418 return DerivedCtor; 11419 } 11420 11421 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) { 11422 InheritedConstructorInfo ICI(*this, Ctor->getLocation(), 11423 Ctor->getInheritedConstructor().getShadowDecl()); 11424 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI, 11425 /*Diagnose*/true); 11426 } 11427 11428 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation, 11429 CXXConstructorDecl *Constructor) { 11430 CXXRecordDecl *ClassDecl = Constructor->getParent(); 11431 assert(Constructor->getInheritedConstructor() && 11432 !Constructor->doesThisDeclarationHaveABody() && 11433 !Constructor->isDeleted()); 11434 if (Constructor->willHaveBody() || Constructor->isInvalidDecl()) 11435 return; 11436 11437 // Initializations are performed "as if by a defaulted default constructor", 11438 // so enter the appropriate scope. 11439 SynthesizedFunctionScope Scope(*this, Constructor); 11440 11441 // The exception specification is needed because we are defining the 11442 // function. 11443 ResolveExceptionSpec(CurrentLocation, 11444 Constructor->getType()->castAs<FunctionProtoType>()); 11445 MarkVTableUsed(CurrentLocation, ClassDecl); 11446 11447 // Add a context note for diagnostics produced after this point. 11448 Scope.addContextNote(CurrentLocation); 11449 11450 ConstructorUsingShadowDecl *Shadow = 11451 Constructor->getInheritedConstructor().getShadowDecl(); 11452 CXXConstructorDecl *InheritedCtor = 11453 Constructor->getInheritedConstructor().getConstructor(); 11454 11455 // [class.inhctor.init]p1: 11456 // initialization proceeds as if a defaulted default constructor is used to 11457 // initialize the D object and each base class subobject from which the 11458 // constructor was inherited 11459 11460 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow); 11461 CXXRecordDecl *RD = Shadow->getParent(); 11462 SourceLocation InitLoc = Shadow->getLocation(); 11463 11464 // Build explicit initializers for all base classes from which the 11465 // constructor was inherited. 11466 SmallVector<CXXCtorInitializer*, 8> Inits; 11467 for (bool VBase : {false, true}) { 11468 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) { 11469 if (B.isVirtual() != VBase) 11470 continue; 11471 11472 auto *BaseRD = B.getType()->getAsCXXRecordDecl(); 11473 if (!BaseRD) 11474 continue; 11475 11476 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor); 11477 if (!BaseCtor.first) 11478 continue; 11479 11480 MarkFunctionReferenced(CurrentLocation, BaseCtor.first); 11481 ExprResult Init = new (Context) CXXInheritedCtorInitExpr( 11482 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second); 11483 11484 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc); 11485 Inits.push_back(new (Context) CXXCtorInitializer( 11486 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc, 11487 SourceLocation())); 11488 } 11489 } 11490 11491 // We now proceed as if for a defaulted default constructor, with the relevant 11492 // initializers replaced. 11493 11494 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) { 11495 Constructor->setInvalidDecl(); 11496 return; 11497 } 11498 11499 Constructor->setBody(new (Context) CompoundStmt(InitLoc)); 11500 Constructor->markUsed(Context); 11501 11502 if (ASTMutationListener *L = getASTMutationListener()) { 11503 L->CompletedImplicitDefinition(Constructor); 11504 } 11505 11506 DiagnoseUninitializedFields(*this, Constructor); 11507 } 11508 11509 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) { 11510 // C++ [class.dtor]p2: 11511 // If a class has no user-declared destructor, a destructor is 11512 // declared implicitly. An implicitly-declared destructor is an 11513 // inline public member of its class. 11514 assert(ClassDecl->needsImplicitDestructor()); 11515 11516 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor); 11517 if (DSM.isAlreadyBeingDeclared()) 11518 return nullptr; 11519 11520 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 11521 CXXDestructor, 11522 false); 11523 11524 // Create the actual destructor declaration. 11525 CanQualType ClassType 11526 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl)); 11527 SourceLocation ClassLoc = ClassDecl->getLocation(); 11528 DeclarationName Name 11529 = Context.DeclarationNames.getCXXDestructorName(ClassType); 11530 DeclarationNameInfo NameInfo(Name, ClassLoc); 11531 CXXDestructorDecl *Destructor = 11532 CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, 11533 QualType(), nullptr, /*isInline=*/true, 11534 /*isImplicitlyDeclared=*/true, 11535 Constexpr ? CSK_constexpr : CSK_unspecified); 11536 Destructor->setAccess(AS_public); 11537 Destructor->setDefaulted(); 11538 11539 if (getLangOpts().CUDA) { 11540 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor, 11541 Destructor, 11542 /* ConstRHS */ false, 11543 /* Diagnose */ false); 11544 } 11545 11546 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None); 11547 11548 // We don't need to use SpecialMemberIsTrivial here; triviality for 11549 // destructors is easy to compute. 11550 Destructor->setTrivial(ClassDecl->hasTrivialDestructor()); 11551 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() || 11552 ClassDecl->hasTrivialDestructorForCall()); 11553 11554 // Note that we have declared this destructor. 11555 ++getASTContext().NumImplicitDestructorsDeclared; 11556 11557 Scope *S = getScopeForContext(ClassDecl); 11558 CheckImplicitSpecialMemberDeclaration(S, Destructor); 11559 11560 // We can't check whether an implicit destructor is deleted before we complete 11561 // the definition of the class, because its validity depends on the alignment 11562 // of the class. We'll check this from ActOnFields once the class is complete. 11563 if (ClassDecl->isCompleteDefinition() && 11564 ShouldDeleteSpecialMember(Destructor, CXXDestructor)) 11565 SetDeclDeleted(Destructor, ClassLoc); 11566 11567 // Introduce this destructor into its scope. 11568 if (S) 11569 PushOnScopeChains(Destructor, S, false); 11570 ClassDecl->addDecl(Destructor); 11571 11572 return Destructor; 11573 } 11574 11575 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation, 11576 CXXDestructorDecl *Destructor) { 11577 assert((Destructor->isDefaulted() && 11578 !Destructor->doesThisDeclarationHaveABody() && 11579 !Destructor->isDeleted()) && 11580 "DefineImplicitDestructor - call it for implicit default dtor"); 11581 if (Destructor->willHaveBody() || Destructor->isInvalidDecl()) 11582 return; 11583 11584 CXXRecordDecl *ClassDecl = Destructor->getParent(); 11585 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor"); 11586 11587 SynthesizedFunctionScope Scope(*this, Destructor); 11588 11589 // The exception specification is needed because we are defining the 11590 // function. 11591 ResolveExceptionSpec(CurrentLocation, 11592 Destructor->getType()->castAs<FunctionProtoType>()); 11593 MarkVTableUsed(CurrentLocation, ClassDecl); 11594 11595 // Add a context note for diagnostics produced after this point. 11596 Scope.addContextNote(CurrentLocation); 11597 11598 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 11599 Destructor->getParent()); 11600 11601 if (CheckDestructor(Destructor)) { 11602 Destructor->setInvalidDecl(); 11603 return; 11604 } 11605 11606 SourceLocation Loc = Destructor->getEndLoc().isValid() 11607 ? Destructor->getEndLoc() 11608 : Destructor->getLocation(); 11609 Destructor->setBody(new (Context) CompoundStmt(Loc)); 11610 Destructor->markUsed(Context); 11611 11612 if (ASTMutationListener *L = getASTMutationListener()) { 11613 L->CompletedImplicitDefinition(Destructor); 11614 } 11615 } 11616 11617 /// Perform any semantic analysis which needs to be delayed until all 11618 /// pending class member declarations have been parsed. 11619 void Sema::ActOnFinishCXXMemberDecls() { 11620 // If the context is an invalid C++ class, just suppress these checks. 11621 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) { 11622 if (Record->isInvalidDecl()) { 11623 DelayedOverridingExceptionSpecChecks.clear(); 11624 DelayedEquivalentExceptionSpecChecks.clear(); 11625 return; 11626 } 11627 checkForMultipleExportedDefaultConstructors(*this, Record); 11628 } 11629 } 11630 11631 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) { 11632 referenceDLLExportedClassMethods(); 11633 11634 if (!DelayedDllExportMemberFunctions.empty()) { 11635 SmallVector<CXXMethodDecl*, 4> WorkList; 11636 std::swap(DelayedDllExportMemberFunctions, WorkList); 11637 for (CXXMethodDecl *M : WorkList) { 11638 DefineImplicitSpecialMember(*this, M, M->getLocation()); 11639 11640 // Pass the method to the consumer to get emitted. This is not necessary 11641 // for explicit instantiation definitions, as they will get emitted 11642 // anyway. 11643 if (M->getParent()->getTemplateSpecializationKind() != 11644 TSK_ExplicitInstantiationDefinition) 11645 ActOnFinishInlineFunctionDef(M); 11646 } 11647 } 11648 } 11649 11650 void Sema::referenceDLLExportedClassMethods() { 11651 if (!DelayedDllExportClasses.empty()) { 11652 // Calling ReferenceDllExportedMembers might cause the current function to 11653 // be called again, so use a local copy of DelayedDllExportClasses. 11654 SmallVector<CXXRecordDecl *, 4> WorkList; 11655 std::swap(DelayedDllExportClasses, WorkList); 11656 for (CXXRecordDecl *Class : WorkList) 11657 ReferenceDllExportedMembers(*this, Class); 11658 } 11659 } 11660 11661 void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) { 11662 assert(getLangOpts().CPlusPlus11 && 11663 "adjusting dtor exception specs was introduced in c++11"); 11664 11665 if (Destructor->isDependentContext()) 11666 return; 11667 11668 // C++11 [class.dtor]p3: 11669 // A declaration of a destructor that does not have an exception- 11670 // specification is implicitly considered to have the same exception- 11671 // specification as an implicit declaration. 11672 const FunctionProtoType *DtorType = Destructor->getType()-> 11673 getAs<FunctionProtoType>(); 11674 if (DtorType->hasExceptionSpec()) 11675 return; 11676 11677 // Replace the destructor's type, building off the existing one. Fortunately, 11678 // the only thing of interest in the destructor type is its extended info. 11679 // The return and arguments are fixed. 11680 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo(); 11681 EPI.ExceptionSpec.Type = EST_Unevaluated; 11682 EPI.ExceptionSpec.SourceDecl = Destructor; 11683 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI)); 11684 11685 // FIXME: If the destructor has a body that could throw, and the newly created 11686 // spec doesn't allow exceptions, we should emit a warning, because this 11687 // change in behavior can break conforming C++03 programs at runtime. 11688 // However, we don't have a body or an exception specification yet, so it 11689 // needs to be done somewhere else. 11690 } 11691 11692 namespace { 11693 /// An abstract base class for all helper classes used in building the 11694 // copy/move operators. These classes serve as factory functions and help us 11695 // avoid using the same Expr* in the AST twice. 11696 class ExprBuilder { 11697 ExprBuilder(const ExprBuilder&) = delete; 11698 ExprBuilder &operator=(const ExprBuilder&) = delete; 11699 11700 protected: 11701 static Expr *assertNotNull(Expr *E) { 11702 assert(E && "Expression construction must not fail."); 11703 return E; 11704 } 11705 11706 public: 11707 ExprBuilder() {} 11708 virtual ~ExprBuilder() {} 11709 11710 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0; 11711 }; 11712 11713 class RefBuilder: public ExprBuilder { 11714 VarDecl *Var; 11715 QualType VarType; 11716 11717 public: 11718 Expr *build(Sema &S, SourceLocation Loc) const override { 11719 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc)); 11720 } 11721 11722 RefBuilder(VarDecl *Var, QualType VarType) 11723 : Var(Var), VarType(VarType) {} 11724 }; 11725 11726 class ThisBuilder: public ExprBuilder { 11727 public: 11728 Expr *build(Sema &S, SourceLocation Loc) const override { 11729 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>()); 11730 } 11731 }; 11732 11733 class CastBuilder: public ExprBuilder { 11734 const ExprBuilder &Builder; 11735 QualType Type; 11736 ExprValueKind Kind; 11737 const CXXCastPath &Path; 11738 11739 public: 11740 Expr *build(Sema &S, SourceLocation Loc) const override { 11741 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type, 11742 CK_UncheckedDerivedToBase, Kind, 11743 &Path).get()); 11744 } 11745 11746 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind, 11747 const CXXCastPath &Path) 11748 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {} 11749 }; 11750 11751 class DerefBuilder: public ExprBuilder { 11752 const ExprBuilder &Builder; 11753 11754 public: 11755 Expr *build(Sema &S, SourceLocation Loc) const override { 11756 return assertNotNull( 11757 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get()); 11758 } 11759 11760 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 11761 }; 11762 11763 class MemberBuilder: public ExprBuilder { 11764 const ExprBuilder &Builder; 11765 QualType Type; 11766 CXXScopeSpec SS; 11767 bool IsArrow; 11768 LookupResult &MemberLookup; 11769 11770 public: 11771 Expr *build(Sema &S, SourceLocation Loc) const override { 11772 return assertNotNull(S.BuildMemberReferenceExpr( 11773 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(), 11774 nullptr, MemberLookup, nullptr, nullptr).get()); 11775 } 11776 11777 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow, 11778 LookupResult &MemberLookup) 11779 : Builder(Builder), Type(Type), IsArrow(IsArrow), 11780 MemberLookup(MemberLookup) {} 11781 }; 11782 11783 class MoveCastBuilder: public ExprBuilder { 11784 const ExprBuilder &Builder; 11785 11786 public: 11787 Expr *build(Sema &S, SourceLocation Loc) const override { 11788 return assertNotNull(CastForMoving(S, Builder.build(S, Loc))); 11789 } 11790 11791 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 11792 }; 11793 11794 class LvalueConvBuilder: public ExprBuilder { 11795 const ExprBuilder &Builder; 11796 11797 public: 11798 Expr *build(Sema &S, SourceLocation Loc) const override { 11799 return assertNotNull( 11800 S.DefaultLvalueConversion(Builder.build(S, Loc)).get()); 11801 } 11802 11803 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {} 11804 }; 11805 11806 class SubscriptBuilder: public ExprBuilder { 11807 const ExprBuilder &Base; 11808 const ExprBuilder &Index; 11809 11810 public: 11811 Expr *build(Sema &S, SourceLocation Loc) const override { 11812 return assertNotNull(S.CreateBuiltinArraySubscriptExpr( 11813 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get()); 11814 } 11815 11816 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index) 11817 : Base(Base), Index(Index) {} 11818 }; 11819 11820 } // end anonymous namespace 11821 11822 /// When generating a defaulted copy or move assignment operator, if a field 11823 /// should be copied with __builtin_memcpy rather than via explicit assignments, 11824 /// do so. This optimization only applies for arrays of scalars, and for arrays 11825 /// of class type where the selected copy/move-assignment operator is trivial. 11826 static StmtResult 11827 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T, 11828 const ExprBuilder &ToB, const ExprBuilder &FromB) { 11829 // Compute the size of the memory buffer to be copied. 11830 QualType SizeType = S.Context.getSizeType(); 11831 llvm::APInt Size(S.Context.getTypeSize(SizeType), 11832 S.Context.getTypeSizeInChars(T).getQuantity()); 11833 11834 // Take the address of the field references for "from" and "to". We 11835 // directly construct UnaryOperators here because semantic analysis 11836 // does not permit us to take the address of an xvalue. 11837 Expr *From = FromB.build(S, Loc); 11838 From = new (S.Context) UnaryOperator(From, UO_AddrOf, 11839 S.Context.getPointerType(From->getType()), 11840 VK_RValue, OK_Ordinary, Loc, false); 11841 Expr *To = ToB.build(S, Loc); 11842 To = new (S.Context) UnaryOperator(To, UO_AddrOf, 11843 S.Context.getPointerType(To->getType()), 11844 VK_RValue, OK_Ordinary, Loc, false); 11845 11846 const Type *E = T->getBaseElementTypeUnsafe(); 11847 bool NeedsCollectableMemCpy = 11848 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember(); 11849 11850 // Create a reference to the __builtin_objc_memmove_collectable function 11851 StringRef MemCpyName = NeedsCollectableMemCpy ? 11852 "__builtin_objc_memmove_collectable" : 11853 "__builtin_memcpy"; 11854 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc, 11855 Sema::LookupOrdinaryName); 11856 S.LookupName(R, S.TUScope, true); 11857 11858 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>(); 11859 if (!MemCpy) 11860 // Something went horribly wrong earlier, and we will have complained 11861 // about it. 11862 return StmtError(); 11863 11864 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy, 11865 VK_RValue, Loc, nullptr); 11866 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail"); 11867 11868 Expr *CallArgs[] = { 11869 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc) 11870 }; 11871 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(), 11872 Loc, CallArgs, Loc); 11873 11874 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!"); 11875 return Call.getAs<Stmt>(); 11876 } 11877 11878 /// Builds a statement that copies/moves the given entity from \p From to 11879 /// \c To. 11880 /// 11881 /// This routine is used to copy/move the members of a class with an 11882 /// implicitly-declared copy/move assignment operator. When the entities being 11883 /// copied are arrays, this routine builds for loops to copy them. 11884 /// 11885 /// \param S The Sema object used for type-checking. 11886 /// 11887 /// \param Loc The location where the implicit copy/move is being generated. 11888 /// 11889 /// \param T The type of the expressions being copied/moved. Both expressions 11890 /// must have this type. 11891 /// 11892 /// \param To The expression we are copying/moving to. 11893 /// 11894 /// \param From The expression we are copying/moving from. 11895 /// 11896 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject. 11897 /// Otherwise, it's a non-static member subobject. 11898 /// 11899 /// \param Copying Whether we're copying or moving. 11900 /// 11901 /// \param Depth Internal parameter recording the depth of the recursion. 11902 /// 11903 /// \returns A statement or a loop that copies the expressions, or StmtResult(0) 11904 /// if a memcpy should be used instead. 11905 static StmtResult 11906 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T, 11907 const ExprBuilder &To, const ExprBuilder &From, 11908 bool CopyingBaseSubobject, bool Copying, 11909 unsigned Depth = 0) { 11910 // C++11 [class.copy]p28: 11911 // Each subobject is assigned in the manner appropriate to its type: 11912 // 11913 // - if the subobject is of class type, as if by a call to operator= with 11914 // the subobject as the object expression and the corresponding 11915 // subobject of x as a single function argument (as if by explicit 11916 // qualification; that is, ignoring any possible virtual overriding 11917 // functions in more derived classes); 11918 // 11919 // C++03 [class.copy]p13: 11920 // - if the subobject is of class type, the copy assignment operator for 11921 // the class is used (as if by explicit qualification; that is, 11922 // ignoring any possible virtual overriding functions in more derived 11923 // classes); 11924 if (const RecordType *RecordTy = T->getAs<RecordType>()) { 11925 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl()); 11926 11927 // Look for operator=. 11928 DeclarationName Name 11929 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal); 11930 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName); 11931 S.LookupQualifiedName(OpLookup, ClassDecl, false); 11932 11933 // Prior to C++11, filter out any result that isn't a copy/move-assignment 11934 // operator. 11935 if (!S.getLangOpts().CPlusPlus11) { 11936 LookupResult::Filter F = OpLookup.makeFilter(); 11937 while (F.hasNext()) { 11938 NamedDecl *D = F.next(); 11939 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 11940 if (Method->isCopyAssignmentOperator() || 11941 (!Copying && Method->isMoveAssignmentOperator())) 11942 continue; 11943 11944 F.erase(); 11945 } 11946 F.done(); 11947 } 11948 11949 // Suppress the protected check (C++ [class.protected]) for each of the 11950 // assignment operators we found. This strange dance is required when 11951 // we're assigning via a base classes's copy-assignment operator. To 11952 // ensure that we're getting the right base class subobject (without 11953 // ambiguities), we need to cast "this" to that subobject type; to 11954 // ensure that we don't go through the virtual call mechanism, we need 11955 // to qualify the operator= name with the base class (see below). However, 11956 // this means that if the base class has a protected copy assignment 11957 // operator, the protected member access check will fail. So, we 11958 // rewrite "protected" access to "public" access in this case, since we 11959 // know by construction that we're calling from a derived class. 11960 if (CopyingBaseSubobject) { 11961 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end(); 11962 L != LEnd; ++L) { 11963 if (L.getAccess() == AS_protected) 11964 L.setAccess(AS_public); 11965 } 11966 } 11967 11968 // Create the nested-name-specifier that will be used to qualify the 11969 // reference to operator=; this is required to suppress the virtual 11970 // call mechanism. 11971 CXXScopeSpec SS; 11972 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr()); 11973 SS.MakeTrivial(S.Context, 11974 NestedNameSpecifier::Create(S.Context, nullptr, false, 11975 CanonicalT), 11976 Loc); 11977 11978 // Create the reference to operator=. 11979 ExprResult OpEqualRef 11980 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false, 11981 SS, /*TemplateKWLoc=*/SourceLocation(), 11982 /*FirstQualifierInScope=*/nullptr, 11983 OpLookup, 11984 /*TemplateArgs=*/nullptr, /*S*/nullptr, 11985 /*SuppressQualifierCheck=*/true); 11986 if (OpEqualRef.isInvalid()) 11987 return StmtError(); 11988 11989 // Build the call to the assignment operator. 11990 11991 Expr *FromInst = From.build(S, Loc); 11992 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr, 11993 OpEqualRef.getAs<Expr>(), 11994 Loc, FromInst, Loc); 11995 if (Call.isInvalid()) 11996 return StmtError(); 11997 11998 // If we built a call to a trivial 'operator=' while copying an array, 11999 // bail out. We'll replace the whole shebang with a memcpy. 12000 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get()); 12001 if (CE && CE->getMethodDecl()->isTrivial() && Depth) 12002 return StmtResult((Stmt*)nullptr); 12003 12004 // Convert to an expression-statement, and clean up any produced 12005 // temporaries. 12006 return S.ActOnExprStmt(Call); 12007 } 12008 12009 // - if the subobject is of scalar type, the built-in assignment 12010 // operator is used. 12011 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T); 12012 if (!ArrayTy) { 12013 ExprResult Assignment = S.CreateBuiltinBinOp( 12014 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc)); 12015 if (Assignment.isInvalid()) 12016 return StmtError(); 12017 return S.ActOnExprStmt(Assignment); 12018 } 12019 12020 // - if the subobject is an array, each element is assigned, in the 12021 // manner appropriate to the element type; 12022 12023 // Construct a loop over the array bounds, e.g., 12024 // 12025 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0) 12026 // 12027 // that will copy each of the array elements. 12028 QualType SizeType = S.Context.getSizeType(); 12029 12030 // Create the iteration variable. 12031 IdentifierInfo *IterationVarName = nullptr; 12032 { 12033 SmallString<8> Str; 12034 llvm::raw_svector_ostream OS(Str); 12035 OS << "__i" << Depth; 12036 IterationVarName = &S.Context.Idents.get(OS.str()); 12037 } 12038 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, 12039 IterationVarName, SizeType, 12040 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), 12041 SC_None); 12042 12043 // Initialize the iteration variable to zero. 12044 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0); 12045 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc)); 12046 12047 // Creates a reference to the iteration variable. 12048 RefBuilder IterationVarRef(IterationVar, SizeType); 12049 LvalueConvBuilder IterationVarRefRVal(IterationVarRef); 12050 12051 // Create the DeclStmt that holds the iteration variable. 12052 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc); 12053 12054 // Subscript the "from" and "to" expressions with the iteration variable. 12055 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal); 12056 MoveCastBuilder FromIndexMove(FromIndexCopy); 12057 const ExprBuilder *FromIndex; 12058 if (Copying) 12059 FromIndex = &FromIndexCopy; 12060 else 12061 FromIndex = &FromIndexMove; 12062 12063 SubscriptBuilder ToIndex(To, IterationVarRefRVal); 12064 12065 // Build the copy/move for an individual element of the array. 12066 StmtResult Copy = 12067 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(), 12068 ToIndex, *FromIndex, CopyingBaseSubobject, 12069 Copying, Depth + 1); 12070 // Bail out if copying fails or if we determined that we should use memcpy. 12071 if (Copy.isInvalid() || !Copy.get()) 12072 return Copy; 12073 12074 // Create the comparison against the array bound. 12075 llvm::APInt Upper 12076 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType)); 12077 Expr *Comparison 12078 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc), 12079 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), 12080 BO_NE, S.Context.BoolTy, 12081 VK_RValue, OK_Ordinary, Loc, FPOptions()); 12082 12083 // Create the pre-increment of the iteration variable. We can determine 12084 // whether the increment will overflow based on the value of the array 12085 // bound. 12086 Expr *Increment = new (S.Context) 12087 UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc, SizeType, 12088 VK_LValue, OK_Ordinary, Loc, Upper.isMaxValue()); 12089 12090 // Construct the loop that copies all elements of this array. 12091 return S.ActOnForStmt( 12092 Loc, Loc, InitStmt, 12093 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean), 12094 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get()); 12095 } 12096 12097 static StmtResult 12098 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T, 12099 const ExprBuilder &To, const ExprBuilder &From, 12100 bool CopyingBaseSubobject, bool Copying) { 12101 // Maybe we should use a memcpy? 12102 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() && 12103 T.isTriviallyCopyableType(S.Context)) 12104 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 12105 12106 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From, 12107 CopyingBaseSubobject, 12108 Copying, 0)); 12109 12110 // If we ended up picking a trivial assignment operator for an array of a 12111 // non-trivially-copyable class type, just emit a memcpy. 12112 if (!Result.isInvalid() && !Result.get()) 12113 return buildMemcpyForAssignmentOp(S, Loc, T, To, From); 12114 12115 return Result; 12116 } 12117 12118 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) { 12119 // Note: The following rules are largely analoguous to the copy 12120 // constructor rules. Note that virtual bases are not taken into account 12121 // for determining the argument type of the operator. Note also that 12122 // operators taking an object instead of a reference are allowed. 12123 assert(ClassDecl->needsImplicitCopyAssignment()); 12124 12125 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment); 12126 if (DSM.isAlreadyBeingDeclared()) 12127 return nullptr; 12128 12129 QualType ArgType = Context.getTypeDeclType(ClassDecl); 12130 if (Context.getLangOpts().OpenCLCPlusPlus) 12131 ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic); 12132 QualType RetType = Context.getLValueReferenceType(ArgType); 12133 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam(); 12134 if (Const) 12135 ArgType = ArgType.withConst(); 12136 12137 ArgType = Context.getLValueReferenceType(ArgType); 12138 12139 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12140 CXXCopyAssignment, 12141 Const); 12142 12143 // An implicitly-declared copy assignment operator is an inline public 12144 // member of its class. 12145 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 12146 SourceLocation ClassLoc = ClassDecl->getLocation(); 12147 DeclarationNameInfo NameInfo(Name, ClassLoc); 12148 CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create( 12149 Context, ClassDecl, ClassLoc, NameInfo, QualType(), 12150 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 12151 /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified, 12152 SourceLocation()); 12153 CopyAssignment->setAccess(AS_public); 12154 CopyAssignment->setDefaulted(); 12155 CopyAssignment->setImplicit(); 12156 12157 if (getLangOpts().CUDA) { 12158 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment, 12159 CopyAssignment, 12160 /* ConstRHS */ Const, 12161 /* Diagnose */ false); 12162 } 12163 12164 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType); 12165 12166 // Add the parameter to the operator. 12167 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment, 12168 ClassLoc, ClassLoc, 12169 /*Id=*/nullptr, ArgType, 12170 /*TInfo=*/nullptr, SC_None, 12171 nullptr); 12172 CopyAssignment->setParams(FromParam); 12173 12174 CopyAssignment->setTrivial( 12175 ClassDecl->needsOverloadResolutionForCopyAssignment() 12176 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment) 12177 : ClassDecl->hasTrivialCopyAssignment()); 12178 12179 // Note that we have added this copy-assignment operator. 12180 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared; 12181 12182 Scope *S = getScopeForContext(ClassDecl); 12183 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment); 12184 12185 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) 12186 SetDeclDeleted(CopyAssignment, ClassLoc); 12187 12188 if (S) 12189 PushOnScopeChains(CopyAssignment, S, false); 12190 ClassDecl->addDecl(CopyAssignment); 12191 12192 return CopyAssignment; 12193 } 12194 12195 /// Diagnose an implicit copy operation for a class which is odr-used, but 12196 /// which is deprecated because the class has a user-declared copy constructor, 12197 /// copy assignment operator, or destructor. 12198 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) { 12199 assert(CopyOp->isImplicit()); 12200 12201 CXXRecordDecl *RD = CopyOp->getParent(); 12202 CXXMethodDecl *UserDeclaredOperation = nullptr; 12203 12204 // In Microsoft mode, assignment operations don't affect constructors and 12205 // vice versa. 12206 if (RD->hasUserDeclaredDestructor()) { 12207 UserDeclaredOperation = RD->getDestructor(); 12208 } else if (!isa<CXXConstructorDecl>(CopyOp) && 12209 RD->hasUserDeclaredCopyConstructor() && 12210 !S.getLangOpts().MSVCCompat) { 12211 // Find any user-declared copy constructor. 12212 for (auto *I : RD->ctors()) { 12213 if (I->isCopyConstructor()) { 12214 UserDeclaredOperation = I; 12215 break; 12216 } 12217 } 12218 assert(UserDeclaredOperation); 12219 } else if (isa<CXXConstructorDecl>(CopyOp) && 12220 RD->hasUserDeclaredCopyAssignment() && 12221 !S.getLangOpts().MSVCCompat) { 12222 // Find any user-declared move assignment operator. 12223 for (auto *I : RD->methods()) { 12224 if (I->isCopyAssignmentOperator()) { 12225 UserDeclaredOperation = I; 12226 break; 12227 } 12228 } 12229 assert(UserDeclaredOperation); 12230 } 12231 12232 if (UserDeclaredOperation) { 12233 S.Diag(UserDeclaredOperation->getLocation(), 12234 diag::warn_deprecated_copy_operation) 12235 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp) 12236 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation); 12237 } 12238 } 12239 12240 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 12241 CXXMethodDecl *CopyAssignOperator) { 12242 assert((CopyAssignOperator->isDefaulted() && 12243 CopyAssignOperator->isOverloadedOperator() && 12244 CopyAssignOperator->getOverloadedOperator() == OO_Equal && 12245 !CopyAssignOperator->doesThisDeclarationHaveABody() && 12246 !CopyAssignOperator->isDeleted()) && 12247 "DefineImplicitCopyAssignment called for wrong function"); 12248 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl()) 12249 return; 12250 12251 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent(); 12252 if (ClassDecl->isInvalidDecl()) { 12253 CopyAssignOperator->setInvalidDecl(); 12254 return; 12255 } 12256 12257 SynthesizedFunctionScope Scope(*this, CopyAssignOperator); 12258 12259 // The exception specification is needed because we are defining the 12260 // function. 12261 ResolveExceptionSpec(CurrentLocation, 12262 CopyAssignOperator->getType()->castAs<FunctionProtoType>()); 12263 12264 // Add a context note for diagnostics produced after this point. 12265 Scope.addContextNote(CurrentLocation); 12266 12267 // C++11 [class.copy]p18: 12268 // The [definition of an implicitly declared copy assignment operator] is 12269 // deprecated if the class has a user-declared copy constructor or a 12270 // user-declared destructor. 12271 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit()) 12272 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator); 12273 12274 // C++0x [class.copy]p30: 12275 // The implicitly-defined or explicitly-defaulted copy assignment operator 12276 // for a non-union class X performs memberwise copy assignment of its 12277 // subobjects. The direct base classes of X are assigned first, in the 12278 // order of their declaration in the base-specifier-list, and then the 12279 // immediate non-static data members of X are assigned, in the order in 12280 // which they were declared in the class definition. 12281 12282 // The statements that form the synthesized function body. 12283 SmallVector<Stmt*, 8> Statements; 12284 12285 // The parameter for the "other" object, which we are copying from. 12286 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0); 12287 Qualifiers OtherQuals = Other->getType().getQualifiers(); 12288 QualType OtherRefType = Other->getType(); 12289 if (const LValueReferenceType *OtherRef 12290 = OtherRefType->getAs<LValueReferenceType>()) { 12291 OtherRefType = OtherRef->getPointeeType(); 12292 OtherQuals = OtherRefType.getQualifiers(); 12293 } 12294 12295 // Our location for everything implicitly-generated. 12296 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid() 12297 ? CopyAssignOperator->getEndLoc() 12298 : CopyAssignOperator->getLocation(); 12299 12300 // Builds a DeclRefExpr for the "other" object. 12301 RefBuilder OtherRef(Other, OtherRefType); 12302 12303 // Builds the "this" pointer. 12304 ThisBuilder This; 12305 12306 // Assign base classes. 12307 bool Invalid = false; 12308 for (auto &Base : ClassDecl->bases()) { 12309 // Form the assignment: 12310 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other)); 12311 QualType BaseType = Base.getType().getUnqualifiedType(); 12312 if (!BaseType->isRecordType()) { 12313 Invalid = true; 12314 continue; 12315 } 12316 12317 CXXCastPath BasePath; 12318 BasePath.push_back(&Base); 12319 12320 // Construct the "from" expression, which is an implicit cast to the 12321 // appropriately-qualified base type. 12322 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals), 12323 VK_LValue, BasePath); 12324 12325 // Dereference "this". 12326 DerefBuilder DerefThis(This); 12327 CastBuilder To(DerefThis, 12328 Context.getQualifiedType( 12329 BaseType, CopyAssignOperator->getMethodQualifiers()), 12330 VK_LValue, BasePath); 12331 12332 // Build the copy. 12333 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType, 12334 To, From, 12335 /*CopyingBaseSubobject=*/true, 12336 /*Copying=*/true); 12337 if (Copy.isInvalid()) { 12338 CopyAssignOperator->setInvalidDecl(); 12339 return; 12340 } 12341 12342 // Success! Record the copy. 12343 Statements.push_back(Copy.getAs<Expr>()); 12344 } 12345 12346 // Assign non-static members. 12347 for (auto *Field : ClassDecl->fields()) { 12348 // FIXME: We should form some kind of AST representation for the implied 12349 // memcpy in a union copy operation. 12350 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 12351 continue; 12352 12353 if (Field->isInvalidDecl()) { 12354 Invalid = true; 12355 continue; 12356 } 12357 12358 // Check for members of reference type; we can't copy those. 12359 if (Field->getType()->isReferenceType()) { 12360 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 12361 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 12362 Diag(Field->getLocation(), diag::note_declared_at); 12363 Invalid = true; 12364 continue; 12365 } 12366 12367 // Check for members of const-qualified, non-class type. 12368 QualType BaseType = Context.getBaseElementType(Field->getType()); 12369 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 12370 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 12371 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 12372 Diag(Field->getLocation(), diag::note_declared_at); 12373 Invalid = true; 12374 continue; 12375 } 12376 12377 // Suppress assigning zero-width bitfields. 12378 if (Field->isZeroLengthBitField(Context)) 12379 continue; 12380 12381 QualType FieldType = Field->getType().getNonReferenceType(); 12382 if (FieldType->isIncompleteArrayType()) { 12383 assert(ClassDecl->hasFlexibleArrayMember() && 12384 "Incomplete array type is not valid"); 12385 continue; 12386 } 12387 12388 // Build references to the field in the object we're copying from and to. 12389 CXXScopeSpec SS; // Intentionally empty 12390 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 12391 LookupMemberName); 12392 MemberLookup.addDecl(Field); 12393 MemberLookup.resolveKind(); 12394 12395 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup); 12396 12397 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup); 12398 12399 // Build the copy of this field. 12400 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType, 12401 To, From, 12402 /*CopyingBaseSubobject=*/false, 12403 /*Copying=*/true); 12404 if (Copy.isInvalid()) { 12405 CopyAssignOperator->setInvalidDecl(); 12406 return; 12407 } 12408 12409 // Success! Record the copy. 12410 Statements.push_back(Copy.getAs<Stmt>()); 12411 } 12412 12413 if (!Invalid) { 12414 // Add a "return *this;" 12415 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 12416 12417 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 12418 if (Return.isInvalid()) 12419 Invalid = true; 12420 else 12421 Statements.push_back(Return.getAs<Stmt>()); 12422 } 12423 12424 if (Invalid) { 12425 CopyAssignOperator->setInvalidDecl(); 12426 return; 12427 } 12428 12429 StmtResult Body; 12430 { 12431 CompoundScopeRAII CompoundScope(*this); 12432 Body = ActOnCompoundStmt(Loc, Loc, Statements, 12433 /*isStmtExpr=*/false); 12434 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 12435 } 12436 CopyAssignOperator->setBody(Body.getAs<Stmt>()); 12437 CopyAssignOperator->markUsed(Context); 12438 12439 if (ASTMutationListener *L = getASTMutationListener()) { 12440 L->CompletedImplicitDefinition(CopyAssignOperator); 12441 } 12442 } 12443 12444 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) { 12445 assert(ClassDecl->needsImplicitMoveAssignment()); 12446 12447 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment); 12448 if (DSM.isAlreadyBeingDeclared()) 12449 return nullptr; 12450 12451 // Note: The following rules are largely analoguous to the move 12452 // constructor rules. 12453 12454 QualType ArgType = Context.getTypeDeclType(ClassDecl); 12455 if (Context.getLangOpts().OpenCLCPlusPlus) 12456 ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic); 12457 QualType RetType = Context.getLValueReferenceType(ArgType); 12458 ArgType = Context.getRValueReferenceType(ArgType); 12459 12460 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12461 CXXMoveAssignment, 12462 false); 12463 12464 // An implicitly-declared move assignment operator is an inline public 12465 // member of its class. 12466 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); 12467 SourceLocation ClassLoc = ClassDecl->getLocation(); 12468 DeclarationNameInfo NameInfo(Name, ClassLoc); 12469 CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create( 12470 Context, ClassDecl, ClassLoc, NameInfo, QualType(), 12471 /*TInfo=*/nullptr, /*StorageClass=*/SC_None, 12472 /*isInline=*/true, Constexpr ? CSK_constexpr : CSK_unspecified, 12473 SourceLocation()); 12474 MoveAssignment->setAccess(AS_public); 12475 MoveAssignment->setDefaulted(); 12476 MoveAssignment->setImplicit(); 12477 12478 if (getLangOpts().CUDA) { 12479 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment, 12480 MoveAssignment, 12481 /* ConstRHS */ false, 12482 /* Diagnose */ false); 12483 } 12484 12485 // Build an exception specification pointing back at this member. 12486 FunctionProtoType::ExtProtoInfo EPI = 12487 getImplicitMethodEPI(*this, MoveAssignment); 12488 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI)); 12489 12490 // Add the parameter to the operator. 12491 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment, 12492 ClassLoc, ClassLoc, 12493 /*Id=*/nullptr, ArgType, 12494 /*TInfo=*/nullptr, SC_None, 12495 nullptr); 12496 MoveAssignment->setParams(FromParam); 12497 12498 MoveAssignment->setTrivial( 12499 ClassDecl->needsOverloadResolutionForMoveAssignment() 12500 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment) 12501 : ClassDecl->hasTrivialMoveAssignment()); 12502 12503 // Note that we have added this copy-assignment operator. 12504 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared; 12505 12506 Scope *S = getScopeForContext(ClassDecl); 12507 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment); 12508 12509 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) { 12510 ClassDecl->setImplicitMoveAssignmentIsDeleted(); 12511 SetDeclDeleted(MoveAssignment, ClassLoc); 12512 } 12513 12514 if (S) 12515 PushOnScopeChains(MoveAssignment, S, false); 12516 ClassDecl->addDecl(MoveAssignment); 12517 12518 return MoveAssignment; 12519 } 12520 12521 /// Check if we're implicitly defining a move assignment operator for a class 12522 /// with virtual bases. Such a move assignment might move-assign the virtual 12523 /// base multiple times. 12524 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class, 12525 SourceLocation CurrentLocation) { 12526 assert(!Class->isDependentContext() && "should not define dependent move"); 12527 12528 // Only a virtual base could get implicitly move-assigned multiple times. 12529 // Only a non-trivial move assignment can observe this. We only want to 12530 // diagnose if we implicitly define an assignment operator that assigns 12531 // two base classes, both of which move-assign the same virtual base. 12532 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() || 12533 Class->getNumBases() < 2) 12534 return; 12535 12536 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist; 12537 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap; 12538 VBaseMap VBases; 12539 12540 for (auto &BI : Class->bases()) { 12541 Worklist.push_back(&BI); 12542 while (!Worklist.empty()) { 12543 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val(); 12544 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl(); 12545 12546 // If the base has no non-trivial move assignment operators, 12547 // we don't care about moves from it. 12548 if (!Base->hasNonTrivialMoveAssignment()) 12549 continue; 12550 12551 // If there's nothing virtual here, skip it. 12552 if (!BaseSpec->isVirtual() && !Base->getNumVBases()) 12553 continue; 12554 12555 // If we're not actually going to call a move assignment for this base, 12556 // or the selected move assignment is trivial, skip it. 12557 Sema::SpecialMemberOverloadResult SMOR = 12558 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment, 12559 /*ConstArg*/false, /*VolatileArg*/false, 12560 /*RValueThis*/true, /*ConstThis*/false, 12561 /*VolatileThis*/false); 12562 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() || 12563 !SMOR.getMethod()->isMoveAssignmentOperator()) 12564 continue; 12565 12566 if (BaseSpec->isVirtual()) { 12567 // We're going to move-assign this virtual base, and its move 12568 // assignment operator is not trivial. If this can happen for 12569 // multiple distinct direct bases of Class, diagnose it. (If it 12570 // only happens in one base, we'll diagnose it when synthesizing 12571 // that base class's move assignment operator.) 12572 CXXBaseSpecifier *&Existing = 12573 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI)) 12574 .first->second; 12575 if (Existing && Existing != &BI) { 12576 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times) 12577 << Class << Base; 12578 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here) 12579 << (Base->getCanonicalDecl() == 12580 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 12581 << Base << Existing->getType() << Existing->getSourceRange(); 12582 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here) 12583 << (Base->getCanonicalDecl() == 12584 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl()) 12585 << Base << BI.getType() << BaseSpec->getSourceRange(); 12586 12587 // Only diagnose each vbase once. 12588 Existing = nullptr; 12589 } 12590 } else { 12591 // Only walk over bases that have defaulted move assignment operators. 12592 // We assume that any user-provided move assignment operator handles 12593 // the multiple-moves-of-vbase case itself somehow. 12594 if (!SMOR.getMethod()->isDefaulted()) 12595 continue; 12596 12597 // We're going to move the base classes of Base. Add them to the list. 12598 for (auto &BI : Base->bases()) 12599 Worklist.push_back(&BI); 12600 } 12601 } 12602 } 12603 } 12604 12605 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 12606 CXXMethodDecl *MoveAssignOperator) { 12607 assert((MoveAssignOperator->isDefaulted() && 12608 MoveAssignOperator->isOverloadedOperator() && 12609 MoveAssignOperator->getOverloadedOperator() == OO_Equal && 12610 !MoveAssignOperator->doesThisDeclarationHaveABody() && 12611 !MoveAssignOperator->isDeleted()) && 12612 "DefineImplicitMoveAssignment called for wrong function"); 12613 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl()) 12614 return; 12615 12616 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent(); 12617 if (ClassDecl->isInvalidDecl()) { 12618 MoveAssignOperator->setInvalidDecl(); 12619 return; 12620 } 12621 12622 // C++0x [class.copy]p28: 12623 // The implicitly-defined or move assignment operator for a non-union class 12624 // X performs memberwise move assignment of its subobjects. The direct base 12625 // classes of X are assigned first, in the order of their declaration in the 12626 // base-specifier-list, and then the immediate non-static data members of X 12627 // are assigned, in the order in which they were declared in the class 12628 // definition. 12629 12630 // Issue a warning if our implicit move assignment operator will move 12631 // from a virtual base more than once. 12632 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation); 12633 12634 SynthesizedFunctionScope Scope(*this, MoveAssignOperator); 12635 12636 // The exception specification is needed because we are defining the 12637 // function. 12638 ResolveExceptionSpec(CurrentLocation, 12639 MoveAssignOperator->getType()->castAs<FunctionProtoType>()); 12640 12641 // Add a context note for diagnostics produced after this point. 12642 Scope.addContextNote(CurrentLocation); 12643 12644 // The statements that form the synthesized function body. 12645 SmallVector<Stmt*, 8> Statements; 12646 12647 // The parameter for the "other" object, which we are move from. 12648 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0); 12649 QualType OtherRefType = Other->getType()-> 12650 getAs<RValueReferenceType>()->getPointeeType(); 12651 12652 // Our location for everything implicitly-generated. 12653 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid() 12654 ? MoveAssignOperator->getEndLoc() 12655 : MoveAssignOperator->getLocation(); 12656 12657 // Builds a reference to the "other" object. 12658 RefBuilder OtherRef(Other, OtherRefType); 12659 // Cast to rvalue. 12660 MoveCastBuilder MoveOther(OtherRef); 12661 12662 // Builds the "this" pointer. 12663 ThisBuilder This; 12664 12665 // Assign base classes. 12666 bool Invalid = false; 12667 for (auto &Base : ClassDecl->bases()) { 12668 // C++11 [class.copy]p28: 12669 // It is unspecified whether subobjects representing virtual base classes 12670 // are assigned more than once by the implicitly-defined copy assignment 12671 // operator. 12672 // FIXME: Do not assign to a vbase that will be assigned by some other base 12673 // class. For a move-assignment, this can result in the vbase being moved 12674 // multiple times. 12675 12676 // Form the assignment: 12677 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other)); 12678 QualType BaseType = Base.getType().getUnqualifiedType(); 12679 if (!BaseType->isRecordType()) { 12680 Invalid = true; 12681 continue; 12682 } 12683 12684 CXXCastPath BasePath; 12685 BasePath.push_back(&Base); 12686 12687 // Construct the "from" expression, which is an implicit cast to the 12688 // appropriately-qualified base type. 12689 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath); 12690 12691 // Dereference "this". 12692 DerefBuilder DerefThis(This); 12693 12694 // Implicitly cast "this" to the appropriately-qualified base type. 12695 CastBuilder To(DerefThis, 12696 Context.getQualifiedType( 12697 BaseType, MoveAssignOperator->getMethodQualifiers()), 12698 VK_LValue, BasePath); 12699 12700 // Build the move. 12701 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType, 12702 To, From, 12703 /*CopyingBaseSubobject=*/true, 12704 /*Copying=*/false); 12705 if (Move.isInvalid()) { 12706 MoveAssignOperator->setInvalidDecl(); 12707 return; 12708 } 12709 12710 // Success! Record the move. 12711 Statements.push_back(Move.getAs<Expr>()); 12712 } 12713 12714 // Assign non-static members. 12715 for (auto *Field : ClassDecl->fields()) { 12716 // FIXME: We should form some kind of AST representation for the implied 12717 // memcpy in a union copy operation. 12718 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion()) 12719 continue; 12720 12721 if (Field->isInvalidDecl()) { 12722 Invalid = true; 12723 continue; 12724 } 12725 12726 // Check for members of reference type; we can't move those. 12727 if (Field->getType()->isReferenceType()) { 12728 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 12729 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName(); 12730 Diag(Field->getLocation(), diag::note_declared_at); 12731 Invalid = true; 12732 continue; 12733 } 12734 12735 // Check for members of const-qualified, non-class type. 12736 QualType BaseType = Context.getBaseElementType(Field->getType()); 12737 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) { 12738 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign) 12739 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName(); 12740 Diag(Field->getLocation(), diag::note_declared_at); 12741 Invalid = true; 12742 continue; 12743 } 12744 12745 // Suppress assigning zero-width bitfields. 12746 if (Field->isZeroLengthBitField(Context)) 12747 continue; 12748 12749 QualType FieldType = Field->getType().getNonReferenceType(); 12750 if (FieldType->isIncompleteArrayType()) { 12751 assert(ClassDecl->hasFlexibleArrayMember() && 12752 "Incomplete array type is not valid"); 12753 continue; 12754 } 12755 12756 // Build references to the field in the object we're copying from and to. 12757 LookupResult MemberLookup(*this, Field->getDeclName(), Loc, 12758 LookupMemberName); 12759 MemberLookup.addDecl(Field); 12760 MemberLookup.resolveKind(); 12761 MemberBuilder From(MoveOther, OtherRefType, 12762 /*IsArrow=*/false, MemberLookup); 12763 MemberBuilder To(This, getCurrentThisType(), 12764 /*IsArrow=*/true, MemberLookup); 12765 12766 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue 12767 "Member reference with rvalue base must be rvalue except for reference " 12768 "members, which aren't allowed for move assignment."); 12769 12770 // Build the move of this field. 12771 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType, 12772 To, From, 12773 /*CopyingBaseSubobject=*/false, 12774 /*Copying=*/false); 12775 if (Move.isInvalid()) { 12776 MoveAssignOperator->setInvalidDecl(); 12777 return; 12778 } 12779 12780 // Success! Record the copy. 12781 Statements.push_back(Move.getAs<Stmt>()); 12782 } 12783 12784 if (!Invalid) { 12785 // Add a "return *this;" 12786 ExprResult ThisObj = 12787 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc)); 12788 12789 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get()); 12790 if (Return.isInvalid()) 12791 Invalid = true; 12792 else 12793 Statements.push_back(Return.getAs<Stmt>()); 12794 } 12795 12796 if (Invalid) { 12797 MoveAssignOperator->setInvalidDecl(); 12798 return; 12799 } 12800 12801 StmtResult Body; 12802 { 12803 CompoundScopeRAII CompoundScope(*this); 12804 Body = ActOnCompoundStmt(Loc, Loc, Statements, 12805 /*isStmtExpr=*/false); 12806 assert(!Body.isInvalid() && "Compound statement creation cannot fail"); 12807 } 12808 MoveAssignOperator->setBody(Body.getAs<Stmt>()); 12809 MoveAssignOperator->markUsed(Context); 12810 12811 if (ASTMutationListener *L = getASTMutationListener()) { 12812 L->CompletedImplicitDefinition(MoveAssignOperator); 12813 } 12814 } 12815 12816 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor( 12817 CXXRecordDecl *ClassDecl) { 12818 // C++ [class.copy]p4: 12819 // If the class definition does not explicitly declare a copy 12820 // constructor, one is declared implicitly. 12821 assert(ClassDecl->needsImplicitCopyConstructor()); 12822 12823 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor); 12824 if (DSM.isAlreadyBeingDeclared()) 12825 return nullptr; 12826 12827 QualType ClassType = Context.getTypeDeclType(ClassDecl); 12828 QualType ArgType = ClassType; 12829 bool Const = ClassDecl->implicitCopyConstructorHasConstParam(); 12830 if (Const) 12831 ArgType = ArgType.withConst(); 12832 12833 if (Context.getLangOpts().OpenCLCPlusPlus) 12834 ArgType = Context.getAddrSpaceQualType(ArgType, LangAS::opencl_generic); 12835 12836 ArgType = Context.getLValueReferenceType(ArgType); 12837 12838 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12839 CXXCopyConstructor, 12840 Const); 12841 12842 DeclarationName Name 12843 = Context.DeclarationNames.getCXXConstructorName( 12844 Context.getCanonicalType(ClassType)); 12845 SourceLocation ClassLoc = ClassDecl->getLocation(); 12846 DeclarationNameInfo NameInfo(Name, ClassLoc); 12847 12848 // An implicitly-declared copy constructor is an inline public 12849 // member of its class. 12850 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create( 12851 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 12852 ExplicitSpecifier(), 12853 /*isInline=*/true, 12854 /*isImplicitlyDeclared=*/true, 12855 Constexpr ? CSK_constexpr : CSK_unspecified); 12856 CopyConstructor->setAccess(AS_public); 12857 CopyConstructor->setDefaulted(); 12858 12859 if (getLangOpts().CUDA) { 12860 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor, 12861 CopyConstructor, 12862 /* ConstRHS */ Const, 12863 /* Diagnose */ false); 12864 } 12865 12866 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType); 12867 12868 // Add the parameter to the constructor. 12869 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor, 12870 ClassLoc, ClassLoc, 12871 /*IdentifierInfo=*/nullptr, 12872 ArgType, /*TInfo=*/nullptr, 12873 SC_None, nullptr); 12874 CopyConstructor->setParams(FromParam); 12875 12876 CopyConstructor->setTrivial( 12877 ClassDecl->needsOverloadResolutionForCopyConstructor() 12878 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor) 12879 : ClassDecl->hasTrivialCopyConstructor()); 12880 12881 CopyConstructor->setTrivialForCall( 12882 ClassDecl->hasAttr<TrivialABIAttr>() || 12883 (ClassDecl->needsOverloadResolutionForCopyConstructor() 12884 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor, 12885 TAH_ConsiderTrivialABI) 12886 : ClassDecl->hasTrivialCopyConstructorForCall())); 12887 12888 // Note that we have declared this constructor. 12889 ++getASTContext().NumImplicitCopyConstructorsDeclared; 12890 12891 Scope *S = getScopeForContext(ClassDecl); 12892 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor); 12893 12894 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) { 12895 ClassDecl->setImplicitCopyConstructorIsDeleted(); 12896 SetDeclDeleted(CopyConstructor, ClassLoc); 12897 } 12898 12899 if (S) 12900 PushOnScopeChains(CopyConstructor, S, false); 12901 ClassDecl->addDecl(CopyConstructor); 12902 12903 return CopyConstructor; 12904 } 12905 12906 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 12907 CXXConstructorDecl *CopyConstructor) { 12908 assert((CopyConstructor->isDefaulted() && 12909 CopyConstructor->isCopyConstructor() && 12910 !CopyConstructor->doesThisDeclarationHaveABody() && 12911 !CopyConstructor->isDeleted()) && 12912 "DefineImplicitCopyConstructor - call it for implicit copy ctor"); 12913 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl()) 12914 return; 12915 12916 CXXRecordDecl *ClassDecl = CopyConstructor->getParent(); 12917 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor"); 12918 12919 SynthesizedFunctionScope Scope(*this, CopyConstructor); 12920 12921 // The exception specification is needed because we are defining the 12922 // function. 12923 ResolveExceptionSpec(CurrentLocation, 12924 CopyConstructor->getType()->castAs<FunctionProtoType>()); 12925 MarkVTableUsed(CurrentLocation, ClassDecl); 12926 12927 // Add a context note for diagnostics produced after this point. 12928 Scope.addContextNote(CurrentLocation); 12929 12930 // C++11 [class.copy]p7: 12931 // The [definition of an implicitly declared copy constructor] is 12932 // deprecated if the class has a user-declared copy assignment operator 12933 // or a user-declared destructor. 12934 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit()) 12935 diagnoseDeprecatedCopyOperation(*this, CopyConstructor); 12936 12937 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) { 12938 CopyConstructor->setInvalidDecl(); 12939 } else { 12940 SourceLocation Loc = CopyConstructor->getEndLoc().isValid() 12941 ? CopyConstructor->getEndLoc() 12942 : CopyConstructor->getLocation(); 12943 Sema::CompoundScopeRAII CompoundScope(*this); 12944 CopyConstructor->setBody( 12945 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>()); 12946 CopyConstructor->markUsed(Context); 12947 } 12948 12949 if (ASTMutationListener *L = getASTMutationListener()) { 12950 L->CompletedImplicitDefinition(CopyConstructor); 12951 } 12952 } 12953 12954 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor( 12955 CXXRecordDecl *ClassDecl) { 12956 assert(ClassDecl->needsImplicitMoveConstructor()); 12957 12958 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor); 12959 if (DSM.isAlreadyBeingDeclared()) 12960 return nullptr; 12961 12962 QualType ClassType = Context.getTypeDeclType(ClassDecl); 12963 12964 QualType ArgType = ClassType; 12965 if (Context.getLangOpts().OpenCLCPlusPlus) 12966 ArgType = Context.getAddrSpaceQualType(ClassType, LangAS::opencl_generic); 12967 ArgType = Context.getRValueReferenceType(ArgType); 12968 12969 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl, 12970 CXXMoveConstructor, 12971 false); 12972 12973 DeclarationName Name 12974 = Context.DeclarationNames.getCXXConstructorName( 12975 Context.getCanonicalType(ClassType)); 12976 SourceLocation ClassLoc = ClassDecl->getLocation(); 12977 DeclarationNameInfo NameInfo(Name, ClassLoc); 12978 12979 // C++11 [class.copy]p11: 12980 // An implicitly-declared copy/move constructor is an inline public 12981 // member of its class. 12982 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create( 12983 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr, 12984 ExplicitSpecifier(), 12985 /*isInline=*/true, 12986 /*isImplicitlyDeclared=*/true, 12987 Constexpr ? CSK_constexpr : CSK_unspecified); 12988 MoveConstructor->setAccess(AS_public); 12989 MoveConstructor->setDefaulted(); 12990 12991 if (getLangOpts().CUDA) { 12992 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor, 12993 MoveConstructor, 12994 /* ConstRHS */ false, 12995 /* Diagnose */ false); 12996 } 12997 12998 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType); 12999 13000 // Add the parameter to the constructor. 13001 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor, 13002 ClassLoc, ClassLoc, 13003 /*IdentifierInfo=*/nullptr, 13004 ArgType, /*TInfo=*/nullptr, 13005 SC_None, nullptr); 13006 MoveConstructor->setParams(FromParam); 13007 13008 MoveConstructor->setTrivial( 13009 ClassDecl->needsOverloadResolutionForMoveConstructor() 13010 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor) 13011 : ClassDecl->hasTrivialMoveConstructor()); 13012 13013 MoveConstructor->setTrivialForCall( 13014 ClassDecl->hasAttr<TrivialABIAttr>() || 13015 (ClassDecl->needsOverloadResolutionForMoveConstructor() 13016 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor, 13017 TAH_ConsiderTrivialABI) 13018 : ClassDecl->hasTrivialMoveConstructorForCall())); 13019 13020 // Note that we have declared this constructor. 13021 ++getASTContext().NumImplicitMoveConstructorsDeclared; 13022 13023 Scope *S = getScopeForContext(ClassDecl); 13024 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor); 13025 13026 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) { 13027 ClassDecl->setImplicitMoveConstructorIsDeleted(); 13028 SetDeclDeleted(MoveConstructor, ClassLoc); 13029 } 13030 13031 if (S) 13032 PushOnScopeChains(MoveConstructor, S, false); 13033 ClassDecl->addDecl(MoveConstructor); 13034 13035 return MoveConstructor; 13036 } 13037 13038 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 13039 CXXConstructorDecl *MoveConstructor) { 13040 assert((MoveConstructor->isDefaulted() && 13041 MoveConstructor->isMoveConstructor() && 13042 !MoveConstructor->doesThisDeclarationHaveABody() && 13043 !MoveConstructor->isDeleted()) && 13044 "DefineImplicitMoveConstructor - call it for implicit move ctor"); 13045 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl()) 13046 return; 13047 13048 CXXRecordDecl *ClassDecl = MoveConstructor->getParent(); 13049 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor"); 13050 13051 SynthesizedFunctionScope Scope(*this, MoveConstructor); 13052 13053 // The exception specification is needed because we are defining the 13054 // function. 13055 ResolveExceptionSpec(CurrentLocation, 13056 MoveConstructor->getType()->castAs<FunctionProtoType>()); 13057 MarkVTableUsed(CurrentLocation, ClassDecl); 13058 13059 // Add a context note for diagnostics produced after this point. 13060 Scope.addContextNote(CurrentLocation); 13061 13062 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) { 13063 MoveConstructor->setInvalidDecl(); 13064 } else { 13065 SourceLocation Loc = MoveConstructor->getEndLoc().isValid() 13066 ? MoveConstructor->getEndLoc() 13067 : MoveConstructor->getLocation(); 13068 Sema::CompoundScopeRAII CompoundScope(*this); 13069 MoveConstructor->setBody(ActOnCompoundStmt( 13070 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>()); 13071 MoveConstructor->markUsed(Context); 13072 } 13073 13074 if (ASTMutationListener *L = getASTMutationListener()) { 13075 L->CompletedImplicitDefinition(MoveConstructor); 13076 } 13077 } 13078 13079 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) { 13080 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD); 13081 } 13082 13083 void Sema::DefineImplicitLambdaToFunctionPointerConversion( 13084 SourceLocation CurrentLocation, 13085 CXXConversionDecl *Conv) { 13086 SynthesizedFunctionScope Scope(*this, Conv); 13087 assert(!Conv->getReturnType()->isUndeducedType()); 13088 13089 CXXRecordDecl *Lambda = Conv->getParent(); 13090 FunctionDecl *CallOp = Lambda->getLambdaCallOperator(); 13091 FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(); 13092 13093 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) { 13094 CallOp = InstantiateFunctionDeclaration( 13095 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 13096 if (!CallOp) 13097 return; 13098 13099 Invoker = InstantiateFunctionDeclaration( 13100 Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation); 13101 if (!Invoker) 13102 return; 13103 } 13104 13105 if (CallOp->isInvalidDecl()) 13106 return; 13107 13108 // Mark the call operator referenced (and add to pending instantiations 13109 // if necessary). 13110 // For both the conversion and static-invoker template specializations 13111 // we construct their body's in this function, so no need to add them 13112 // to the PendingInstantiations. 13113 MarkFunctionReferenced(CurrentLocation, CallOp); 13114 13115 // Fill in the __invoke function with a dummy implementation. IR generation 13116 // will fill in the actual details. Update its type in case it contained 13117 // an 'auto'. 13118 Invoker->markUsed(Context); 13119 Invoker->setReferenced(); 13120 Invoker->setType(Conv->getReturnType()->getPointeeType()); 13121 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation())); 13122 13123 // Construct the body of the conversion function { return __invoke; }. 13124 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(), 13125 VK_LValue, Conv->getLocation()); 13126 assert(FunctionRef && "Can't refer to __invoke function?"); 13127 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get(); 13128 Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(), 13129 Conv->getLocation())); 13130 Conv->markUsed(Context); 13131 Conv->setReferenced(); 13132 13133 if (ASTMutationListener *L = getASTMutationListener()) { 13134 L->CompletedImplicitDefinition(Conv); 13135 L->CompletedImplicitDefinition(Invoker); 13136 } 13137 } 13138 13139 13140 13141 void Sema::DefineImplicitLambdaToBlockPointerConversion( 13142 SourceLocation CurrentLocation, 13143 CXXConversionDecl *Conv) 13144 { 13145 assert(!Conv->getParent()->isGenericLambda()); 13146 13147 SynthesizedFunctionScope Scope(*this, Conv); 13148 13149 // Copy-initialize the lambda object as needed to capture it. 13150 Expr *This = ActOnCXXThis(CurrentLocation).get(); 13151 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get(); 13152 13153 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation, 13154 Conv->getLocation(), 13155 Conv, DerefThis); 13156 13157 // If we're not under ARC, make sure we still get the _Block_copy/autorelease 13158 // behavior. Note that only the general conversion function does this 13159 // (since it's unusable otherwise); in the case where we inline the 13160 // block literal, it has block literal lifetime semantics. 13161 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount) 13162 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(), 13163 CK_CopyAndAutoreleaseBlockObject, 13164 BuildBlock.get(), nullptr, VK_RValue); 13165 13166 if (BuildBlock.isInvalid()) { 13167 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 13168 Conv->setInvalidDecl(); 13169 return; 13170 } 13171 13172 // Create the return statement that returns the block from the conversion 13173 // function. 13174 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get()); 13175 if (Return.isInvalid()) { 13176 Diag(CurrentLocation, diag::note_lambda_to_block_conv); 13177 Conv->setInvalidDecl(); 13178 return; 13179 } 13180 13181 // Set the body of the conversion function. 13182 Stmt *ReturnS = Return.get(); 13183 Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(), 13184 Conv->getLocation())); 13185 Conv->markUsed(Context); 13186 13187 // We're done; notify the mutation listener, if any. 13188 if (ASTMutationListener *L = getASTMutationListener()) { 13189 L->CompletedImplicitDefinition(Conv); 13190 } 13191 } 13192 13193 /// Determine whether the given list arguments contains exactly one 13194 /// "real" (non-default) argument. 13195 static bool hasOneRealArgument(MultiExprArg Args) { 13196 switch (Args.size()) { 13197 case 0: 13198 return false; 13199 13200 default: 13201 if (!Args[1]->isDefaultArgument()) 13202 return false; 13203 13204 LLVM_FALLTHROUGH; 13205 case 1: 13206 return !Args[0]->isDefaultArgument(); 13207 } 13208 13209 return false; 13210 } 13211 13212 ExprResult 13213 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 13214 NamedDecl *FoundDecl, 13215 CXXConstructorDecl *Constructor, 13216 MultiExprArg ExprArgs, 13217 bool HadMultipleCandidates, 13218 bool IsListInitialization, 13219 bool IsStdInitListInitialization, 13220 bool RequiresZeroInit, 13221 unsigned ConstructKind, 13222 SourceRange ParenRange) { 13223 bool Elidable = false; 13224 13225 // C++0x [class.copy]p34: 13226 // When certain criteria are met, an implementation is allowed to 13227 // omit the copy/move construction of a class object, even if the 13228 // copy/move constructor and/or destructor for the object have 13229 // side effects. [...] 13230 // - when a temporary class object that has not been bound to a 13231 // reference (12.2) would be copied/moved to a class object 13232 // with the same cv-unqualified type, the copy/move operation 13233 // can be omitted by constructing the temporary object 13234 // directly into the target of the omitted copy/move 13235 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor && 13236 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) { 13237 Expr *SubExpr = ExprArgs[0]; 13238 Elidable = SubExpr->isTemporaryObject( 13239 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext())); 13240 } 13241 13242 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, 13243 FoundDecl, Constructor, 13244 Elidable, ExprArgs, HadMultipleCandidates, 13245 IsListInitialization, 13246 IsStdInitListInitialization, RequiresZeroInit, 13247 ConstructKind, ParenRange); 13248 } 13249 13250 ExprResult 13251 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 13252 NamedDecl *FoundDecl, 13253 CXXConstructorDecl *Constructor, 13254 bool Elidable, 13255 MultiExprArg ExprArgs, 13256 bool HadMultipleCandidates, 13257 bool IsListInitialization, 13258 bool IsStdInitListInitialization, 13259 bool RequiresZeroInit, 13260 unsigned ConstructKind, 13261 SourceRange ParenRange) { 13262 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) { 13263 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow); 13264 if (DiagnoseUseOfDecl(Constructor, ConstructLoc)) 13265 return ExprError(); 13266 } 13267 13268 return BuildCXXConstructExpr( 13269 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs, 13270 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization, 13271 RequiresZeroInit, ConstructKind, ParenRange); 13272 } 13273 13274 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 13275 /// including handling of its default argument expressions. 13276 ExprResult 13277 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 13278 CXXConstructorDecl *Constructor, 13279 bool Elidable, 13280 MultiExprArg ExprArgs, 13281 bool HadMultipleCandidates, 13282 bool IsListInitialization, 13283 bool IsStdInitListInitialization, 13284 bool RequiresZeroInit, 13285 unsigned ConstructKind, 13286 SourceRange ParenRange) { 13287 assert(declaresSameEntity( 13288 Constructor->getParent(), 13289 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) && 13290 "given constructor for wrong type"); 13291 MarkFunctionReferenced(ConstructLoc, Constructor); 13292 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor)) 13293 return ExprError(); 13294 13295 return CXXConstructExpr::Create( 13296 Context, DeclInitType, ConstructLoc, Constructor, Elidable, 13297 ExprArgs, HadMultipleCandidates, IsListInitialization, 13298 IsStdInitListInitialization, RequiresZeroInit, 13299 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind), 13300 ParenRange); 13301 } 13302 13303 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) { 13304 assert(Field->hasInClassInitializer()); 13305 13306 // If we already have the in-class initializer nothing needs to be done. 13307 if (Field->getInClassInitializer()) 13308 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext); 13309 13310 // If we might have already tried and failed to instantiate, don't try again. 13311 if (Field->isInvalidDecl()) 13312 return ExprError(); 13313 13314 // Maybe we haven't instantiated the in-class initializer. Go check the 13315 // pattern FieldDecl to see if it has one. 13316 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent()); 13317 13318 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) { 13319 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern(); 13320 DeclContext::lookup_result Lookup = 13321 ClassPattern->lookup(Field->getDeclName()); 13322 13323 // Lookup can return at most two results: the pattern for the field, or the 13324 // injected class name of the parent record. No other member can have the 13325 // same name as the field. 13326 // In modules mode, lookup can return multiple results (coming from 13327 // different modules). 13328 assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) && 13329 "more than two lookup results for field name"); 13330 FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]); 13331 if (!Pattern) { 13332 assert(isa<CXXRecordDecl>(Lookup[0]) && 13333 "cannot have other non-field member with same name"); 13334 for (auto L : Lookup) 13335 if (isa<FieldDecl>(L)) { 13336 Pattern = cast<FieldDecl>(L); 13337 break; 13338 } 13339 assert(Pattern && "We must have set the Pattern!"); 13340 } 13341 13342 if (!Pattern->hasInClassInitializer() || 13343 InstantiateInClassInitializer(Loc, Field, Pattern, 13344 getTemplateInstantiationArgs(Field))) { 13345 // Don't diagnose this again. 13346 Field->setInvalidDecl(); 13347 return ExprError(); 13348 } 13349 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext); 13350 } 13351 13352 // DR1351: 13353 // If the brace-or-equal-initializer of a non-static data member 13354 // invokes a defaulted default constructor of its class or of an 13355 // enclosing class in a potentially evaluated subexpression, the 13356 // program is ill-formed. 13357 // 13358 // This resolution is unworkable: the exception specification of the 13359 // default constructor can be needed in an unevaluated context, in 13360 // particular, in the operand of a noexcept-expression, and we can be 13361 // unable to compute an exception specification for an enclosed class. 13362 // 13363 // Any attempt to resolve the exception specification of a defaulted default 13364 // constructor before the initializer is lexically complete will ultimately 13365 // come here at which point we can diagnose it. 13366 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext(); 13367 Diag(Loc, diag::err_in_class_initializer_not_yet_parsed) 13368 << OutermostClass << Field; 13369 Diag(Field->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed); 13370 // Recover by marking the field invalid, unless we're in a SFINAE context. 13371 if (!isSFINAEContext()) 13372 Field->setInvalidDecl(); 13373 return ExprError(); 13374 } 13375 13376 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) { 13377 if (VD->isInvalidDecl()) return; 13378 13379 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl()); 13380 if (ClassDecl->isInvalidDecl()) return; 13381 if (ClassDecl->hasIrrelevantDestructor()) return; 13382 if (ClassDecl->isDependentContext()) return; 13383 13384 if (VD->isNoDestroy(getASTContext())) 13385 return; 13386 13387 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 13388 13389 // If this is an array, we'll require the destructor during initialization, so 13390 // we can skip over this. We still want to emit exit-time destructor warnings 13391 // though. 13392 if (!VD->getType()->isArrayType()) { 13393 MarkFunctionReferenced(VD->getLocation(), Destructor); 13394 CheckDestructorAccess(VD->getLocation(), Destructor, 13395 PDiag(diag::err_access_dtor_var) 13396 << VD->getDeclName() << VD->getType()); 13397 DiagnoseUseOfDecl(Destructor, VD->getLocation()); 13398 } 13399 13400 if (Destructor->isTrivial()) return; 13401 13402 // If the destructor is constexpr, check whether the variable has constant 13403 // destruction now. 13404 if (Destructor->isConstexpr() && VD->getInit() && 13405 !VD->getInit()->isValueDependent() && VD->evaluateValue()) { 13406 SmallVector<PartialDiagnosticAt, 8> Notes; 13407 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr()) { 13408 Diag(VD->getLocation(), 13409 diag::err_constexpr_var_requires_const_destruction) << VD; 13410 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 13411 Diag(Notes[I].first, Notes[I].second); 13412 } 13413 } 13414 13415 if (!VD->hasGlobalStorage()) return; 13416 13417 // Emit warning for non-trivial dtor in global scope (a real global, 13418 // class-static, function-static). 13419 Diag(VD->getLocation(), diag::warn_exit_time_destructor); 13420 13421 // TODO: this should be re-enabled for static locals by !CXAAtExit 13422 if (!VD->isStaticLocal()) 13423 Diag(VD->getLocation(), diag::warn_global_destructor); 13424 } 13425 13426 /// Given a constructor and the set of arguments provided for the 13427 /// constructor, convert the arguments and add any required default arguments 13428 /// to form a proper call to this constructor. 13429 /// 13430 /// \returns true if an error occurred, false otherwise. 13431 bool 13432 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor, 13433 MultiExprArg ArgsPtr, 13434 SourceLocation Loc, 13435 SmallVectorImpl<Expr*> &ConvertedArgs, 13436 bool AllowExplicit, 13437 bool IsListInitialization) { 13438 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall. 13439 unsigned NumArgs = ArgsPtr.size(); 13440 Expr **Args = ArgsPtr.data(); 13441 13442 const FunctionProtoType *Proto 13443 = Constructor->getType()->getAs<FunctionProtoType>(); 13444 assert(Proto && "Constructor without a prototype?"); 13445 unsigned NumParams = Proto->getNumParams(); 13446 13447 // If too few arguments are available, we'll fill in the rest with defaults. 13448 if (NumArgs < NumParams) 13449 ConvertedArgs.reserve(NumParams); 13450 else 13451 ConvertedArgs.reserve(NumArgs); 13452 13453 VariadicCallType CallType = 13454 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 13455 SmallVector<Expr *, 8> AllArgs; 13456 bool Invalid = GatherArgumentsForCall(Loc, Constructor, 13457 Proto, 0, 13458 llvm::makeArrayRef(Args, NumArgs), 13459 AllArgs, 13460 CallType, AllowExplicit, 13461 IsListInitialization); 13462 ConvertedArgs.append(AllArgs.begin(), AllArgs.end()); 13463 13464 DiagnoseSentinelCalls(Constructor, Loc, AllArgs); 13465 13466 CheckConstructorCall(Constructor, 13467 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()), 13468 Proto, Loc); 13469 13470 return Invalid; 13471 } 13472 13473 static inline bool 13474 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef, 13475 const FunctionDecl *FnDecl) { 13476 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext(); 13477 if (isa<NamespaceDecl>(DC)) { 13478 return SemaRef.Diag(FnDecl->getLocation(), 13479 diag::err_operator_new_delete_declared_in_namespace) 13480 << FnDecl->getDeclName(); 13481 } 13482 13483 if (isa<TranslationUnitDecl>(DC) && 13484 FnDecl->getStorageClass() == SC_Static) { 13485 return SemaRef.Diag(FnDecl->getLocation(), 13486 diag::err_operator_new_delete_declared_static) 13487 << FnDecl->getDeclName(); 13488 } 13489 13490 return false; 13491 } 13492 13493 static QualType 13494 RemoveAddressSpaceFromPtr(Sema &SemaRef, const PointerType *PtrTy) { 13495 QualType QTy = PtrTy->getPointeeType(); 13496 QTy = SemaRef.Context.removeAddrSpaceQualType(QTy); 13497 return SemaRef.Context.getPointerType(QTy); 13498 } 13499 13500 static inline bool 13501 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl, 13502 CanQualType ExpectedResultType, 13503 CanQualType ExpectedFirstParamType, 13504 unsigned DependentParamTypeDiag, 13505 unsigned InvalidParamTypeDiag) { 13506 QualType ResultType = 13507 FnDecl->getType()->getAs<FunctionType>()->getReturnType(); 13508 13509 // Check that the result type is not dependent. 13510 if (ResultType->isDependentType()) 13511 return SemaRef.Diag(FnDecl->getLocation(), 13512 diag::err_operator_new_delete_dependent_result_type) 13513 << FnDecl->getDeclName() << ExpectedResultType; 13514 13515 // The operator is valid on any address space for OpenCL. 13516 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 13517 if (auto *PtrTy = ResultType->getAs<PointerType>()) { 13518 ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 13519 } 13520 } 13521 13522 // Check that the result type is what we expect. 13523 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) 13524 return SemaRef.Diag(FnDecl->getLocation(), 13525 diag::err_operator_new_delete_invalid_result_type) 13526 << FnDecl->getDeclName() << ExpectedResultType; 13527 13528 // A function template must have at least 2 parameters. 13529 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2) 13530 return SemaRef.Diag(FnDecl->getLocation(), 13531 diag::err_operator_new_delete_template_too_few_parameters) 13532 << FnDecl->getDeclName(); 13533 13534 // The function decl must have at least 1 parameter. 13535 if (FnDecl->getNumParams() == 0) 13536 return SemaRef.Diag(FnDecl->getLocation(), 13537 diag::err_operator_new_delete_too_few_parameters) 13538 << FnDecl->getDeclName(); 13539 13540 // Check the first parameter type is not dependent. 13541 QualType FirstParamType = FnDecl->getParamDecl(0)->getType(); 13542 if (FirstParamType->isDependentType()) 13543 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag) 13544 << FnDecl->getDeclName() << ExpectedFirstParamType; 13545 13546 // Check that the first parameter type is what we expect. 13547 if (SemaRef.getLangOpts().OpenCLCPlusPlus) { 13548 // The operator is valid on any address space for OpenCL. 13549 if (auto *PtrTy = 13550 FnDecl->getParamDecl(0)->getType()->getAs<PointerType>()) { 13551 FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy); 13552 } 13553 } 13554 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() != 13555 ExpectedFirstParamType) 13556 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag) 13557 << FnDecl->getDeclName() << ExpectedFirstParamType; 13558 13559 return false; 13560 } 13561 13562 static bool 13563 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) { 13564 // C++ [basic.stc.dynamic.allocation]p1: 13565 // A program is ill-formed if an allocation function is declared in a 13566 // namespace scope other than global scope or declared static in global 13567 // scope. 13568 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 13569 return true; 13570 13571 CanQualType SizeTy = 13572 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType()); 13573 13574 // C++ [basic.stc.dynamic.allocation]p1: 13575 // The return type shall be void*. The first parameter shall have type 13576 // std::size_t. 13577 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy, 13578 SizeTy, 13579 diag::err_operator_new_dependent_param_type, 13580 diag::err_operator_new_param_type)) 13581 return true; 13582 13583 // C++ [basic.stc.dynamic.allocation]p1: 13584 // The first parameter shall not have an associated default argument. 13585 if (FnDecl->getParamDecl(0)->hasDefaultArg()) 13586 return SemaRef.Diag(FnDecl->getLocation(), 13587 diag::err_operator_new_default_arg) 13588 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange(); 13589 13590 return false; 13591 } 13592 13593 static bool 13594 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) { 13595 // C++ [basic.stc.dynamic.deallocation]p1: 13596 // A program is ill-formed if deallocation functions are declared in a 13597 // namespace scope other than global scope or declared static in global 13598 // scope. 13599 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl)) 13600 return true; 13601 13602 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl); 13603 13604 // C++ P0722: 13605 // Within a class C, the first parameter of a destroying operator delete 13606 // shall be of type C *. The first parameter of any other deallocation 13607 // function shall be of type void *. 13608 CanQualType ExpectedFirstParamType = 13609 MD && MD->isDestroyingOperatorDelete() 13610 ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType( 13611 SemaRef.Context.getRecordType(MD->getParent()))) 13612 : SemaRef.Context.VoidPtrTy; 13613 13614 // C++ [basic.stc.dynamic.deallocation]p2: 13615 // Each deallocation function shall return void 13616 if (CheckOperatorNewDeleteTypes( 13617 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType, 13618 diag::err_operator_delete_dependent_param_type, 13619 diag::err_operator_delete_param_type)) 13620 return true; 13621 13622 // C++ P0722: 13623 // A destroying operator delete shall be a usual deallocation function. 13624 if (MD && !MD->getParent()->isDependentContext() && 13625 MD->isDestroyingOperatorDelete() && 13626 !SemaRef.isUsualDeallocationFunction(MD)) { 13627 SemaRef.Diag(MD->getLocation(), 13628 diag::err_destroying_operator_delete_not_usual); 13629 return true; 13630 } 13631 13632 return false; 13633 } 13634 13635 /// CheckOverloadedOperatorDeclaration - Check whether the declaration 13636 /// of this overloaded operator is well-formed. If so, returns false; 13637 /// otherwise, emits appropriate diagnostics and returns true. 13638 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) { 13639 assert(FnDecl && FnDecl->isOverloadedOperator() && 13640 "Expected an overloaded operator declaration"); 13641 13642 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator(); 13643 13644 // C++ [over.oper]p5: 13645 // The allocation and deallocation functions, operator new, 13646 // operator new[], operator delete and operator delete[], are 13647 // described completely in 3.7.3. The attributes and restrictions 13648 // found in the rest of this subclause do not apply to them unless 13649 // explicitly stated in 3.7.3. 13650 if (Op == OO_Delete || Op == OO_Array_Delete) 13651 return CheckOperatorDeleteDeclaration(*this, FnDecl); 13652 13653 if (Op == OO_New || Op == OO_Array_New) 13654 return CheckOperatorNewDeclaration(*this, FnDecl); 13655 13656 // C++ [over.oper]p6: 13657 // An operator function shall either be a non-static member 13658 // function or be a non-member function and have at least one 13659 // parameter whose type is a class, a reference to a class, an 13660 // enumeration, or a reference to an enumeration. 13661 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) { 13662 if (MethodDecl->isStatic()) 13663 return Diag(FnDecl->getLocation(), 13664 diag::err_operator_overload_static) << FnDecl->getDeclName(); 13665 } else { 13666 bool ClassOrEnumParam = false; 13667 for (auto Param : FnDecl->parameters()) { 13668 QualType ParamType = Param->getType().getNonReferenceType(); 13669 if (ParamType->isDependentType() || ParamType->isRecordType() || 13670 ParamType->isEnumeralType()) { 13671 ClassOrEnumParam = true; 13672 break; 13673 } 13674 } 13675 13676 if (!ClassOrEnumParam) 13677 return Diag(FnDecl->getLocation(), 13678 diag::err_operator_overload_needs_class_or_enum) 13679 << FnDecl->getDeclName(); 13680 } 13681 13682 // C++ [over.oper]p8: 13683 // An operator function cannot have default arguments (8.3.6), 13684 // except where explicitly stated below. 13685 // 13686 // Only the function-call operator allows default arguments 13687 // (C++ [over.call]p1). 13688 if (Op != OO_Call) { 13689 for (auto Param : FnDecl->parameters()) { 13690 if (Param->hasDefaultArg()) 13691 return Diag(Param->getLocation(), 13692 diag::err_operator_overload_default_arg) 13693 << FnDecl->getDeclName() << Param->getDefaultArgRange(); 13694 } 13695 } 13696 13697 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = { 13698 { false, false, false } 13699 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ 13700 , { Unary, Binary, MemberOnly } 13701 #include "clang/Basic/OperatorKinds.def" 13702 }; 13703 13704 bool CanBeUnaryOperator = OperatorUses[Op][0]; 13705 bool CanBeBinaryOperator = OperatorUses[Op][1]; 13706 bool MustBeMemberOperator = OperatorUses[Op][2]; 13707 13708 // C++ [over.oper]p8: 13709 // [...] Operator functions cannot have more or fewer parameters 13710 // than the number required for the corresponding operator, as 13711 // described in the rest of this subclause. 13712 unsigned NumParams = FnDecl->getNumParams() 13713 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0); 13714 if (Op != OO_Call && 13715 ((NumParams == 1 && !CanBeUnaryOperator) || 13716 (NumParams == 2 && !CanBeBinaryOperator) || 13717 (NumParams < 1) || (NumParams > 2))) { 13718 // We have the wrong number of parameters. 13719 unsigned ErrorKind; 13720 if (CanBeUnaryOperator && CanBeBinaryOperator) { 13721 ErrorKind = 2; // 2 -> unary or binary. 13722 } else if (CanBeUnaryOperator) { 13723 ErrorKind = 0; // 0 -> unary 13724 } else { 13725 assert(CanBeBinaryOperator && 13726 "All non-call overloaded operators are unary or binary!"); 13727 ErrorKind = 1; // 1 -> binary 13728 } 13729 13730 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be) 13731 << FnDecl->getDeclName() << NumParams << ErrorKind; 13732 } 13733 13734 // Overloaded operators other than operator() cannot be variadic. 13735 if (Op != OO_Call && 13736 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) { 13737 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic) 13738 << FnDecl->getDeclName(); 13739 } 13740 13741 // Some operators must be non-static member functions. 13742 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) { 13743 return Diag(FnDecl->getLocation(), 13744 diag::err_operator_overload_must_be_member) 13745 << FnDecl->getDeclName(); 13746 } 13747 13748 // C++ [over.inc]p1: 13749 // The user-defined function called operator++ implements the 13750 // prefix and postfix ++ operator. If this function is a member 13751 // function with no parameters, or a non-member function with one 13752 // parameter of class or enumeration type, it defines the prefix 13753 // increment operator ++ for objects of that type. If the function 13754 // is a member function with one parameter (which shall be of type 13755 // int) or a non-member function with two parameters (the second 13756 // of which shall be of type int), it defines the postfix 13757 // increment operator ++ for objects of that type. 13758 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) { 13759 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1); 13760 QualType ParamType = LastParam->getType(); 13761 13762 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) && 13763 !ParamType->isDependentType()) 13764 return Diag(LastParam->getLocation(), 13765 diag::err_operator_overload_post_incdec_must_be_int) 13766 << LastParam->getType() << (Op == OO_MinusMinus); 13767 } 13768 13769 return false; 13770 } 13771 13772 static bool 13773 checkLiteralOperatorTemplateParameterList(Sema &SemaRef, 13774 FunctionTemplateDecl *TpDecl) { 13775 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters(); 13776 13777 // Must have one or two template parameters. 13778 if (TemplateParams->size() == 1) { 13779 NonTypeTemplateParmDecl *PmDecl = 13780 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0)); 13781 13782 // The template parameter must be a char parameter pack. 13783 if (PmDecl && PmDecl->isTemplateParameterPack() && 13784 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy)) 13785 return false; 13786 13787 } else if (TemplateParams->size() == 2) { 13788 TemplateTypeParmDecl *PmType = 13789 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0)); 13790 NonTypeTemplateParmDecl *PmArgs = 13791 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1)); 13792 13793 // The second template parameter must be a parameter pack with the 13794 // first template parameter as its type. 13795 if (PmType && PmArgs && !PmType->isTemplateParameterPack() && 13796 PmArgs->isTemplateParameterPack()) { 13797 const TemplateTypeParmType *TArgs = 13798 PmArgs->getType()->getAs<TemplateTypeParmType>(); 13799 if (TArgs && TArgs->getDepth() == PmType->getDepth() && 13800 TArgs->getIndex() == PmType->getIndex()) { 13801 if (!SemaRef.inTemplateInstantiation()) 13802 SemaRef.Diag(TpDecl->getLocation(), 13803 diag::ext_string_literal_operator_template); 13804 return false; 13805 } 13806 } 13807 } 13808 13809 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(), 13810 diag::err_literal_operator_template) 13811 << TpDecl->getTemplateParameters()->getSourceRange(); 13812 return true; 13813 } 13814 13815 /// CheckLiteralOperatorDeclaration - Check whether the declaration 13816 /// of this literal operator function is well-formed. If so, returns 13817 /// false; otherwise, emits appropriate diagnostics and returns true. 13818 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) { 13819 if (isa<CXXMethodDecl>(FnDecl)) { 13820 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace) 13821 << FnDecl->getDeclName(); 13822 return true; 13823 } 13824 13825 if (FnDecl->isExternC()) { 13826 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c); 13827 if (const LinkageSpecDecl *LSD = 13828 FnDecl->getDeclContext()->getExternCContext()) 13829 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here); 13830 return true; 13831 } 13832 13833 // This might be the definition of a literal operator template. 13834 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate(); 13835 13836 // This might be a specialization of a literal operator template. 13837 if (!TpDecl) 13838 TpDecl = FnDecl->getPrimaryTemplate(); 13839 13840 // template <char...> type operator "" name() and 13841 // template <class T, T...> type operator "" name() are the only valid 13842 // template signatures, and the only valid signatures with no parameters. 13843 if (TpDecl) { 13844 if (FnDecl->param_size() != 0) { 13845 Diag(FnDecl->getLocation(), 13846 diag::err_literal_operator_template_with_params); 13847 return true; 13848 } 13849 13850 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl)) 13851 return true; 13852 13853 } else if (FnDecl->param_size() == 1) { 13854 const ParmVarDecl *Param = FnDecl->getParamDecl(0); 13855 13856 QualType ParamType = Param->getType().getUnqualifiedType(); 13857 13858 // Only unsigned long long int, long double, any character type, and const 13859 // char * are allowed as the only parameters. 13860 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) || 13861 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) || 13862 Context.hasSameType(ParamType, Context.CharTy) || 13863 Context.hasSameType(ParamType, Context.WideCharTy) || 13864 Context.hasSameType(ParamType, Context.Char8Ty) || 13865 Context.hasSameType(ParamType, Context.Char16Ty) || 13866 Context.hasSameType(ParamType, Context.Char32Ty)) { 13867 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) { 13868 QualType InnerType = Ptr->getPointeeType(); 13869 13870 // Pointer parameter must be a const char *. 13871 if (!(Context.hasSameType(InnerType.getUnqualifiedType(), 13872 Context.CharTy) && 13873 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) { 13874 Diag(Param->getSourceRange().getBegin(), 13875 diag::err_literal_operator_param) 13876 << ParamType << "'const char *'" << Param->getSourceRange(); 13877 return true; 13878 } 13879 13880 } else if (ParamType->isRealFloatingType()) { 13881 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 13882 << ParamType << Context.LongDoubleTy << Param->getSourceRange(); 13883 return true; 13884 13885 } else if (ParamType->isIntegerType()) { 13886 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param) 13887 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange(); 13888 return true; 13889 13890 } else { 13891 Diag(Param->getSourceRange().getBegin(), 13892 diag::err_literal_operator_invalid_param) 13893 << ParamType << Param->getSourceRange(); 13894 return true; 13895 } 13896 13897 } else if (FnDecl->param_size() == 2) { 13898 FunctionDecl::param_iterator Param = FnDecl->param_begin(); 13899 13900 // First, verify that the first parameter is correct. 13901 13902 QualType FirstParamType = (*Param)->getType().getUnqualifiedType(); 13903 13904 // Two parameter function must have a pointer to const as a 13905 // first parameter; let's strip those qualifiers. 13906 const PointerType *PT = FirstParamType->getAs<PointerType>(); 13907 13908 if (!PT) { 13909 Diag((*Param)->getSourceRange().getBegin(), 13910 diag::err_literal_operator_param) 13911 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 13912 return true; 13913 } 13914 13915 QualType PointeeType = PT->getPointeeType(); 13916 // First parameter must be const 13917 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) { 13918 Diag((*Param)->getSourceRange().getBegin(), 13919 diag::err_literal_operator_param) 13920 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 13921 return true; 13922 } 13923 13924 QualType InnerType = PointeeType.getUnqualifiedType(); 13925 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and 13926 // const char32_t* are allowed as the first parameter to a two-parameter 13927 // function 13928 if (!(Context.hasSameType(InnerType, Context.CharTy) || 13929 Context.hasSameType(InnerType, Context.WideCharTy) || 13930 Context.hasSameType(InnerType, Context.Char8Ty) || 13931 Context.hasSameType(InnerType, Context.Char16Ty) || 13932 Context.hasSameType(InnerType, Context.Char32Ty))) { 13933 Diag((*Param)->getSourceRange().getBegin(), 13934 diag::err_literal_operator_param) 13935 << FirstParamType << "'const char *'" << (*Param)->getSourceRange(); 13936 return true; 13937 } 13938 13939 // Move on to the second and final parameter. 13940 ++Param; 13941 13942 // The second parameter must be a std::size_t. 13943 QualType SecondParamType = (*Param)->getType().getUnqualifiedType(); 13944 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) { 13945 Diag((*Param)->getSourceRange().getBegin(), 13946 diag::err_literal_operator_param) 13947 << SecondParamType << Context.getSizeType() 13948 << (*Param)->getSourceRange(); 13949 return true; 13950 } 13951 } else { 13952 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count); 13953 return true; 13954 } 13955 13956 // Parameters are good. 13957 13958 // A parameter-declaration-clause containing a default argument is not 13959 // equivalent to any of the permitted forms. 13960 for (auto Param : FnDecl->parameters()) { 13961 if (Param->hasDefaultArg()) { 13962 Diag(Param->getDefaultArgRange().getBegin(), 13963 diag::err_literal_operator_default_argument) 13964 << Param->getDefaultArgRange(); 13965 break; 13966 } 13967 } 13968 13969 StringRef LiteralName 13970 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName(); 13971 if (LiteralName[0] != '_' && 13972 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) { 13973 // C++11 [usrlit.suffix]p1: 13974 // Literal suffix identifiers that do not start with an underscore 13975 // are reserved for future standardization. 13976 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved) 13977 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName); 13978 } 13979 13980 return false; 13981 } 13982 13983 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++ 13984 /// linkage specification, including the language and (if present) 13985 /// the '{'. ExternLoc is the location of the 'extern', Lang is the 13986 /// language string literal. LBraceLoc, if valid, provides the location of 13987 /// the '{' brace. Otherwise, this linkage specification does not 13988 /// have any braces. 13989 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, 13990 Expr *LangStr, 13991 SourceLocation LBraceLoc) { 13992 StringLiteral *Lit = cast<StringLiteral>(LangStr); 13993 if (!Lit->isAscii()) { 13994 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii) 13995 << LangStr->getSourceRange(); 13996 return nullptr; 13997 } 13998 13999 StringRef Lang = Lit->getString(); 14000 LinkageSpecDecl::LanguageIDs Language; 14001 if (Lang == "C") 14002 Language = LinkageSpecDecl::lang_c; 14003 else if (Lang == "C++") 14004 Language = LinkageSpecDecl::lang_cxx; 14005 else if (Lang == "C++11") 14006 Language = LinkageSpecDecl::lang_cxx_11; 14007 else if (Lang == "C++14") 14008 Language = LinkageSpecDecl::lang_cxx_14; 14009 else { 14010 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown) 14011 << LangStr->getSourceRange(); 14012 return nullptr; 14013 } 14014 14015 // FIXME: Add all the various semantics of linkage specifications 14016 14017 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc, 14018 LangStr->getExprLoc(), Language, 14019 LBraceLoc.isValid()); 14020 CurContext->addDecl(D); 14021 PushDeclContext(S, D); 14022 return D; 14023 } 14024 14025 /// ActOnFinishLinkageSpecification - Complete the definition of 14026 /// the C++ linkage specification LinkageSpec. If RBraceLoc is 14027 /// valid, it's the position of the closing '}' brace in a linkage 14028 /// specification that uses braces. 14029 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S, 14030 Decl *LinkageSpec, 14031 SourceLocation RBraceLoc) { 14032 if (RBraceLoc.isValid()) { 14033 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec); 14034 LSDecl->setRBraceLoc(RBraceLoc); 14035 } 14036 PopDeclContext(); 14037 return LinkageSpec; 14038 } 14039 14040 Decl *Sema::ActOnEmptyDeclaration(Scope *S, 14041 const ParsedAttributesView &AttrList, 14042 SourceLocation SemiLoc) { 14043 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc); 14044 // Attribute declarations appertain to empty declaration so we handle 14045 // them here. 14046 ProcessDeclAttributeList(S, ED, AttrList); 14047 14048 CurContext->addDecl(ED); 14049 return ED; 14050 } 14051 14052 /// Perform semantic analysis for the variable declaration that 14053 /// occurs within a C++ catch clause, returning the newly-created 14054 /// variable. 14055 VarDecl *Sema::BuildExceptionDeclaration(Scope *S, 14056 TypeSourceInfo *TInfo, 14057 SourceLocation StartLoc, 14058 SourceLocation Loc, 14059 IdentifierInfo *Name) { 14060 bool Invalid = false; 14061 QualType ExDeclType = TInfo->getType(); 14062 14063 // Arrays and functions decay. 14064 if (ExDeclType->isArrayType()) 14065 ExDeclType = Context.getArrayDecayedType(ExDeclType); 14066 else if (ExDeclType->isFunctionType()) 14067 ExDeclType = Context.getPointerType(ExDeclType); 14068 14069 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type. 14070 // The exception-declaration shall not denote a pointer or reference to an 14071 // incomplete type, other than [cv] void*. 14072 // N2844 forbids rvalue references. 14073 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) { 14074 Diag(Loc, diag::err_catch_rvalue_ref); 14075 Invalid = true; 14076 } 14077 14078 if (ExDeclType->isVariablyModifiedType()) { 14079 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType; 14080 Invalid = true; 14081 } 14082 14083 QualType BaseType = ExDeclType; 14084 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference 14085 unsigned DK = diag::err_catch_incomplete; 14086 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 14087 BaseType = Ptr->getPointeeType(); 14088 Mode = 1; 14089 DK = diag::err_catch_incomplete_ptr; 14090 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) { 14091 // For the purpose of error recovery, we treat rvalue refs like lvalue refs. 14092 BaseType = Ref->getPointeeType(); 14093 Mode = 2; 14094 DK = diag::err_catch_incomplete_ref; 14095 } 14096 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) && 14097 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK)) 14098 Invalid = true; 14099 14100 if (!Invalid && !ExDeclType->isDependentType() && 14101 RequireNonAbstractType(Loc, ExDeclType, 14102 diag::err_abstract_type_in_decl, 14103 AbstractVariableType)) 14104 Invalid = true; 14105 14106 // Only the non-fragile NeXT runtime currently supports C++ catches 14107 // of ObjC types, and no runtime supports catching ObjC types by value. 14108 if (!Invalid && getLangOpts().ObjC) { 14109 QualType T = ExDeclType; 14110 if (const ReferenceType *RT = T->getAs<ReferenceType>()) 14111 T = RT->getPointeeType(); 14112 14113 if (T->isObjCObjectType()) { 14114 Diag(Loc, diag::err_objc_object_catch); 14115 Invalid = true; 14116 } else if (T->isObjCObjectPointerType()) { 14117 // FIXME: should this be a test for macosx-fragile specifically? 14118 if (getLangOpts().ObjCRuntime.isFragile()) 14119 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile); 14120 } 14121 } 14122 14123 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name, 14124 ExDeclType, TInfo, SC_None); 14125 ExDecl->setExceptionVariable(true); 14126 14127 // In ARC, infer 'retaining' for variables of retainable type. 14128 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl)) 14129 Invalid = true; 14130 14131 if (!Invalid && !ExDeclType->isDependentType()) { 14132 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) { 14133 // Insulate this from anything else we might currently be parsing. 14134 EnterExpressionEvaluationContext scope( 14135 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 14136 14137 // C++ [except.handle]p16: 14138 // The object declared in an exception-declaration or, if the 14139 // exception-declaration does not specify a name, a temporary (12.2) is 14140 // copy-initialized (8.5) from the exception object. [...] 14141 // The object is destroyed when the handler exits, after the destruction 14142 // of any automatic objects initialized within the handler. 14143 // 14144 // We just pretend to initialize the object with itself, then make sure 14145 // it can be destroyed later. 14146 QualType initType = Context.getExceptionObjectType(ExDeclType); 14147 14148 InitializedEntity entity = 14149 InitializedEntity::InitializeVariable(ExDecl); 14150 InitializationKind initKind = 14151 InitializationKind::CreateCopy(Loc, SourceLocation()); 14152 14153 Expr *opaqueValue = 14154 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary); 14155 InitializationSequence sequence(*this, entity, initKind, opaqueValue); 14156 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue); 14157 if (result.isInvalid()) 14158 Invalid = true; 14159 else { 14160 // If the constructor used was non-trivial, set this as the 14161 // "initializer". 14162 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>(); 14163 if (!construct->getConstructor()->isTrivial()) { 14164 Expr *init = MaybeCreateExprWithCleanups(construct); 14165 ExDecl->setInit(init); 14166 } 14167 14168 // And make sure it's destructable. 14169 FinalizeVarWithDestructor(ExDecl, recordType); 14170 } 14171 } 14172 } 14173 14174 if (Invalid) 14175 ExDecl->setInvalidDecl(); 14176 14177 return ExDecl; 14178 } 14179 14180 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch 14181 /// handler. 14182 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) { 14183 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 14184 bool Invalid = D.isInvalidType(); 14185 14186 // Check for unexpanded parameter packs. 14187 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 14188 UPPC_ExceptionType)) { 14189 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy, 14190 D.getIdentifierLoc()); 14191 Invalid = true; 14192 } 14193 14194 IdentifierInfo *II = D.getIdentifier(); 14195 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(), 14196 LookupOrdinaryName, 14197 ForVisibleRedeclaration)) { 14198 // The scope should be freshly made just for us. There is just no way 14199 // it contains any previous declaration, except for function parameters in 14200 // a function-try-block's catch statement. 14201 assert(!S->isDeclScope(PrevDecl)); 14202 if (isDeclInScope(PrevDecl, CurContext, S)) { 14203 Diag(D.getIdentifierLoc(), diag::err_redefinition) 14204 << D.getIdentifier(); 14205 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 14206 Invalid = true; 14207 } else if (PrevDecl->isTemplateParameter()) 14208 // Maybe we will complain about the shadowed template parameter. 14209 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 14210 } 14211 14212 if (D.getCXXScopeSpec().isSet() && !Invalid) { 14213 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator) 14214 << D.getCXXScopeSpec().getRange(); 14215 Invalid = true; 14216 } 14217 14218 VarDecl *ExDecl = BuildExceptionDeclaration( 14219 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier()); 14220 if (Invalid) 14221 ExDecl->setInvalidDecl(); 14222 14223 // Add the exception declaration into this scope. 14224 if (II) 14225 PushOnScopeChains(ExDecl, S); 14226 else 14227 CurContext->addDecl(ExDecl); 14228 14229 ProcessDeclAttributes(S, ExDecl, D); 14230 return ExDecl; 14231 } 14232 14233 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 14234 Expr *AssertExpr, 14235 Expr *AssertMessageExpr, 14236 SourceLocation RParenLoc) { 14237 StringLiteral *AssertMessage = 14238 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr; 14239 14240 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression)) 14241 return nullptr; 14242 14243 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr, 14244 AssertMessage, RParenLoc, false); 14245 } 14246 14247 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 14248 Expr *AssertExpr, 14249 StringLiteral *AssertMessage, 14250 SourceLocation RParenLoc, 14251 bool Failed) { 14252 assert(AssertExpr != nullptr && "Expected non-null condition"); 14253 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() && 14254 !Failed) { 14255 // In a static_assert-declaration, the constant-expression shall be a 14256 // constant expression that can be contextually converted to bool. 14257 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr); 14258 if (Converted.isInvalid()) 14259 Failed = true; 14260 14261 ExprResult FullAssertExpr = 14262 ActOnFinishFullExpr(Converted.get(), StaticAssertLoc, 14263 /*DiscardedValue*/ false, 14264 /*IsConstexpr*/ true); 14265 if (FullAssertExpr.isInvalid()) 14266 Failed = true; 14267 else 14268 AssertExpr = FullAssertExpr.get(); 14269 14270 llvm::APSInt Cond; 14271 if (!Failed && VerifyIntegerConstantExpression(AssertExpr, &Cond, 14272 diag::err_static_assert_expression_is_not_constant, 14273 /*AllowFold=*/false).isInvalid()) 14274 Failed = true; 14275 14276 if (!Failed && !Cond) { 14277 SmallString<256> MsgBuffer; 14278 llvm::raw_svector_ostream Msg(MsgBuffer); 14279 if (AssertMessage) 14280 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy()); 14281 14282 Expr *InnerCond = nullptr; 14283 std::string InnerCondDescription; 14284 std::tie(InnerCond, InnerCondDescription) = 14285 findFailedBooleanCondition(Converted.get()); 14286 if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond) 14287 && !isa<IntegerLiteral>(InnerCond)) { 14288 Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed) 14289 << InnerCondDescription << !AssertMessage 14290 << Msg.str() << InnerCond->getSourceRange(); 14291 } else { 14292 Diag(StaticAssertLoc, diag::err_static_assert_failed) 14293 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange(); 14294 } 14295 Failed = true; 14296 } 14297 } else { 14298 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc, 14299 /*DiscardedValue*/false, 14300 /*IsConstexpr*/true); 14301 if (FullAssertExpr.isInvalid()) 14302 Failed = true; 14303 else 14304 AssertExpr = FullAssertExpr.get(); 14305 } 14306 14307 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc, 14308 AssertExpr, AssertMessage, RParenLoc, 14309 Failed); 14310 14311 CurContext->addDecl(Decl); 14312 return Decl; 14313 } 14314 14315 /// Perform semantic analysis of the given friend type declaration. 14316 /// 14317 /// \returns A friend declaration that. 14318 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart, 14319 SourceLocation FriendLoc, 14320 TypeSourceInfo *TSInfo) { 14321 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration"); 14322 14323 QualType T = TSInfo->getType(); 14324 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange(); 14325 14326 // C++03 [class.friend]p2: 14327 // An elaborated-type-specifier shall be used in a friend declaration 14328 // for a class.* 14329 // 14330 // * The class-key of the elaborated-type-specifier is required. 14331 if (!CodeSynthesisContexts.empty()) { 14332 // Do not complain about the form of friend template types during any kind 14333 // of code synthesis. For template instantiation, we will have complained 14334 // when the template was defined. 14335 } else { 14336 if (!T->isElaboratedTypeSpecifier()) { 14337 // If we evaluated the type to a record type, suggest putting 14338 // a tag in front. 14339 if (const RecordType *RT = T->getAs<RecordType>()) { 14340 RecordDecl *RD = RT->getDecl(); 14341 14342 SmallString<16> InsertionText(" "); 14343 InsertionText += RD->getKindName(); 14344 14345 Diag(TypeRange.getBegin(), 14346 getLangOpts().CPlusPlus11 ? 14347 diag::warn_cxx98_compat_unelaborated_friend_type : 14348 diag::ext_unelaborated_friend_type) 14349 << (unsigned) RD->getTagKind() 14350 << T 14351 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc), 14352 InsertionText); 14353 } else { 14354 Diag(FriendLoc, 14355 getLangOpts().CPlusPlus11 ? 14356 diag::warn_cxx98_compat_nonclass_type_friend : 14357 diag::ext_nonclass_type_friend) 14358 << T 14359 << TypeRange; 14360 } 14361 } else if (T->getAs<EnumType>()) { 14362 Diag(FriendLoc, 14363 getLangOpts().CPlusPlus11 ? 14364 diag::warn_cxx98_compat_enum_friend : 14365 diag::ext_enum_friend) 14366 << T 14367 << TypeRange; 14368 } 14369 14370 // C++11 [class.friend]p3: 14371 // A friend declaration that does not declare a function shall have one 14372 // of the following forms: 14373 // friend elaborated-type-specifier ; 14374 // friend simple-type-specifier ; 14375 // friend typename-specifier ; 14376 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc) 14377 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T; 14378 } 14379 14380 // If the type specifier in a friend declaration designates a (possibly 14381 // cv-qualified) class type, that class is declared as a friend; otherwise, 14382 // the friend declaration is ignored. 14383 return FriendDecl::Create(Context, CurContext, 14384 TSInfo->getTypeLoc().getBeginLoc(), TSInfo, 14385 FriendLoc); 14386 } 14387 14388 /// Handle a friend tag declaration where the scope specifier was 14389 /// templated. 14390 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 14391 unsigned TagSpec, SourceLocation TagLoc, 14392 CXXScopeSpec &SS, IdentifierInfo *Name, 14393 SourceLocation NameLoc, 14394 const ParsedAttributesView &Attr, 14395 MultiTemplateParamsArg TempParamLists) { 14396 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 14397 14398 bool IsMemberSpecialization = false; 14399 bool Invalid = false; 14400 14401 if (TemplateParameterList *TemplateParams = 14402 MatchTemplateParametersToScopeSpecifier( 14403 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true, 14404 IsMemberSpecialization, Invalid)) { 14405 if (TemplateParams->size() > 0) { 14406 // This is a declaration of a class template. 14407 if (Invalid) 14408 return nullptr; 14409 14410 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name, 14411 NameLoc, Attr, TemplateParams, AS_public, 14412 /*ModulePrivateLoc=*/SourceLocation(), 14413 FriendLoc, TempParamLists.size() - 1, 14414 TempParamLists.data()).get(); 14415 } else { 14416 // The "template<>" header is extraneous. 14417 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 14418 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 14419 IsMemberSpecialization = true; 14420 } 14421 } 14422 14423 if (Invalid) return nullptr; 14424 14425 bool isAllExplicitSpecializations = true; 14426 for (unsigned I = TempParamLists.size(); I-- > 0; ) { 14427 if (TempParamLists[I]->size()) { 14428 isAllExplicitSpecializations = false; 14429 break; 14430 } 14431 } 14432 14433 // FIXME: don't ignore attributes. 14434 14435 // If it's explicit specializations all the way down, just forget 14436 // about the template header and build an appropriate non-templated 14437 // friend. TODO: for source fidelity, remember the headers. 14438 if (isAllExplicitSpecializations) { 14439 if (SS.isEmpty()) { 14440 bool Owned = false; 14441 bool IsDependent = false; 14442 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc, 14443 Attr, AS_public, 14444 /*ModulePrivateLoc=*/SourceLocation(), 14445 MultiTemplateParamsArg(), Owned, IsDependent, 14446 /*ScopedEnumKWLoc=*/SourceLocation(), 14447 /*ScopedEnumUsesClassTag=*/false, 14448 /*UnderlyingType=*/TypeResult(), 14449 /*IsTypeSpecifier=*/false, 14450 /*IsTemplateParamOrArg=*/false); 14451 } 14452 14453 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 14454 ElaboratedTypeKeyword Keyword 14455 = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 14456 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc, 14457 *Name, NameLoc); 14458 if (T.isNull()) 14459 return nullptr; 14460 14461 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 14462 if (isa<DependentNameType>(T)) { 14463 DependentNameTypeLoc TL = 14464 TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 14465 TL.setElaboratedKeywordLoc(TagLoc); 14466 TL.setQualifierLoc(QualifierLoc); 14467 TL.setNameLoc(NameLoc); 14468 } else { 14469 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>(); 14470 TL.setElaboratedKeywordLoc(TagLoc); 14471 TL.setQualifierLoc(QualifierLoc); 14472 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc); 14473 } 14474 14475 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 14476 TSI, FriendLoc, TempParamLists); 14477 Friend->setAccess(AS_public); 14478 CurContext->addDecl(Friend); 14479 return Friend; 14480 } 14481 14482 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?"); 14483 14484 14485 14486 // Handle the case of a templated-scope friend class. e.g. 14487 // template <class T> class A<T>::B; 14488 // FIXME: we don't support these right now. 14489 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported) 14490 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext); 14491 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 14492 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name); 14493 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 14494 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>(); 14495 TL.setElaboratedKeywordLoc(TagLoc); 14496 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 14497 TL.setNameLoc(NameLoc); 14498 14499 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc, 14500 TSI, FriendLoc, TempParamLists); 14501 Friend->setAccess(AS_public); 14502 Friend->setUnsupportedFriend(true); 14503 CurContext->addDecl(Friend); 14504 return Friend; 14505 } 14506 14507 /// Handle a friend type declaration. This works in tandem with 14508 /// ActOnTag. 14509 /// 14510 /// Notes on friend class templates: 14511 /// 14512 /// We generally treat friend class declarations as if they were 14513 /// declaring a class. So, for example, the elaborated type specifier 14514 /// in a friend declaration is required to obey the restrictions of a 14515 /// class-head (i.e. no typedefs in the scope chain), template 14516 /// parameters are required to match up with simple template-ids, &c. 14517 /// However, unlike when declaring a template specialization, it's 14518 /// okay to refer to a template specialization without an empty 14519 /// template parameter declaration, e.g. 14520 /// friend class A<T>::B<unsigned>; 14521 /// We permit this as a special case; if there are any template 14522 /// parameters present at all, require proper matching, i.e. 14523 /// template <> template \<class T> friend class A<int>::B; 14524 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 14525 MultiTemplateParamsArg TempParams) { 14526 SourceLocation Loc = DS.getBeginLoc(); 14527 14528 assert(DS.isFriendSpecified()); 14529 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 14530 14531 // C++ [class.friend]p3: 14532 // A friend declaration that does not declare a function shall have one of 14533 // the following forms: 14534 // friend elaborated-type-specifier ; 14535 // friend simple-type-specifier ; 14536 // friend typename-specifier ; 14537 // 14538 // Any declaration with a type qualifier does not have that form. (It's 14539 // legal to specify a qualified type as a friend, you just can't write the 14540 // keywords.) 14541 if (DS.getTypeQualifiers()) { 14542 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 14543 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const"; 14544 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 14545 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile"; 14546 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 14547 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict"; 14548 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 14549 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic"; 14550 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 14551 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned"; 14552 } 14553 14554 // Try to convert the decl specifier to a type. This works for 14555 // friend templates because ActOnTag never produces a ClassTemplateDecl 14556 // for a TUK_Friend. 14557 Declarator TheDeclarator(DS, DeclaratorContext::MemberContext); 14558 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S); 14559 QualType T = TSI->getType(); 14560 if (TheDeclarator.isInvalidType()) 14561 return nullptr; 14562 14563 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration)) 14564 return nullptr; 14565 14566 // This is definitely an error in C++98. It's probably meant to 14567 // be forbidden in C++0x, too, but the specification is just 14568 // poorly written. 14569 // 14570 // The problem is with declarations like the following: 14571 // template <T> friend A<T>::foo; 14572 // where deciding whether a class C is a friend or not now hinges 14573 // on whether there exists an instantiation of A that causes 14574 // 'foo' to equal C. There are restrictions on class-heads 14575 // (which we declare (by fiat) elaborated friend declarations to 14576 // be) that makes this tractable. 14577 // 14578 // FIXME: handle "template <> friend class A<T>;", which 14579 // is possibly well-formed? Who even knows? 14580 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) { 14581 Diag(Loc, diag::err_tagless_friend_type_template) 14582 << DS.getSourceRange(); 14583 return nullptr; 14584 } 14585 14586 // C++98 [class.friend]p1: A friend of a class is a function 14587 // or class that is not a member of the class . . . 14588 // This is fixed in DR77, which just barely didn't make the C++03 14589 // deadline. It's also a very silly restriction that seriously 14590 // affects inner classes and which nobody else seems to implement; 14591 // thus we never diagnose it, not even in -pedantic. 14592 // 14593 // But note that we could warn about it: it's always useless to 14594 // friend one of your own members (it's not, however, worthless to 14595 // friend a member of an arbitrary specialization of your template). 14596 14597 Decl *D; 14598 if (!TempParams.empty()) 14599 D = FriendTemplateDecl::Create(Context, CurContext, Loc, 14600 TempParams, 14601 TSI, 14602 DS.getFriendSpecLoc()); 14603 else 14604 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI); 14605 14606 if (!D) 14607 return nullptr; 14608 14609 D->setAccess(AS_public); 14610 CurContext->addDecl(D); 14611 14612 return D; 14613 } 14614 14615 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, 14616 MultiTemplateParamsArg TemplateParams) { 14617 const DeclSpec &DS = D.getDeclSpec(); 14618 14619 assert(DS.isFriendSpecified()); 14620 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified); 14621 14622 SourceLocation Loc = D.getIdentifierLoc(); 14623 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 14624 14625 // C++ [class.friend]p1 14626 // A friend of a class is a function or class.... 14627 // Note that this sees through typedefs, which is intended. 14628 // It *doesn't* see through dependent types, which is correct 14629 // according to [temp.arg.type]p3: 14630 // If a declaration acquires a function type through a 14631 // type dependent on a template-parameter and this causes 14632 // a declaration that does not use the syntactic form of a 14633 // function declarator to have a function type, the program 14634 // is ill-formed. 14635 if (!TInfo->getType()->isFunctionType()) { 14636 Diag(Loc, diag::err_unexpected_friend); 14637 14638 // It might be worthwhile to try to recover by creating an 14639 // appropriate declaration. 14640 return nullptr; 14641 } 14642 14643 // C++ [namespace.memdef]p3 14644 // - If a friend declaration in a non-local class first declares a 14645 // class or function, the friend class or function is a member 14646 // of the innermost enclosing namespace. 14647 // - The name of the friend is not found by simple name lookup 14648 // until a matching declaration is provided in that namespace 14649 // scope (either before or after the class declaration granting 14650 // friendship). 14651 // - If a friend function is called, its name may be found by the 14652 // name lookup that considers functions from namespaces and 14653 // classes associated with the types of the function arguments. 14654 // - When looking for a prior declaration of a class or a function 14655 // declared as a friend, scopes outside the innermost enclosing 14656 // namespace scope are not considered. 14657 14658 CXXScopeSpec &SS = D.getCXXScopeSpec(); 14659 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 14660 assert(NameInfo.getName()); 14661 14662 // Check for unexpanded parameter packs. 14663 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) || 14664 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) || 14665 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration)) 14666 return nullptr; 14667 14668 // The context we found the declaration in, or in which we should 14669 // create the declaration. 14670 DeclContext *DC; 14671 Scope *DCScope = S; 14672 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 14673 ForExternalRedeclaration); 14674 14675 // There are five cases here. 14676 // - There's no scope specifier and we're in a local class. Only look 14677 // for functions declared in the immediately-enclosing block scope. 14678 // We recover from invalid scope qualifiers as if they just weren't there. 14679 FunctionDecl *FunctionContainingLocalClass = nullptr; 14680 if ((SS.isInvalid() || !SS.isSet()) && 14681 (FunctionContainingLocalClass = 14682 cast<CXXRecordDecl>(CurContext)->isLocalClass())) { 14683 // C++11 [class.friend]p11: 14684 // If a friend declaration appears in a local class and the name 14685 // specified is an unqualified name, a prior declaration is 14686 // looked up without considering scopes that are outside the 14687 // innermost enclosing non-class scope. For a friend function 14688 // declaration, if there is no prior declaration, the program is 14689 // ill-formed. 14690 14691 // Find the innermost enclosing non-class scope. This is the block 14692 // scope containing the local class definition (or for a nested class, 14693 // the outer local class). 14694 DCScope = S->getFnParent(); 14695 14696 // Look up the function name in the scope. 14697 Previous.clear(LookupLocalFriendName); 14698 LookupName(Previous, S, /*AllowBuiltinCreation*/false); 14699 14700 if (!Previous.empty()) { 14701 // All possible previous declarations must have the same context: 14702 // either they were declared at block scope or they are members of 14703 // one of the enclosing local classes. 14704 DC = Previous.getRepresentativeDecl()->getDeclContext(); 14705 } else { 14706 // This is ill-formed, but provide the context that we would have 14707 // declared the function in, if we were permitted to, for error recovery. 14708 DC = FunctionContainingLocalClass; 14709 } 14710 adjustContextForLocalExternDecl(DC); 14711 14712 // C++ [class.friend]p6: 14713 // A function can be defined in a friend declaration of a class if and 14714 // only if the class is a non-local class (9.8), the function name is 14715 // unqualified, and the function has namespace scope. 14716 if (D.isFunctionDefinition()) { 14717 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class); 14718 } 14719 14720 // - There's no scope specifier, in which case we just go to the 14721 // appropriate scope and look for a function or function template 14722 // there as appropriate. 14723 } else if (SS.isInvalid() || !SS.isSet()) { 14724 // C++11 [namespace.memdef]p3: 14725 // If the name in a friend declaration is neither qualified nor 14726 // a template-id and the declaration is a function or an 14727 // elaborated-type-specifier, the lookup to determine whether 14728 // the entity has been previously declared shall not consider 14729 // any scopes outside the innermost enclosing namespace. 14730 bool isTemplateId = 14731 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId; 14732 14733 // Find the appropriate context according to the above. 14734 DC = CurContext; 14735 14736 // Skip class contexts. If someone can cite chapter and verse 14737 // for this behavior, that would be nice --- it's what GCC and 14738 // EDG do, and it seems like a reasonable intent, but the spec 14739 // really only says that checks for unqualified existing 14740 // declarations should stop at the nearest enclosing namespace, 14741 // not that they should only consider the nearest enclosing 14742 // namespace. 14743 while (DC->isRecord()) 14744 DC = DC->getParent(); 14745 14746 DeclContext *LookupDC = DC; 14747 while (LookupDC->isTransparentContext()) 14748 LookupDC = LookupDC->getParent(); 14749 14750 while (true) { 14751 LookupQualifiedName(Previous, LookupDC); 14752 14753 if (!Previous.empty()) { 14754 DC = LookupDC; 14755 break; 14756 } 14757 14758 if (isTemplateId) { 14759 if (isa<TranslationUnitDecl>(LookupDC)) break; 14760 } else { 14761 if (LookupDC->isFileContext()) break; 14762 } 14763 LookupDC = LookupDC->getParent(); 14764 } 14765 14766 DCScope = getScopeForDeclContext(S, DC); 14767 14768 // - There's a non-dependent scope specifier, in which case we 14769 // compute it and do a previous lookup there for a function 14770 // or function template. 14771 } else if (!SS.getScopeRep()->isDependent()) { 14772 DC = computeDeclContext(SS); 14773 if (!DC) return nullptr; 14774 14775 if (RequireCompleteDeclContext(SS, DC)) return nullptr; 14776 14777 LookupQualifiedName(Previous, DC); 14778 14779 // C++ [class.friend]p1: A friend of a class is a function or 14780 // class that is not a member of the class . . . 14781 if (DC->Equals(CurContext)) 14782 Diag(DS.getFriendSpecLoc(), 14783 getLangOpts().CPlusPlus11 ? 14784 diag::warn_cxx98_compat_friend_is_member : 14785 diag::err_friend_is_member); 14786 14787 if (D.isFunctionDefinition()) { 14788 // C++ [class.friend]p6: 14789 // A function can be defined in a friend declaration of a class if and 14790 // only if the class is a non-local class (9.8), the function name is 14791 // unqualified, and the function has namespace scope. 14792 // 14793 // FIXME: We should only do this if the scope specifier names the 14794 // innermost enclosing namespace; otherwise the fixit changes the 14795 // meaning of the code. 14796 SemaDiagnosticBuilder DB 14797 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def); 14798 14799 DB << SS.getScopeRep(); 14800 if (DC->isFileContext()) 14801 DB << FixItHint::CreateRemoval(SS.getRange()); 14802 SS.clear(); 14803 } 14804 14805 // - There's a scope specifier that does not match any template 14806 // parameter lists, in which case we use some arbitrary context, 14807 // create a method or method template, and wait for instantiation. 14808 // - There's a scope specifier that does match some template 14809 // parameter lists, which we don't handle right now. 14810 } else { 14811 if (D.isFunctionDefinition()) { 14812 // C++ [class.friend]p6: 14813 // A function can be defined in a friend declaration of a class if and 14814 // only if the class is a non-local class (9.8), the function name is 14815 // unqualified, and the function has namespace scope. 14816 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def) 14817 << SS.getScopeRep(); 14818 } 14819 14820 DC = CurContext; 14821 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?"); 14822 } 14823 14824 if (!DC->isRecord()) { 14825 int DiagArg = -1; 14826 switch (D.getName().getKind()) { 14827 case UnqualifiedIdKind::IK_ConstructorTemplateId: 14828 case UnqualifiedIdKind::IK_ConstructorName: 14829 DiagArg = 0; 14830 break; 14831 case UnqualifiedIdKind::IK_DestructorName: 14832 DiagArg = 1; 14833 break; 14834 case UnqualifiedIdKind::IK_ConversionFunctionId: 14835 DiagArg = 2; 14836 break; 14837 case UnqualifiedIdKind::IK_DeductionGuideName: 14838 DiagArg = 3; 14839 break; 14840 case UnqualifiedIdKind::IK_Identifier: 14841 case UnqualifiedIdKind::IK_ImplicitSelfParam: 14842 case UnqualifiedIdKind::IK_LiteralOperatorId: 14843 case UnqualifiedIdKind::IK_OperatorFunctionId: 14844 case UnqualifiedIdKind::IK_TemplateId: 14845 break; 14846 } 14847 // This implies that it has to be an operator or function. 14848 if (DiagArg >= 0) { 14849 Diag(Loc, diag::err_introducing_special_friend) << DiagArg; 14850 return nullptr; 14851 } 14852 } 14853 14854 // FIXME: This is an egregious hack to cope with cases where the scope stack 14855 // does not contain the declaration context, i.e., in an out-of-line 14856 // definition of a class. 14857 Scope FakeDCScope(S, Scope::DeclScope, Diags); 14858 if (!DCScope) { 14859 FakeDCScope.setEntity(DC); 14860 DCScope = &FakeDCScope; 14861 } 14862 14863 bool AddToScope = true; 14864 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous, 14865 TemplateParams, AddToScope); 14866 if (!ND) return nullptr; 14867 14868 assert(ND->getLexicalDeclContext() == CurContext); 14869 14870 // If we performed typo correction, we might have added a scope specifier 14871 // and changed the decl context. 14872 DC = ND->getDeclContext(); 14873 14874 // Add the function declaration to the appropriate lookup tables, 14875 // adjusting the redeclarations list as necessary. We don't 14876 // want to do this yet if the friending class is dependent. 14877 // 14878 // Also update the scope-based lookup if the target context's 14879 // lookup context is in lexical scope. 14880 if (!CurContext->isDependentContext()) { 14881 DC = DC->getRedeclContext(); 14882 DC->makeDeclVisibleInContext(ND); 14883 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 14884 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false); 14885 } 14886 14887 FriendDecl *FrD = FriendDecl::Create(Context, CurContext, 14888 D.getIdentifierLoc(), ND, 14889 DS.getFriendSpecLoc()); 14890 FrD->setAccess(AS_public); 14891 CurContext->addDecl(FrD); 14892 14893 if (ND->isInvalidDecl()) { 14894 FrD->setInvalidDecl(); 14895 } else { 14896 if (DC->isRecord()) CheckFriendAccess(ND); 14897 14898 FunctionDecl *FD; 14899 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 14900 FD = FTD->getTemplatedDecl(); 14901 else 14902 FD = cast<FunctionDecl>(ND); 14903 14904 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a 14905 // default argument expression, that declaration shall be a definition 14906 // and shall be the only declaration of the function or function 14907 // template in the translation unit. 14908 if (functionDeclHasDefaultArgument(FD)) { 14909 // We can't look at FD->getPreviousDecl() because it may not have been set 14910 // if we're in a dependent context. If the function is known to be a 14911 // redeclaration, we will have narrowed Previous down to the right decl. 14912 if (D.isRedeclaration()) { 14913 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared); 14914 Diag(Previous.getRepresentativeDecl()->getLocation(), 14915 diag::note_previous_declaration); 14916 } else if (!D.isFunctionDefinition()) 14917 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def); 14918 } 14919 14920 // Mark templated-scope function declarations as unsupported. 14921 if (FD->getNumTemplateParameterLists() && SS.isValid()) { 14922 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported) 14923 << SS.getScopeRep() << SS.getRange() 14924 << cast<CXXRecordDecl>(CurContext); 14925 FrD->setUnsupportedFriend(true); 14926 } 14927 } 14928 14929 return ND; 14930 } 14931 14932 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) { 14933 AdjustDeclIfTemplate(Dcl); 14934 14935 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl); 14936 if (!Fn) { 14937 Diag(DelLoc, diag::err_deleted_non_function); 14938 return; 14939 } 14940 14941 // Deleted function does not have a body. 14942 Fn->setWillHaveBody(false); 14943 14944 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) { 14945 // Don't consider the implicit declaration we generate for explicit 14946 // specializations. FIXME: Do not generate these implicit declarations. 14947 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization || 14948 Prev->getPreviousDecl()) && 14949 !Prev->isDefined()) { 14950 Diag(DelLoc, diag::err_deleted_decl_not_first); 14951 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(), 14952 Prev->isImplicit() ? diag::note_previous_implicit_declaration 14953 : diag::note_previous_declaration); 14954 } 14955 // If the declaration wasn't the first, we delete the function anyway for 14956 // recovery. 14957 Fn = Fn->getCanonicalDecl(); 14958 } 14959 14960 // dllimport/dllexport cannot be deleted. 14961 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) { 14962 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr; 14963 Fn->setInvalidDecl(); 14964 } 14965 14966 if (Fn->isDeleted()) 14967 return; 14968 14969 // See if we're deleting a function which is already known to override a 14970 // non-deleted virtual function. 14971 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) { 14972 bool IssuedDiagnostic = false; 14973 for (const CXXMethodDecl *O : MD->overridden_methods()) { 14974 if (!(*MD->begin_overridden_methods())->isDeleted()) { 14975 if (!IssuedDiagnostic) { 14976 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName(); 14977 IssuedDiagnostic = true; 14978 } 14979 Diag(O->getLocation(), diag::note_overridden_virtual_function); 14980 } 14981 } 14982 // If this function was implicitly deleted because it was defaulted, 14983 // explain why it was deleted. 14984 if (IssuedDiagnostic && MD->isDefaulted()) 14985 ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr, 14986 /*Diagnose*/true); 14987 } 14988 14989 // C++11 [basic.start.main]p3: 14990 // A program that defines main as deleted [...] is ill-formed. 14991 if (Fn->isMain()) 14992 Diag(DelLoc, diag::err_deleted_main); 14993 14994 // C++11 [dcl.fct.def.delete]p4: 14995 // A deleted function is implicitly inline. 14996 Fn->setImplicitlyInline(); 14997 Fn->setDeletedAsWritten(); 14998 } 14999 15000 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) { 15001 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl); 15002 15003 if (MD) { 15004 if (MD->getParent()->isDependentType()) { 15005 MD->setDefaulted(); 15006 MD->setExplicitlyDefaulted(); 15007 return; 15008 } 15009 15010 CXXSpecialMember Member = getSpecialMember(MD); 15011 if (Member == CXXInvalid) { 15012 if (!MD->isInvalidDecl()) 15013 Diag(DefaultLoc, diag::err_default_special_members); 15014 return; 15015 } 15016 15017 MD->setDefaulted(); 15018 MD->setExplicitlyDefaulted(); 15019 15020 // Unset that we will have a body for this function. We might not, 15021 // if it turns out to be trivial, and we don't need this marking now 15022 // that we've marked it as defaulted. 15023 MD->setWillHaveBody(false); 15024 15025 // If this definition appears within the record, do the checking when 15026 // the record is complete. 15027 const FunctionDecl *Primary = MD; 15028 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern()) 15029 // Ask the template instantiation pattern that actually had the 15030 // '= default' on it. 15031 Primary = Pattern; 15032 15033 // If the method was defaulted on its first declaration, we will have 15034 // already performed the checking in CheckCompletedCXXClass. Such a 15035 // declaration doesn't trigger an implicit definition. 15036 if (Primary->getCanonicalDecl()->isDefaulted()) 15037 return; 15038 15039 CheckExplicitlyDefaultedSpecialMember(MD); 15040 15041 if (!MD->isInvalidDecl()) 15042 DefineImplicitSpecialMember(*this, MD, DefaultLoc); 15043 } else { 15044 Diag(DefaultLoc, diag::err_default_special_members); 15045 } 15046 } 15047 15048 static void SearchForReturnInStmt(Sema &Self, Stmt *S) { 15049 for (Stmt *SubStmt : S->children()) { 15050 if (!SubStmt) 15051 continue; 15052 if (isa<ReturnStmt>(SubStmt)) 15053 Self.Diag(SubStmt->getBeginLoc(), 15054 diag::err_return_in_constructor_handler); 15055 if (!isa<Expr>(SubStmt)) 15056 SearchForReturnInStmt(Self, SubStmt); 15057 } 15058 } 15059 15060 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) { 15061 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) { 15062 CXXCatchStmt *Handler = TryBlock->getHandler(I); 15063 SearchForReturnInStmt(*this, Handler); 15064 } 15065 } 15066 15067 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 15068 const CXXMethodDecl *Old) { 15069 const auto *NewFT = New->getType()->getAs<FunctionProtoType>(); 15070 const auto *OldFT = Old->getType()->getAs<FunctionProtoType>(); 15071 15072 if (OldFT->hasExtParameterInfos()) { 15073 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I) 15074 // A parameter of the overriding method should be annotated with noescape 15075 // if the corresponding parameter of the overridden method is annotated. 15076 if (OldFT->getExtParameterInfo(I).isNoEscape() && 15077 !NewFT->getExtParameterInfo(I).isNoEscape()) { 15078 Diag(New->getParamDecl(I)->getLocation(), 15079 diag::warn_overriding_method_missing_noescape); 15080 Diag(Old->getParamDecl(I)->getLocation(), 15081 diag::note_overridden_marked_noescape); 15082 } 15083 } 15084 15085 // Virtual overrides must have the same code_seg. 15086 const auto *OldCSA = Old->getAttr<CodeSegAttr>(); 15087 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 15088 if ((NewCSA || OldCSA) && 15089 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) { 15090 Diag(New->getLocation(), diag::err_mismatched_code_seg_override); 15091 Diag(Old->getLocation(), diag::note_previous_declaration); 15092 return true; 15093 } 15094 15095 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv(); 15096 15097 // If the calling conventions match, everything is fine 15098 if (NewCC == OldCC) 15099 return false; 15100 15101 // If the calling conventions mismatch because the new function is static, 15102 // suppress the calling convention mismatch error; the error about static 15103 // function override (err_static_overrides_virtual from 15104 // Sema::CheckFunctionDeclaration) is more clear. 15105 if (New->getStorageClass() == SC_Static) 15106 return false; 15107 15108 Diag(New->getLocation(), 15109 diag::err_conflicting_overriding_cc_attributes) 15110 << New->getDeclName() << New->getType() << Old->getType(); 15111 Diag(Old->getLocation(), diag::note_overridden_virtual_function); 15112 return true; 15113 } 15114 15115 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 15116 const CXXMethodDecl *Old) { 15117 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType(); 15118 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType(); 15119 15120 if (Context.hasSameType(NewTy, OldTy) || 15121 NewTy->isDependentType() || OldTy->isDependentType()) 15122 return false; 15123 15124 // Check if the return types are covariant 15125 QualType NewClassTy, OldClassTy; 15126 15127 /// Both types must be pointers or references to classes. 15128 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) { 15129 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) { 15130 NewClassTy = NewPT->getPointeeType(); 15131 OldClassTy = OldPT->getPointeeType(); 15132 } 15133 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) { 15134 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) { 15135 if (NewRT->getTypeClass() == OldRT->getTypeClass()) { 15136 NewClassTy = NewRT->getPointeeType(); 15137 OldClassTy = OldRT->getPointeeType(); 15138 } 15139 } 15140 } 15141 15142 // The return types aren't either both pointers or references to a class type. 15143 if (NewClassTy.isNull()) { 15144 Diag(New->getLocation(), 15145 diag::err_different_return_type_for_overriding_virtual_function) 15146 << New->getDeclName() << NewTy << OldTy 15147 << New->getReturnTypeSourceRange(); 15148 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 15149 << Old->getReturnTypeSourceRange(); 15150 15151 return true; 15152 } 15153 15154 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) { 15155 // C++14 [class.virtual]p8: 15156 // If the class type in the covariant return type of D::f differs from 15157 // that of B::f, the class type in the return type of D::f shall be 15158 // complete at the point of declaration of D::f or shall be the class 15159 // type D. 15160 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) { 15161 if (!RT->isBeingDefined() && 15162 RequireCompleteType(New->getLocation(), NewClassTy, 15163 diag::err_covariant_return_incomplete, 15164 New->getDeclName())) 15165 return true; 15166 } 15167 15168 // Check if the new class derives from the old class. 15169 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) { 15170 Diag(New->getLocation(), diag::err_covariant_return_not_derived) 15171 << New->getDeclName() << NewTy << OldTy 15172 << New->getReturnTypeSourceRange(); 15173 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 15174 << Old->getReturnTypeSourceRange(); 15175 return true; 15176 } 15177 15178 // Check if we the conversion from derived to base is valid. 15179 if (CheckDerivedToBaseConversion( 15180 NewClassTy, OldClassTy, 15181 diag::err_covariant_return_inaccessible_base, 15182 diag::err_covariant_return_ambiguous_derived_to_base_conv, 15183 New->getLocation(), New->getReturnTypeSourceRange(), 15184 New->getDeclName(), nullptr)) { 15185 // FIXME: this note won't trigger for delayed access control 15186 // diagnostics, and it's impossible to get an undelayed error 15187 // here from access control during the original parse because 15188 // the ParsingDeclSpec/ParsingDeclarator are still in scope. 15189 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 15190 << Old->getReturnTypeSourceRange(); 15191 return true; 15192 } 15193 } 15194 15195 // The qualifiers of the return types must be the same. 15196 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) { 15197 Diag(New->getLocation(), 15198 diag::err_covariant_return_type_different_qualifications) 15199 << New->getDeclName() << NewTy << OldTy 15200 << New->getReturnTypeSourceRange(); 15201 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 15202 << Old->getReturnTypeSourceRange(); 15203 return true; 15204 } 15205 15206 15207 // The new class type must have the same or less qualifiers as the old type. 15208 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) { 15209 Diag(New->getLocation(), 15210 diag::err_covariant_return_type_class_type_more_qualified) 15211 << New->getDeclName() << NewTy << OldTy 15212 << New->getReturnTypeSourceRange(); 15213 Diag(Old->getLocation(), diag::note_overridden_virtual_function) 15214 << Old->getReturnTypeSourceRange(); 15215 return true; 15216 } 15217 15218 return false; 15219 } 15220 15221 /// Mark the given method pure. 15222 /// 15223 /// \param Method the method to be marked pure. 15224 /// 15225 /// \param InitRange the source range that covers the "0" initializer. 15226 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) { 15227 SourceLocation EndLoc = InitRange.getEnd(); 15228 if (EndLoc.isValid()) 15229 Method->setRangeEnd(EndLoc); 15230 15231 if (Method->isVirtual() || Method->getParent()->isDependentContext()) { 15232 Method->setPure(); 15233 return false; 15234 } 15235 15236 if (!Method->isInvalidDecl()) 15237 Diag(Method->getLocation(), diag::err_non_virtual_pure) 15238 << Method->getDeclName() << InitRange; 15239 return true; 15240 } 15241 15242 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) { 15243 if (D->getFriendObjectKind()) 15244 Diag(D->getLocation(), diag::err_pure_friend); 15245 else if (auto *M = dyn_cast<CXXMethodDecl>(D)) 15246 CheckPureMethod(M, ZeroLoc); 15247 else 15248 Diag(D->getLocation(), diag::err_illegal_initializer); 15249 } 15250 15251 /// Determine whether the given declaration is a global variable or 15252 /// static data member. 15253 static bool isNonlocalVariable(const Decl *D) { 15254 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D)) 15255 return Var->hasGlobalStorage(); 15256 15257 return false; 15258 } 15259 15260 /// Invoked when we are about to parse an initializer for the declaration 15261 /// 'Dcl'. 15262 /// 15263 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 15264 /// static data member of class X, names should be looked up in the scope of 15265 /// class X. If the declaration had a scope specifier, a scope will have 15266 /// been created and passed in for this purpose. Otherwise, S will be null. 15267 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) { 15268 // If there is no declaration, there was an error parsing it. 15269 if (!D || D->isInvalidDecl()) 15270 return; 15271 15272 // We will always have a nested name specifier here, but this declaration 15273 // might not be out of line if the specifier names the current namespace: 15274 // extern int n; 15275 // int ::n = 0; 15276 if (S && D->isOutOfLine()) 15277 EnterDeclaratorContext(S, D->getDeclContext()); 15278 15279 // If we are parsing the initializer for a static data member, push a 15280 // new expression evaluation context that is associated with this static 15281 // data member. 15282 if (isNonlocalVariable(D)) 15283 PushExpressionEvaluationContext( 15284 ExpressionEvaluationContext::PotentiallyEvaluated, D); 15285 } 15286 15287 /// Invoked after we are finished parsing an initializer for the declaration D. 15288 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) { 15289 // If there is no declaration, there was an error parsing it. 15290 if (!D || D->isInvalidDecl()) 15291 return; 15292 15293 if (isNonlocalVariable(D)) 15294 PopExpressionEvaluationContext(); 15295 15296 if (S && D->isOutOfLine()) 15297 ExitDeclaratorContext(S); 15298 } 15299 15300 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a 15301 /// C++ if/switch/while/for statement. 15302 /// e.g: "if (int x = f()) {...}" 15303 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) { 15304 // C++ 6.4p2: 15305 // The declarator shall not specify a function or an array. 15306 // The type-specifier-seq shall not contain typedef and shall not declare a 15307 // new class or enumeration. 15308 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 15309 "Parser allowed 'typedef' as storage class of condition decl."); 15310 15311 Decl *Dcl = ActOnDeclarator(S, D); 15312 if (!Dcl) 15313 return true; 15314 15315 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function. 15316 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type) 15317 << D.getSourceRange(); 15318 return true; 15319 } 15320 15321 return Dcl; 15322 } 15323 15324 void Sema::LoadExternalVTableUses() { 15325 if (!ExternalSource) 15326 return; 15327 15328 SmallVector<ExternalVTableUse, 4> VTables; 15329 ExternalSource->ReadUsedVTables(VTables); 15330 SmallVector<VTableUse, 4> NewUses; 15331 for (unsigned I = 0, N = VTables.size(); I != N; ++I) { 15332 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos 15333 = VTablesUsed.find(VTables[I].Record); 15334 // Even if a definition wasn't required before, it may be required now. 15335 if (Pos != VTablesUsed.end()) { 15336 if (!Pos->second && VTables[I].DefinitionRequired) 15337 Pos->second = true; 15338 continue; 15339 } 15340 15341 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired; 15342 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location)); 15343 } 15344 15345 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end()); 15346 } 15347 15348 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 15349 bool DefinitionRequired) { 15350 // Ignore any vtable uses in unevaluated operands or for classes that do 15351 // not have a vtable. 15352 if (!Class->isDynamicClass() || Class->isDependentContext() || 15353 CurContext->isDependentContext() || isUnevaluatedContext()) 15354 return; 15355 // Do not mark as used if compiling for the device outside of the target 15356 // region. 15357 if (LangOpts.OpenMP && LangOpts.OpenMPIsDevice && 15358 !isInOpenMPDeclareTargetContext() && 15359 !isInOpenMPTargetExecutionDirective()) { 15360 if (!DefinitionRequired) 15361 MarkVirtualMembersReferenced(Loc, Class); 15362 return; 15363 } 15364 15365 // Try to insert this class into the map. 15366 LoadExternalVTableUses(); 15367 Class = Class->getCanonicalDecl(); 15368 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool> 15369 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired)); 15370 if (!Pos.second) { 15371 // If we already had an entry, check to see if we are promoting this vtable 15372 // to require a definition. If so, we need to reappend to the VTableUses 15373 // list, since we may have already processed the first entry. 15374 if (DefinitionRequired && !Pos.first->second) { 15375 Pos.first->second = true; 15376 } else { 15377 // Otherwise, we can early exit. 15378 return; 15379 } 15380 } else { 15381 // The Microsoft ABI requires that we perform the destructor body 15382 // checks (i.e. operator delete() lookup) when the vtable is marked used, as 15383 // the deleting destructor is emitted with the vtable, not with the 15384 // destructor definition as in the Itanium ABI. 15385 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 15386 CXXDestructorDecl *DD = Class->getDestructor(); 15387 if (DD && DD->isVirtual() && !DD->isDeleted()) { 15388 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) { 15389 // If this is an out-of-line declaration, marking it referenced will 15390 // not do anything. Manually call CheckDestructor to look up operator 15391 // delete(). 15392 ContextRAII SavedContext(*this, DD); 15393 CheckDestructor(DD); 15394 } else { 15395 MarkFunctionReferenced(Loc, Class->getDestructor()); 15396 } 15397 } 15398 } 15399 } 15400 15401 // Local classes need to have their virtual members marked 15402 // immediately. For all other classes, we mark their virtual members 15403 // at the end of the translation unit. 15404 if (Class->isLocalClass()) 15405 MarkVirtualMembersReferenced(Loc, Class); 15406 else 15407 VTableUses.push_back(std::make_pair(Class, Loc)); 15408 } 15409 15410 bool Sema::DefineUsedVTables() { 15411 LoadExternalVTableUses(); 15412 if (VTableUses.empty()) 15413 return false; 15414 15415 // Note: The VTableUses vector could grow as a result of marking 15416 // the members of a class as "used", so we check the size each 15417 // time through the loop and prefer indices (which are stable) to 15418 // iterators (which are not). 15419 bool DefinedAnything = false; 15420 for (unsigned I = 0; I != VTableUses.size(); ++I) { 15421 CXXRecordDecl *Class = VTableUses[I].first->getDefinition(); 15422 if (!Class) 15423 continue; 15424 TemplateSpecializationKind ClassTSK = 15425 Class->getTemplateSpecializationKind(); 15426 15427 SourceLocation Loc = VTableUses[I].second; 15428 15429 bool DefineVTable = true; 15430 15431 // If this class has a key function, but that key function is 15432 // defined in another translation unit, we don't need to emit the 15433 // vtable even though we're using it. 15434 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class); 15435 if (KeyFunction && !KeyFunction->hasBody()) { 15436 // The key function is in another translation unit. 15437 DefineVTable = false; 15438 TemplateSpecializationKind TSK = 15439 KeyFunction->getTemplateSpecializationKind(); 15440 assert(TSK != TSK_ExplicitInstantiationDefinition && 15441 TSK != TSK_ImplicitInstantiation && 15442 "Instantiations don't have key functions"); 15443 (void)TSK; 15444 } else if (!KeyFunction) { 15445 // If we have a class with no key function that is the subject 15446 // of an explicit instantiation declaration, suppress the 15447 // vtable; it will live with the explicit instantiation 15448 // definition. 15449 bool IsExplicitInstantiationDeclaration = 15450 ClassTSK == TSK_ExplicitInstantiationDeclaration; 15451 for (auto R : Class->redecls()) { 15452 TemplateSpecializationKind TSK 15453 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind(); 15454 if (TSK == TSK_ExplicitInstantiationDeclaration) 15455 IsExplicitInstantiationDeclaration = true; 15456 else if (TSK == TSK_ExplicitInstantiationDefinition) { 15457 IsExplicitInstantiationDeclaration = false; 15458 break; 15459 } 15460 } 15461 15462 if (IsExplicitInstantiationDeclaration) 15463 DefineVTable = false; 15464 } 15465 15466 // The exception specifications for all virtual members may be needed even 15467 // if we are not providing an authoritative form of the vtable in this TU. 15468 // We may choose to emit it available_externally anyway. 15469 if (!DefineVTable) { 15470 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class); 15471 continue; 15472 } 15473 15474 // Mark all of the virtual members of this class as referenced, so 15475 // that we can build a vtable. Then, tell the AST consumer that a 15476 // vtable for this class is required. 15477 DefinedAnything = true; 15478 MarkVirtualMembersReferenced(Loc, Class); 15479 CXXRecordDecl *Canonical = Class->getCanonicalDecl(); 15480 if (VTablesUsed[Canonical]) 15481 Consumer.HandleVTable(Class); 15482 15483 // Warn if we're emitting a weak vtable. The vtable will be weak if there is 15484 // no key function or the key function is inlined. Don't warn in C++ ABIs 15485 // that lack key functions, since the user won't be able to make one. 15486 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() && 15487 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) { 15488 const FunctionDecl *KeyFunctionDef = nullptr; 15489 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) && 15490 KeyFunctionDef->isInlined())) { 15491 Diag(Class->getLocation(), 15492 ClassTSK == TSK_ExplicitInstantiationDefinition 15493 ? diag::warn_weak_template_vtable 15494 : diag::warn_weak_vtable) 15495 << Class; 15496 } 15497 } 15498 } 15499 VTableUses.clear(); 15500 15501 return DefinedAnything; 15502 } 15503 15504 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 15505 const CXXRecordDecl *RD) { 15506 for (const auto *I : RD->methods()) 15507 if (I->isVirtual() && !I->isPure()) 15508 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>()); 15509 } 15510 15511 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc, 15512 const CXXRecordDecl *RD, 15513 bool ConstexprOnly) { 15514 // Mark all functions which will appear in RD's vtable as used. 15515 CXXFinalOverriderMap FinalOverriders; 15516 RD->getFinalOverriders(FinalOverriders); 15517 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(), 15518 E = FinalOverriders.end(); 15519 I != E; ++I) { 15520 for (OverridingMethods::const_iterator OI = I->second.begin(), 15521 OE = I->second.end(); 15522 OI != OE; ++OI) { 15523 assert(OI->second.size() > 0 && "no final overrider"); 15524 CXXMethodDecl *Overrider = OI->second.front().Method; 15525 15526 // C++ [basic.def.odr]p2: 15527 // [...] A virtual member function is used if it is not pure. [...] 15528 if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr())) 15529 MarkFunctionReferenced(Loc, Overrider); 15530 } 15531 } 15532 15533 // Only classes that have virtual bases need a VTT. 15534 if (RD->getNumVBases() == 0) 15535 return; 15536 15537 for (const auto &I : RD->bases()) { 15538 const CXXRecordDecl *Base = 15539 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); 15540 if (Base->getNumVBases() == 0) 15541 continue; 15542 MarkVirtualMembersReferenced(Loc, Base); 15543 } 15544 } 15545 15546 /// SetIvarInitializers - This routine builds initialization ASTs for the 15547 /// Objective-C implementation whose ivars need be initialized. 15548 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) { 15549 if (!getLangOpts().CPlusPlus) 15550 return; 15551 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) { 15552 SmallVector<ObjCIvarDecl*, 8> ivars; 15553 CollectIvarsToConstructOrDestruct(OID, ivars); 15554 if (ivars.empty()) 15555 return; 15556 SmallVector<CXXCtorInitializer*, 32> AllToInit; 15557 for (unsigned i = 0; i < ivars.size(); i++) { 15558 FieldDecl *Field = ivars[i]; 15559 if (Field->isInvalidDecl()) 15560 continue; 15561 15562 CXXCtorInitializer *Member; 15563 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field); 15564 InitializationKind InitKind = 15565 InitializationKind::CreateDefault(ObjCImplementation->getLocation()); 15566 15567 InitializationSequence InitSeq(*this, InitEntity, InitKind, None); 15568 ExprResult MemberInit = 15569 InitSeq.Perform(*this, InitEntity, InitKind, None); 15570 MemberInit = MaybeCreateExprWithCleanups(MemberInit); 15571 // Note, MemberInit could actually come back empty if no initialization 15572 // is required (e.g., because it would call a trivial default constructor) 15573 if (!MemberInit.get() || MemberInit.isInvalid()) 15574 continue; 15575 15576 Member = 15577 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(), 15578 SourceLocation(), 15579 MemberInit.getAs<Expr>(), 15580 SourceLocation()); 15581 AllToInit.push_back(Member); 15582 15583 // Be sure that the destructor is accessible and is marked as referenced. 15584 if (const RecordType *RecordTy = 15585 Context.getBaseElementType(Field->getType()) 15586 ->getAs<RecordType>()) { 15587 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl()); 15588 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 15589 MarkFunctionReferenced(Field->getLocation(), Destructor); 15590 CheckDestructorAccess(Field->getLocation(), Destructor, 15591 PDiag(diag::err_access_dtor_ivar) 15592 << Context.getBaseElementType(Field->getType())); 15593 } 15594 } 15595 } 15596 ObjCImplementation->setIvarInitializers(Context, 15597 AllToInit.data(), AllToInit.size()); 15598 } 15599 } 15600 15601 static 15602 void DelegatingCycleHelper(CXXConstructorDecl* Ctor, 15603 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid, 15604 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid, 15605 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current, 15606 Sema &S) { 15607 if (Ctor->isInvalidDecl()) 15608 return; 15609 15610 CXXConstructorDecl *Target = Ctor->getTargetConstructor(); 15611 15612 // Target may not be determinable yet, for instance if this is a dependent 15613 // call in an uninstantiated template. 15614 if (Target) { 15615 const FunctionDecl *FNTarget = nullptr; 15616 (void)Target->hasBody(FNTarget); 15617 Target = const_cast<CXXConstructorDecl*>( 15618 cast_or_null<CXXConstructorDecl>(FNTarget)); 15619 } 15620 15621 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(), 15622 // Avoid dereferencing a null pointer here. 15623 *TCanonical = Target? Target->getCanonicalDecl() : nullptr; 15624 15625 if (!Current.insert(Canonical).second) 15626 return; 15627 15628 // We know that beyond here, we aren't chaining into a cycle. 15629 if (!Target || !Target->isDelegatingConstructor() || 15630 Target->isInvalidDecl() || Valid.count(TCanonical)) { 15631 Valid.insert(Current.begin(), Current.end()); 15632 Current.clear(); 15633 // We've hit a cycle. 15634 } else if (TCanonical == Canonical || Invalid.count(TCanonical) || 15635 Current.count(TCanonical)) { 15636 // If we haven't diagnosed this cycle yet, do so now. 15637 if (!Invalid.count(TCanonical)) { 15638 S.Diag((*Ctor->init_begin())->getSourceLocation(), 15639 diag::warn_delegating_ctor_cycle) 15640 << Ctor; 15641 15642 // Don't add a note for a function delegating directly to itself. 15643 if (TCanonical != Canonical) 15644 S.Diag(Target->getLocation(), diag::note_it_delegates_to); 15645 15646 CXXConstructorDecl *C = Target; 15647 while (C->getCanonicalDecl() != Canonical) { 15648 const FunctionDecl *FNTarget = nullptr; 15649 (void)C->getTargetConstructor()->hasBody(FNTarget); 15650 assert(FNTarget && "Ctor cycle through bodiless function"); 15651 15652 C = const_cast<CXXConstructorDecl*>( 15653 cast<CXXConstructorDecl>(FNTarget)); 15654 S.Diag(C->getLocation(), diag::note_which_delegates_to); 15655 } 15656 } 15657 15658 Invalid.insert(Current.begin(), Current.end()); 15659 Current.clear(); 15660 } else { 15661 DelegatingCycleHelper(Target, Valid, Invalid, Current, S); 15662 } 15663 } 15664 15665 15666 void Sema::CheckDelegatingCtorCycles() { 15667 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current; 15668 15669 for (DelegatingCtorDeclsType::iterator 15670 I = DelegatingCtorDecls.begin(ExternalSource), 15671 E = DelegatingCtorDecls.end(); 15672 I != E; ++I) 15673 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this); 15674 15675 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI) 15676 (*CI)->setInvalidDecl(); 15677 } 15678 15679 namespace { 15680 /// AST visitor that finds references to the 'this' expression. 15681 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> { 15682 Sema &S; 15683 15684 public: 15685 explicit FindCXXThisExpr(Sema &S) : S(S) { } 15686 15687 bool VisitCXXThisExpr(CXXThisExpr *E) { 15688 S.Diag(E->getLocation(), diag::err_this_static_member_func) 15689 << E->isImplicit(); 15690 return false; 15691 } 15692 }; 15693 } 15694 15695 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) { 15696 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 15697 if (!TSInfo) 15698 return false; 15699 15700 TypeLoc TL = TSInfo->getTypeLoc(); 15701 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 15702 if (!ProtoTL) 15703 return false; 15704 15705 // C++11 [expr.prim.general]p3: 15706 // [The expression this] shall not appear before the optional 15707 // cv-qualifier-seq and it shall not appear within the declaration of a 15708 // static member function (although its type and value category are defined 15709 // within a static member function as they are within a non-static member 15710 // function). [ Note: this is because declaration matching does not occur 15711 // until the complete declarator is known. - end note ] 15712 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 15713 FindCXXThisExpr Finder(*this); 15714 15715 // If the return type came after the cv-qualifier-seq, check it now. 15716 if (Proto->hasTrailingReturn() && 15717 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc())) 15718 return true; 15719 15720 // Check the exception specification. 15721 if (checkThisInStaticMemberFunctionExceptionSpec(Method)) 15722 return true; 15723 15724 return checkThisInStaticMemberFunctionAttributes(Method); 15725 } 15726 15727 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) { 15728 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo(); 15729 if (!TSInfo) 15730 return false; 15731 15732 TypeLoc TL = TSInfo->getTypeLoc(); 15733 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>(); 15734 if (!ProtoTL) 15735 return false; 15736 15737 const FunctionProtoType *Proto = ProtoTL.getTypePtr(); 15738 FindCXXThisExpr Finder(*this); 15739 15740 switch (Proto->getExceptionSpecType()) { 15741 case EST_Unparsed: 15742 case EST_Uninstantiated: 15743 case EST_Unevaluated: 15744 case EST_BasicNoexcept: 15745 case EST_NoThrow: 15746 case EST_DynamicNone: 15747 case EST_MSAny: 15748 case EST_None: 15749 break; 15750 15751 case EST_DependentNoexcept: 15752 case EST_NoexceptFalse: 15753 case EST_NoexceptTrue: 15754 if (!Finder.TraverseStmt(Proto->getNoexceptExpr())) 15755 return true; 15756 LLVM_FALLTHROUGH; 15757 15758 case EST_Dynamic: 15759 for (const auto &E : Proto->exceptions()) { 15760 if (!Finder.TraverseType(E)) 15761 return true; 15762 } 15763 break; 15764 } 15765 15766 return false; 15767 } 15768 15769 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) { 15770 FindCXXThisExpr Finder(*this); 15771 15772 // Check attributes. 15773 for (const auto *A : Method->attrs()) { 15774 // FIXME: This should be emitted by tblgen. 15775 Expr *Arg = nullptr; 15776 ArrayRef<Expr *> Args; 15777 if (const auto *G = dyn_cast<GuardedByAttr>(A)) 15778 Arg = G->getArg(); 15779 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A)) 15780 Arg = G->getArg(); 15781 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A)) 15782 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size()); 15783 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A)) 15784 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size()); 15785 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) { 15786 Arg = ETLF->getSuccessValue(); 15787 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size()); 15788 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) { 15789 Arg = STLF->getSuccessValue(); 15790 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size()); 15791 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A)) 15792 Arg = LR->getArg(); 15793 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A)) 15794 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size()); 15795 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A)) 15796 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 15797 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A)) 15798 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 15799 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A)) 15800 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size()); 15801 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A)) 15802 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size()); 15803 15804 if (Arg && !Finder.TraverseStmt(Arg)) 15805 return true; 15806 15807 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 15808 if (!Finder.TraverseStmt(Args[I])) 15809 return true; 15810 } 15811 } 15812 15813 return false; 15814 } 15815 15816 void Sema::checkExceptionSpecification( 15817 bool IsTopLevel, ExceptionSpecificationType EST, 15818 ArrayRef<ParsedType> DynamicExceptions, 15819 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, 15820 SmallVectorImpl<QualType> &Exceptions, 15821 FunctionProtoType::ExceptionSpecInfo &ESI) { 15822 Exceptions.clear(); 15823 ESI.Type = EST; 15824 if (EST == EST_Dynamic) { 15825 Exceptions.reserve(DynamicExceptions.size()); 15826 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) { 15827 // FIXME: Preserve type source info. 15828 QualType ET = GetTypeFromParser(DynamicExceptions[ei]); 15829 15830 if (IsTopLevel) { 15831 SmallVector<UnexpandedParameterPack, 2> Unexpanded; 15832 collectUnexpandedParameterPacks(ET, Unexpanded); 15833 if (!Unexpanded.empty()) { 15834 DiagnoseUnexpandedParameterPacks( 15835 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType, 15836 Unexpanded); 15837 continue; 15838 } 15839 } 15840 15841 // Check that the type is valid for an exception spec, and 15842 // drop it if not. 15843 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei])) 15844 Exceptions.push_back(ET); 15845 } 15846 ESI.Exceptions = Exceptions; 15847 return; 15848 } 15849 15850 if (isComputedNoexcept(EST)) { 15851 assert((NoexceptExpr->isTypeDependent() || 15852 NoexceptExpr->getType()->getCanonicalTypeUnqualified() == 15853 Context.BoolTy) && 15854 "Parser should have made sure that the expression is boolean"); 15855 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) { 15856 ESI.Type = EST_BasicNoexcept; 15857 return; 15858 } 15859 15860 ESI.NoexceptExpr = NoexceptExpr; 15861 return; 15862 } 15863 } 15864 15865 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD, 15866 ExceptionSpecificationType EST, 15867 SourceRange SpecificationRange, 15868 ArrayRef<ParsedType> DynamicExceptions, 15869 ArrayRef<SourceRange> DynamicExceptionRanges, 15870 Expr *NoexceptExpr) { 15871 if (!MethodD) 15872 return; 15873 15874 // Dig out the method we're referring to. 15875 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD)) 15876 MethodD = FunTmpl->getTemplatedDecl(); 15877 15878 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD); 15879 if (!Method) 15880 return; 15881 15882 // Check the exception specification. 15883 llvm::SmallVector<QualType, 4> Exceptions; 15884 FunctionProtoType::ExceptionSpecInfo ESI; 15885 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions, 15886 DynamicExceptionRanges, NoexceptExpr, Exceptions, 15887 ESI); 15888 15889 // Update the exception specification on the function type. 15890 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true); 15891 15892 if (Method->isStatic()) 15893 checkThisInStaticMemberFunctionExceptionSpec(Method); 15894 15895 if (Method->isVirtual()) { 15896 // Check overrides, which we previously had to delay. 15897 for (const CXXMethodDecl *O : Method->overridden_methods()) 15898 CheckOverridingFunctionExceptionSpec(Method, O); 15899 } 15900 } 15901 15902 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class. 15903 /// 15904 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record, 15905 SourceLocation DeclStart, Declarator &D, 15906 Expr *BitWidth, 15907 InClassInitStyle InitStyle, 15908 AccessSpecifier AS, 15909 const ParsedAttr &MSPropertyAttr) { 15910 IdentifierInfo *II = D.getIdentifier(); 15911 if (!II) { 15912 Diag(DeclStart, diag::err_anonymous_property); 15913 return nullptr; 15914 } 15915 SourceLocation Loc = D.getIdentifierLoc(); 15916 15917 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 15918 QualType T = TInfo->getType(); 15919 if (getLangOpts().CPlusPlus) { 15920 CheckExtraCXXDefaultArguments(D); 15921 15922 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 15923 UPPC_DataMemberType)) { 15924 D.setInvalidType(); 15925 T = Context.IntTy; 15926 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 15927 } 15928 } 15929 15930 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 15931 15932 if (D.getDeclSpec().isInlineSpecified()) 15933 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 15934 << getLangOpts().CPlusPlus17; 15935 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 15936 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 15937 diag::err_invalid_thread) 15938 << DeclSpec::getSpecifierName(TSCS); 15939 15940 // Check to see if this name was declared as a member previously 15941 NamedDecl *PrevDecl = nullptr; 15942 LookupResult Previous(*this, II, Loc, LookupMemberName, 15943 ForVisibleRedeclaration); 15944 LookupName(Previous, S); 15945 switch (Previous.getResultKind()) { 15946 case LookupResult::Found: 15947 case LookupResult::FoundUnresolvedValue: 15948 PrevDecl = Previous.getAsSingle<NamedDecl>(); 15949 break; 15950 15951 case LookupResult::FoundOverloaded: 15952 PrevDecl = Previous.getRepresentativeDecl(); 15953 break; 15954 15955 case LookupResult::NotFound: 15956 case LookupResult::NotFoundInCurrentInstantiation: 15957 case LookupResult::Ambiguous: 15958 break; 15959 } 15960 15961 if (PrevDecl && PrevDecl->isTemplateParameter()) { 15962 // Maybe we will complain about the shadowed template parameter. 15963 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 15964 // Just pretend that we didn't see the previous declaration. 15965 PrevDecl = nullptr; 15966 } 15967 15968 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 15969 PrevDecl = nullptr; 15970 15971 SourceLocation TSSL = D.getBeginLoc(); 15972 MSPropertyDecl *NewPD = 15973 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL, 15974 MSPropertyAttr.getPropertyDataGetter(), 15975 MSPropertyAttr.getPropertyDataSetter()); 15976 ProcessDeclAttributes(TUScope, NewPD, D); 15977 NewPD->setAccess(AS); 15978 15979 if (NewPD->isInvalidDecl()) 15980 Record->setInvalidDecl(); 15981 15982 if (D.getDeclSpec().isModulePrivateSpecified()) 15983 NewPD->setModulePrivate(); 15984 15985 if (NewPD->isInvalidDecl() && PrevDecl) { 15986 // Don't introduce NewFD into scope; there's already something 15987 // with the same name in the same scope. 15988 } else if (II) { 15989 PushOnScopeChains(NewPD, S); 15990 } else 15991 Record->addDecl(NewPD); 15992 15993 return NewPD; 15994 } 15995